input
stringlengths
29
13k
output
stringlengths
9
73.4k
Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas. His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words. <image> He ate coffee mi...
l=['','-one','-two','-three','-four','-five','-six','-seven','-eight','-nine'] l1=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'] l2=['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety'] l3=['zero','one','two','three','four','five','six','seven','e...
Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them wi...
#include <bits/stdc++.h> using namespace std; long long a[5]; char c[5]; int main() { for (int i = 0; i < 4; i++) cin >> a[i]; for (int i = 0; i < 3; i++) cin >> c[i]; long long ans = 2e18, b1, b2, b3, b4, b5, b6, d1, d2, d3, e1, e2, e3, r1, r2, r3, q1, q2, q3, w1, w2, w3, t1, t2, t3; if (c[0] == '+...
Vitalik the philatelist has a birthday today! As he is a regular customer in a stamp store called 'Robin Bobin', the store management decided to make him a gift. Vitalik wants to buy one stamp and the store will give him a non-empty set of the remaining stamps, such that the greatest common divisor (GCD) of the price...
#include <bits/stdc++.h> using namespace std; const int N = 500100, mod = 1e9 + 7, M = 10000001; int f[N], p[M], tot, c[M], mu[M], a[N], b[N][20], bn[N]; bool is[M]; int cal(int x) { return f[x] - 1; } void add(int &x, int y) { if (y < 0) y += mod; x += y; if (x >= mod) x -= mod; } int main() { f[0] = 1; for ...
Genos has been given n distinct lines on the Cartesian plane. Let <image> be a list of intersection points of these lines. A single point might appear multiple times in this list if it is the intersection of multiple pairs of lines. The order of the list does not matter. Given a query point (p, q), let <image> be the ...
#include <bits/stdc++.h> using namespace std; int n, m; double x, y, a[50050], b[50050], ans; struct data { double angle; int id; friend bool operator<(data a, data b) { return a.angle < b.angle; } } d[100010]; int cnt, last[50050]; int sum[100010]; inline void add(int p, int w) { while (p <= cnt) sum[p] += w, ...
As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake. Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special ca...
def setmax(a, i, v): while i < len(a): a[i] = max(a[i], v) i |= i + 1 def getmax(a, i): r = 0 while i > 0: r = max(r, a[i-1]) i &= i - 1 return r def his(l): maxbit = [0] * len(l) rank = [0] * len(l) for i, j in enumerate(sorted(range(len(l)), key=lambda i: ...
A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n. Limak is a little polar bear. He once had a tree with n vertices but he lost it. He still remembers something about the lost tree though. You are given m pairs of vertices (a1, b1), (a2, b2), ..., (am, ...
#include <bits/stdc++.h> using namespace std; using namespace std; const int N = 300500; int n, m, k; int sz; int p[N]; int cnt[N]; bool used[N]; int todel[N]; vector<int> g[N]; bool cmp(int x, int y) { return cnt[x] < cnt[y]; } void solve() { queue<int> q; for (int i = 1; i <= n; i++) { used[i] = false; } ...
You have a grid with n rows and n columns. Each cell is either empty (denoted by '.') or blocked (denoted by 'X'). Two empty cells are directly connected if they share a side. Two cells (r1, c1) (located in the row r1 and column c1) and (r2, c2) are connected if there exists a sequence of empty cells that starts with ...
#include <bits/stdc++.h> using namespace std; const int N = 505; int c[N][N], sz[N * N], mp[N * N], dp[N][N]; int n, cn; bool vis[N][N]; string s[N]; void dfs(int x, int y) { if (x < 0 || y < 0 || x >= n || y >= n || vis[x][y] || s[x][y] == 'X') return; vis[x][y] = true; c[x][y] = cn; sz[cn]++; dfs(x - 1, y);...
On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe...
#include <bits/stdc++.h> using namespace std; int n, k; double l, v1, v2; double binser(double target) { return target / (v1 + v2); } double msafa; double solve(double start, double End, int students) { if (start >= End) { msafa = End; return 0; } if (students == 0) { msafa = min(start + 0.0001, End);...
There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads. ...
#include <bits/stdc++.h> using namespace std; template <typename Arg1> void __f(const char* name, Arg1&& arg1) { cerr << name << " : " << arg1 << std::endl; } template <typename Arg1, typename... Args> void __f(const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr(names + 1, ','); cerr.writ...
This is an interactive problem. In the interaction section below you will see the information about flushing the output. In this problem, you will be playing a game with Hongcow. How lucky of you! Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and col...
#include <bits/stdc++.h> using namespace std; int N, used[1007]; void read() { scanf("%d", &N); } vector<int> grp1, grp2; int result[1007]; void process() { for (int i = 1; i <= N; i++) result[i] = 0x7fffffff; for (int i = 512; i > 0; i /= 2) if (i < N) { grp1.clear(); grp2.clear(); for (int j...
Tarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two s...
#include <bits/stdc++.h> using namespace std; int f, w, h; const int mod = 1e9 + 7; int ac, all; int fastpow(int x, int a) { int ret = 1; while (a) { if (a & 1) ret = 1LL * ret * x % mod; x = x * 1LL * x % mod; a >>= 1; } return ret; } struct Combin { int fac[200005], rv[200005], facrv[200005]; ...
There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that: * each ball belongs to exactly one of the sets, * there are no empty sets, * there is no set con...
#include <bits/stdc++.h> #pragma GCC optimize("O2") #pragma GCC optimize("unroll-loops,no-stack-protector") #pragma GCC target("avx,avx2,sse,sse2,fma,tune=native") using namespace std; using ll = long long; using vi = vector<ll>; using pi = pair<ll, ll>; using vpi = vector<pi>; using ld = long double; const int maxn = ...
Unlucky year in Berland is such a year that its number n can be represented as n = xa + yb, where a and b are non-negative integer numbers. For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 20 + 31, 17 = 23 + 32 = 24 + 30) and year 18 isn't unlucky as there is no such representation for it. Su...
#include <bits/stdc++.h> using namespace std; vector<long long> pa, pb; vector<long long> njp; int main() { long long x, y, l, r; cin >> x >> y >> l >> r; pa.push_back(1); for (long long p = 1; p <= r / x; p *= x) { pa.push_back(p * x); } pb.push_back(1); for (long long p = 1; p <= r / y; p *= y) { ...
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies. At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand...
n,k=map(int,raw_input().split()) a=map(int,raw_input().split()) r=0 for i in range(n): r+=a[i] x=min(r,8) k-=x r-=x if k<=0: print i+1 exit(0) print -1
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - ...
#include <bits/stdc++.h> using namespace std; double A[128][128], dp[7][128], P[7][128]; int main() { int n; cin >> n; for (int i = 0; i < int((1 << n)); i++) for (int j = 0; j < int((1 << n)); j++) { cin >> A[i][j]; A[i][j] /= 100.0; } for (int i = 0; i < int((1 << n)); i++) P[0][i] = 1.0; ...
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself. There are n stations in the subway. It was built according to the Bertown Transport Law: 1. For each station i there exists exactly one train that goes from this station. I...
import java.math.*; import java.util.*; public class Main { static class Max { long val; long key; public Max(long value,long Key){ val=value; key=Key; } public long getKey() { return key; } public long getVal() { ...
You are given an integer m. Let M = 2m - 1. You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m. A set of integers S is called "good" if the following hold. 1. If <image>, then <image>. 2. If <image>, then <image> 3. <image> ...
#include <bits/stdc++.h> using namespace std; int n, m; string a[1007]; long long mask[1007]; long long dp[1007][1007]; long long hh[1007]; void input() { cin >> m >> n; for (int i = 0; i < n; ++i) { cin >> a[i]; for (int j = 0; j < m; ++j) { if (a[i][j] == '1') { mask[j] += (1LL << i); ...
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai. The i-th walrus becomes displeased if there's a younger walrus stan...
#include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int, int>; mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); template <class Ty> Ty randint(Ty a, Ty b) { return uniform_int_distribution<Ty>(a, b)(rng); } template <class T> void DBG(T&& x) { cerr << x << " "; }...
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets. The Galaxy contains N planets, connected by bidirectional hyperspace tunnels i...
#include <bits/stdc++.h> using namespace std; bool vis[100008]; int tmp, head[100008], pre[100008]; struct edge { int u, v, nxt; } e[100008 * 2]; struct node { int d, id, k; } p[100008]; void adde(int, int); void init(int, int); inline int del(int, int); bool cmp(node a, node b) { return a.d > b.d; } int main() { ...
Arkady has got an infinite plane painted in color 0. Then he draws n rectangles filled with paint with sides parallel to the Cartesian coordinate axes, one after another. The color of the i-th rectangle is i (rectangles are enumerated from 1 to n in the order he draws them). It is possible that new rectangles cover som...
#include <bits/stdc++.h> using namespace std; int N; priority_queue<int> X[800005 * 2]; struct Event { int x, y1, y2, type, color; } E[200005]; struct Query { int x1, y1, x2, y2; } Q[100005]; int cnt; pair<int, int> Range[200005]; map<int, int> Mx, My; int Min[800005 * 2], Max[800005 * 2]; bool seen[200005], Erased...
Oz has a list arr[] of M integers. He has to find all integers K such that : 1) K > 1 2) arr[1]%K = arr[2]%K = arr[3]%K = ... = arr[M]%K where '%' is a modulus operator Help Oz to find all such K's. Input : First line of input contains an integer M. Then M lines follow each containing one integer of the list. Input ...
from math import sqrt def check_k(ls, k): v = ls[0] % k for item in ls: if item % k != v: return False return True M = int(raw_input()) l = [] for _ in xrange(M): l.append(int(raw_input())) p = l[0] - l[1] if p < 0: p = -p ks = [] for d in xrange(1, int(sqrt(p) + 1)): if p % d == 0: ...
Paul was the most famous character in Tekken-3. Of course he went to college and stuff. In one of the exams he wasn't able to answer a question which asked to check if a tuple of 3 non negative integers constituted a Primitive Pythagorian Triplet or not. Paul was not able to answer it correctly and henceforth, he coul...
from fractions import gcd def isPithagorean(a, b, c): if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2: return True return False def isCoPrime(a, b, c): if gcd(a,b) == 1 or gcd(a,c) == 1 or gcd(b,c) == 1: return True return False def isPrimitivePythagorean(a, b, c): if isPithagorean(a, b...
Ed, Edd and Eddy are given an art homework. They have to prepare a banner and print a single line of text on it. They can print any text they want. Ed has decided the text that he wants to put on his banner. Lets call it string s1. But he is too lazy to make a new banner all by himself. He borrows an old banner from ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' t=raw_input() t=int(t) arr=[] for i in range(t): str1=raw_input() str2=raw_input() str2.split() if str1 in str2: arr.append("possible") else: arr.append("not possible") for x...
Serena is interested in only red and yellow roses. She is arranging flowers in some fashion to be presented at her friend's birthday. Her friend loves only red and yellow roses(but mostly red ones). The flowers can be arranged only in the following three ways: 1) red 2) red, yellow 3) red, yellow, yellow This sequence...
import fileinput import re flower_regex = re.compile("^(RY{0,2})+$") for line in fileinput.input(): if fileinput.isfirstline(): continue print flower_regex.match(line) and "YES" or "NO"
John is very good in shooting. We wants to get admitted in HackerEarth Shooting Academy (HESA). But HESA take very hard interview process to select the candidates. In the Interview process, an assignment is given to John. In this assignment, some amount X will be given to John. There are some targets to shoot and to f...
t=int(raw_input()) while t>0: t-=1;cnt=0; x,p=(int(i) for i in raw_input().split()) while (x%p==0) and( x!=0): cnt+=1; if x==p: x=0;break; x//=p; print cnt,x;
Milly loves to eat chocolates. She buys only those food items which contain some amount or percentage of chocolate in it. She has purchased N such food items and now she is planning to make a new food item by her own. She will take equal proportions of all of these N food items and mix them. Now she is confused about ...
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' import math for _ in xrange(input()): N=input() l=map(int,raw_input().split()) s=sum(l) le=len(l) out=float(s)/le print '%.8f'%out
You want to repaint your house entirely for an upcoming occasion. The total area of your house is D units. There are a total of N workers. The i^th worker has his available time Ti, hiring cost Xi and speed Yi. This means that he is available for hiring from time Ti and remains available ever since. Once available, yo...
''' Created on 07-Jan-2016 @author: jana ''' import sys class Worker: def __init__(self,T,X,Y): self.T = T self.X = X self.Y = Y def sort_key(a,b): if a.T == b.T: if a.Y == b.Y: return a.X < b.X return a.Y > b.Y return a.T < b.T Worker.__lt__ ...
Given a String(only lower case letters) , check if any substring has occured Twice : Example : iwsagoodboody Here, substring "ood" occurs twice. Output "YES" if there is any such substring else output "NO" .(without qoutes) Input: First line of input consists of an integer T (1 ≤ T ≤ 100) , indicating the numbe...
for t in xrange(input()): s = raw_input() ok = False for i in xrange(len(s)): for j in xrange(i,len(s)): ss = s[i:j] if len(ss)<1: continue if s.count(ss)>=2: #print ss ok = True break if ok: break if ok: print "YES" else: print "NO"
Sonu and Monu are good friends. One day, Sonu gave a binary string of length L to Monu, and asks Monu to pick two positions a and b in the string. Now he given a number P to Monu and he have to tell what are the chances that there will be 1 on both positions and |a-b| ≤ P Note: Binary String means which contains only...
def gcd(a, b): while b: a, b = b, a % b return a t = int(raw_input()) for tt in range(t) : l,p = [int(i) for i in raw_input().split()] a = [int(i) for i in raw_input()] ii = 0 count = [] for e in a : if e == 1 : ii += 1 count.append(ii) else : count.append(ii) ans = 0 for i in rang...
The Tom has become health conscious and is now lifting weights at the gym. But its his first time so the trainer gives him a simple job to do. He has been given a weight lifting rod and N heavy weights, each weighing 2^0, 2^1, .... , 2^n-1. He has to stick each of the "N" weights on the rod, one after another, in such...
for _ in range(input()): n = input() if n < 0: print "0" fact = 1 start= 1 for i in range(1, n+1): fact *= start start += 2 print fact
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types. The type of i-th query is represented by T_i. * T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i. * T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},...
class segtree: ## define what you want to do ,(min, max) sta = -1 func = max def __init__(self,n): self.n = n self.size = 1 << n.bit_length() self.tree = [self.sta]*(2*self.size) def build(self, list): for i,x in enumerate(list,self.size): self.tree[i] =...
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem: * We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k...
from bisect import bisect_left n = int(input()) A = [0] + list(map(int, input().split())) graph = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = map(int, input().split()) graph[v].append(u) graph[u].append(v) start = 1 stack = [1] par = [-1] * (n + 1) ans = [0] * (n + 1) used = [False] * (n + 1...
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i). ...
#include <bits/stdc++.h> using namespace std; /*#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; template<typename T> using gpp_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; template<typename T, typename L> using gpp_map = tre...
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds. Snuke has an integer sequence s, which is initially empty...
#include<bits/stdc++.h> using namespace std; typedef long long ll; const int N = 200005; int a[N],b[N],h[N],to[N]; int n,w; ll K; void solve(int p,int s) { memset(b,0,sizeof(b)); for(int i = 1;i <= s;i ++) { if(!b[a[p]]) h[++ w] = a[p],b[a[p]] = 1; else { while(h[w] != a[p]) b[h[w]] = 0,w --; b[h[...
A museum exhibits N jewels, Jewel 1, 2, ..., N. The coordinates of Jewel i are (x_i, y_i) (the museum can be regarded as a two-dimensional plane), and the value of that jewel is v_i. Snuke the thief will steal some of these jewels. There are M conditions, Condition 1, 2, ..., M, that must be met when stealing jewels,...
#include<cstdio> #include<iostream> #include<cstring> using namespace std; typedef long long ll; const ll N=1005,inf=1e18,M=1e6; ll w[M],ne[M],la[M],len[M],cst[M],t=1; ll d[M],dep[M],s[M],ans,S,T,vis[M],cur[M]; void alink(ll x,ll y,ll z,ll l){ w[++t]=y; ne[t]=la[x]; la[x]=t; len[t]=z; cst[t]=l; } void link(ll x,ll...
Snuke is introducing a robot arm with the following properties to his factory: * The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i. * For each section, its mode ...
N = int(input()) point = [tuple(map(int, input().split())) for i in range(N)] point_farthest = max(point, key=lambda p: abs(p[0]) + abs(p[1])) mod = sum(point_farthest) % 2 D = [1, 1] if mod == 0 else [1] while sum(D) < abs(point_farthest[0]) + abs(point_farthest[1]): D.append(D[-1] * 2) D.reverse() W = [] for x, y...
Let X = 10^{100}. Inaba has N checker pieces on the number line, where the i-th checker piece is at coordinate X^{i} for all 1 \leq i \leq N. Every second, Inaba chooses two checker pieces, A and B, and move A to the symmetric point of its current position with respect to B. After that, B is removed. (It is possible t...
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> #include<ctime> #include<cstdlib> #define cmax(a,b) (a<(b)?a=(b),1:0) #define cmin(a,b) (a>(b)?a=(b),1:0) #define dmin(a,b) ((a)<(b)?(a):(b)) #define dmax(a,b) ((a)>(b)?(a):(b)) #define CL fclose(stdin),fclose(stdout) namespace io { int F() { in...
Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. ...
r=float(input()) g=float(input()) print(int(2*g-r))
There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j). Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there ...
#include<bits/stdc++.h> #define ll long long #define fo(i,x,y) for(int i=x;i<=y;i++) #define fd(i,x,y) for(int i=x;i>=y;i--) using namespace std; const int maxn=107,maxm=5000007; const int inf=0x1fffffff; int n,m,fi[maxm],la[maxm],ne[maxm],va[maxm],tot=1; char a[maxn][maxn]; #define Leaf(x,y) (1+x*m+y-m) #define LEA...
There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct. Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to onl...
mod = 10 ** 9 + 7 N, *E = map(int, open(0).read().split()) E = sorted((e, 2 * (i < N) - 1) for i, e in enumerate(E)) res = 1 cnt = 0 for _, delta in E: if cnt * delta < 0: res *= abs(cnt) res %= mod cnt += delta print(res)
Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K. She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change). However, as mentioned before, she is very ...
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int K = sc.nextInt(); List<Integer> D = new ArrayList<>(); for(int i = 0;i < K;i++) { D.add(sc.nextInt()); ...
The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box. The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes...
#include <iostream> #include <sstream> #include <vector> #include <string> #include <cmath> #include <map> #include <algorithm> using namespace std; int length, n; vector<int> a; map<pair<int,int>, double> memo; double dist(int i, int j) { return sqrt(4 * a[i] * a[j]); } double f(int p, int prev) { if (__bui...
I decided to plant vegetables in the vegetable garden. There were n seeds, so I sown n seeds one by one a day over n days. All seeds sprout and grow quickly. I can't wait for the harvest time. One day, when I was watering the seedlings as usual, I noticed something strange. There should be n vegetable seedlings, but o...
#include<stdio.h> int main(void) { int j,a[101],b[100],i,n,z[99],k,flg; while(1){ scanf("%d",&n); if(n==0){ break; } n++; for(i=0;i<n;i++){ scanf("%d",&a[i]); } for(k=0;k<n;k++){ j=0; for(i=0;i<n;i++){ if(k!=i){ b[j]=a[i]; j++; } } j=0; for(i=1;i<n-1;i++){ z[j]...
problem Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1). input The input consists of multiple datasets. Each dataset is given in the f...
import java.util.Scanner; public class Main { public static class BIT { int[] dat; public BIT(int n){ dat = new int[n + 1]; } public void add(int k, int a){ // k : 0-indexed for(int i = k + 1; i < dat.length; i += i & -i){ dat[i] += a; } } public int sum(int s, int t){ // [s, t)...
When naming identifiers (variables and functions) in programming, compound words that concatenate words are used. However, if you concatenate them as they are, you will not be able to understand the word breaks, so in general, select and apply the one that is unified from the following naming conventions: * Set to Upp...
while True: name,typ = input().split() if typ=="X": break ans = [] if "_" in name: ans = name.split("_") else: j = 0 for i in range(1,len(name)): if name[i].isupper(): ans.append(name[j:i]) j = i ans.append(name[j:]) ...
Chain Disappearance Puzzle We are playing a puzzle. An upright board with H rows by 5 columns of cells, as shown in the figure below, is used in this puzzle. A stone engraved with a digit, one of 1 through 9, is placed in each of the cells. When three or more stones in horizontally adjacent cells are engraved with the...
while 1: H = int(raw_input()) if H == 0: break A = [map(int,raw_input().split())+[0] for _ in range(H)] ans = 0 while 1: vanish = False for h in range(H): l = r = 0 while r < 6: if A[h][r] != A[h][l]: if r-l >= 3: ...
Stylish is a programming language whose syntax comprises names, that are sequences of Latin alphabet letters, three types of grouping symbols, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested pro...
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i)) #define each(itr,c) for(__typeof(c.begin()) itr=c.begin(); itr!=c.end(); ++itr) #define all(x) (x).begin(),(x).end() #define pb push_back #define fi first #define se second const int INF=123456; int...
Problem In a certain universe, stars exist on one-dimensional integer coordinate points, and aliens use the Manhattan warp device to move between stars. This warp device has N buttons, and when you press button i, you can warp any star whose Manhattan distance from the current star is di at cost ci. Now, an alien at p...
#include <algorithm> #include <cfloat> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include <map> #include <memory> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include ...
You are a teacher at a cram school for elementary school pupils. One day, you showed your students how to calculate division of fraction in a class of mathematics. Your lesson was kind and fluent, and it seemed everything was going so well - except for one thing. After some experiences, a student Max got so curious ab...
#include <cstdio> #include <cstring> using namespace std; unsigned char R[1000000][10][3]; int main() { int x,y,c,t; while(scanf("%d %d",&x,&y), (x||y)) { memset(R,0,sizeof(R)); for(c=1; 1; c++) { x*=10; t=x/y; x%=y; if(R[x][t][0] || R[x][t][1] || R[x][t][2]) { break; } R[x][t][0]...
An angel lives in the clouds above the city where Natsume lives. The angel, like Natsume, loves cats and often comes down to the ground to play with cats. To get down to the ground, the angel made a long, long staircase leading from the clouds to the ground. However, the angel thought that it would be boring to just go...
#include <bits/stdc++.h> using namespace std; const int MAXN = 50005; const int MAXM = 50005; const string str[12] = {"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"}; map<string, int> id; int n, m; int T[MAXN], S[MAXM]; bool rec(int k, int p) { if((m - p) * 2 < (n - 1) - k) return false; if(p == m) return ...
Problem statement $ (X_ {1,1} ∨X_ {1,2}) ∧ (X_ {2,1} ∨X_ {2,2}) ∧ ... ∧ (X_ {M, 1} ∨X_ {M,2 }) Given a logical expression represented by $. However, it is $ X_ {i, j} \ in \\ {x_1, x_2, ..., x_N, ~ x_1, ~ x_2, ..., ~ x_N \\} $. I want to assign a boolean value to each variable $ x_i $ ($ 1 \ leq i \ leq N $) so that t...
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Main { static final int MOD = 1000000007; static Scanner sc = new Scanner(System.in); static int N, M; static int[][] pos; static int[][] Y; static long solveCycle(ArrayList<Cell> li...
ICPC World Finals Day 2 Mr. Tee and his colleagues arrived at the airport terminal. From now on, I will transfer the plane and board the enemy land R country. Since we go through Country D, we have to exchange our money into two currencies. Mr. Kay "How does Mr. Tee exchange money?" Mr. Tee "Huff Huff Huff Huff Huff...
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main(void){ ll M; int rated, rater; ll cd, cr; cin >> M >> rated >> rater >> cd >> cr; ll r_xyen = ceil(100.0*(double)cr/(double)rater); ll d_xyen = ceil(100.0*(double)cd/(double)rated); ll r_changed = floor(rater*(double)r_xyen/...
Example Input 3 5 4 3 6 12 Output Hanako
#include <bits/stdc++.h> #define int long long #define N 100010 using namespace std; const int INF = 1LL<<55; int Max(int &a,int b){return a=max(a,b);} int Min(int &a,int b){return a=min(a,b);} int n,A,B,stone[N]; signed main(){ cin>>n>>A>>B; for(int i=0;i<n;i++) cin>>stone[i]; sort(stone,stone+n); int ans ...
coastline Waves rush to the beach every second. There is data that observes and records how many meters the wave rushed beyond the reference point P every second for only T seconds. The data consists of T integers x1, ..., xT, and for each i (1 ≤ i ≤ T), a wave from point P to the point exactly xi m rushes in i second...
#include<iostream> #include<math.h> #include<vector> #include<algorithm> #include<queue> #include<set> #include<map> #define REP(i, n) for(long long i = 0; i < n; ++i) #define ALL(a) a.begin(), a.end() using namespace std; typedef long long ll; typedef pair<ll, ll> P; int main() { while(1) { int t, d, l; cin>>t>>...
C: Short-circuit evaluation problem Naodai-kun and Hokkaido University-kun are playing games. Hokkaido University first generates the following logical formula represented by BNF. <formula> :: = <or-expr> <or-expr> :: = <and-expr> | <or-expr> "|" <and-expr> <and-expr> :: = <term> | <and-expr> "&" <term> <term> :: =...
// vvvvvvvvvvvv TEMPLATE vvvvvvvvvvvv #include <bits/stdc++.h> using namespace std; using ll = long long; using P = pair<ll, ll>; const ll linf = 1e18; const double eps = 1e-12, pi = acos(-1); #define FOR(i,a,b) for (ll i=(a),__last_##i=(b);i<__last_##i;i++) #define RFOR(i,a,b) for (ll i=(b)-1,__last_##i=(a);i>=__last_...
Contest T-shirts Segtree has $ M $ contest T-shirts. He decided to spend $ N $ days on the contest T-shirt alone, and told $ i = 1, 2, 3, \ dots, N $ "$ A_i $ T-shirt on the $ i $ day." I made a plan for $ N $ to wear. However, if you keep the current plan, you may not be able to do the laundry in time, so I would l...
#include<iostream> #include<algorithm> #include<string> #include<vector> #include<cmath> #define int long long #define mod 1000000007 #define for0(i, n) for(int i = 0; i < (n); i++) #define for1(i, n) for(int i = 1; i <= (n);i++) #define mp make_pair using namespace std; int a, b, c, d, m, n, ans; int ar[234567]; strin...
Given a set of $N$ axis-aligned rectangles in the plane, find the area of regions which are covered by at least one rectangle. Constraints * $ 1 \leq N \leq 2000 $ * $ −10^9 \leq x1_i < x2_i\leq 10^9 $ * $ −10^9 \leq y1_i < y2_i\leq 10^9 $ Input The input is given in the following format. $N$ $x1_1$ $y1_1$ $x2_1$ ...
#include <bits/stdc++.h> #include <numeric> #define REP(i, s, n) for (int i = s; i < n; ++i) #define rep(i, n) REP(i, 0, n) #define SORT(c) sort((c).begin(), (c).end()) #define SORT_INV(c) sort((c).begin(), (c).end(), greater<int>()) #define IINF INT_MAX #define LLINF LLONG_MAX #define DEBUG false #define LL long long...
One day Alice visited Byteland to purchase jewels for her upcoming wedding anniversary. In Byteland, every Jewelry shop has their own discount methods to attract the customers. One discount method called Buy1-Get1 caught Alice's attention. That is, Alice buys one jewel, then she can get one additional jewel with the sa...
from collections import Counter for _ in xrange(int(raw_input())): st=raw_input() st=st.strip() a=[] su=0 for let in st: a.append(let) counts=Counter(a) for key in counts: if key!=" " and counts[key]%2==0: counts[key]=counts[key]/2 continue elif key!=" ": counts[key]=(counts[key]+1)/2 co...
On the eve of Diwali, Hari is decorating his house with a serial light bulb set. The serial light bulb set has N bulbs placed sequentially on a string which is programmed to change patterns every second. If atleast one bulb in the set is on at any given instant of time, how many different patterns of light can the seri...
t=int(raw_input()) for i in range(t): n=int(raw_input()) print (pow(2,n,100000)-1%100000)%100000
Problem Statement Chef has a sequence of N segments: [L1, R1], [L2, R2], ..., [LN, RN]. He wants to transform the first segment to the last one (with index N). His plan is to do this big deal with a number of transformations: firstly he will transform the first segment to the second one, then to the third one, then to ...
t=input() while t: t-=1 n=input() l=[0]*(n+1) r=[0]*(n+1) for i in range(n): l[i],r[i]=map(int,raw_input().split()) i=0 count=0 ans="" while i<(n-1): if l[i+1]>=r[i]: ans=ans+"L+"*(r[i]-l[i]-1)+"R+L+"*(l[i+1]-r[i]+1)+"R+"*(r[i+1]-l[i+1]-1) elif r[i...
Problem Statement Maxim likes dividers of the numbers. Also Maxim is fond of lucky numbers of small elephant from Lviv city.   If you remember, lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky, 5, 17, 467 — aren't.   Now ...
''' Maxim and Dividers Problem code: MAANDI Problem Statement Maxim likes dividers of the numbers. Also Maxim is fond of lucky numbers of small elephant from Lviv city. If you remember, lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 4...
Chef is all ready to show his new dish at the restaurant but he is very scared if the people dislike it. He wants to show them his dish at a perfect time, so that all may like the dish. If the time displayed as HH:MM, where HH is the hour and MM is the minute then, for the Chef's time to be lucky it should be of the fo...
for _ in range(input()): s=raw_input().split() c=0 for i in range(len(s)): if s[i][0]==s[i][4] and s[i][1]==s[i][3]: c+=1 elif s[i][0]==s[i][1]and s[i][3]==s[i][4]: c+=1 elif s[i][0]==s[i][3] and s[i][1]==s[i][4]: c+=1 print c
Exciting offer….!!! It’s World Cup time…. :) Here is an offer awaiting for you i.e… you will get a ticket to watch world cup finals @ Australia. Your task is so simple. You will be given a function . In order to win the prize, you need to reduce the time complexity of that function. fun( n) { if (n==0) ...
n=int(input()) def fun( n): if n==0: return 1 if n==1: return 2 return 2*fun(n-1) ans=fun(n) print ans
There is an array with n elements a1, a2, ..., an and the number x. In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the [bitwise and](https://en.wikipedia.org/wiki/Bitwise_operation#AND) operation. You want the array to have at least two equal elements after appl...
import java.util.*; public class And { public static void main(String[] args) { int[] count = new int[1000000]; int[] count2 = new int[1000000]; Scanner in = new Scanner(System.in); int n = in.nextInt(); int x = in.nextInt(); int[] arr = new int[n]; boolean flag = false; for(int i = 0; i < n; i++) ...
Some programming website is establishing a secure communication protocol. For security reasons, they want to choose several more or less random strings. Initially, they have a string s consisting of lowercase English letters. Now they want to choose q strings using the following steps, and you are to help them. 1. ...
#include <bits/stdc++.h> using namespace std; const int N = 200010; int cnt, np; char s[N]; int ch[N][26], fa[N], l[N], rt[N], ls[N * 20], rs[N * 20], w[N], f[N], id[N]; inline int gi() { int x = 0, o = 1; char ch = getchar(); while (ch < '0' || ch > '9') ch == '-' ? o = -1 : 0, ch = getchar(); while (ch >= '0'...
You invited n guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles. Your guests happen to be a little bit shy, so the i-th guest wants to have a least l_i free chairs to the left of his chair, and a...
#include <bits/stdc++.h> using namespace std; int r[100005], l[100005]; int n; int main() { scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d%d", &l[i], &r[i]); sort(l, l + n); sort(r, r + n); long long ans = 0; for (int i = n - 1; i >= 0; i--) { ans += max(l[i], r[i]); } cout << ans + n << end...
Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row. The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as ...
#include <bits/stdc++.h> using namespace std; int n, ans; vector<int> cub; vector<int> seg; vector<pair<int, int> > b; void in() { ios_base::sync_with_stdio(false); cin.tie(0); cin >> n; string s; cin >> s; for (auto c : s) { cub.push_back(c == 'G'); } } void solution() { int st = -1, fn = -1; int...
You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i. Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also ...
import java.io.*; import java.util.*; public class D { public static void main(String[] args) { InputReader in = new InputReader(System.in); PrintWriter out = new PrintWriter(System.out); Solver solver = new Solver(); solver.solve(in, out); out.close(); } private s...
Little Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task. The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any...
#include <bits/stdc++.h> using namespace std; const int N = 1000010; const long long MOD = 1e9 + 7; void solve() { int a, x, y; cin >> a >> x >> y; int k = a / 2; if (x == k && y == k) { cout << "NO" << "\n"; return; } if (x == k + 1 && y == k) { cout << "NO" << "\n"; retur...
Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules: * There are three parts of sp...
#include <bits/stdc++.h> using namespace std; vector<string> words; string texts[2][3] = {{"soil", "rte", "sitini"}, {"alail", "arte", "setini"}}; int getSex() { int sa = -1; int sb = -1; for (int i = int(0); i < int(words.size()); i++) { string cur = words[i]; reverse((cur).begin(), (cur).end()); for...
Let's call beauty of an array b_1, b_2, …, b_n (n > 1) — min_{1 ≤ i < j ≤ n} |b_i - b_j|. You're given an array a_1, a_2, … a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353. A sequence a is a subsequenc...
#include <bits/stdc++.h> using namespace std; template <typename T> ostream& operator<<(ostream& os, const vector<T>& v) { for (auto i : v) os << i << " "; return os; } template <typename T> ostream& operator<<(ostream& os, const set<T>& v) { for (auto i : v) os << i << " "; return os; } const int M = 1e5 + 5; ...
You are given two integers n and k. You need to construct k regular polygons having same [circumcircle](https://en.wikipedia.org/wiki/Circumscribed_circle), with distinct number of sides l between 3 and n. <image> Illustration for the first example. You can rotate them to minimize the total number of distinct point...
import java.io.*; import java.util.*; public class Codeforces1208G { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k =...
Your program fails again. This time it gets "Wrong answer on test 233" . This is the easier version of the problem. In this version 1 ≤ n ≤ 2000. You can hack this problem only if you solve and lock both problems. The problem is about a test containing n one-choice-questions. Each of the questions contains k options...
#include <bits/stdc++.h> using namespace std; const int N = 2010; const long long Mod = 998244353; long long n, m; long long dp[N][N * 2]; int h[N]; int main() { cin >> n >> m; for (int i = 1; i <= n; i++) cin >> h[i]; dp[0][n + 1] = 1; for (int i = 1; i <= n; i++) { if (h[i] == h[i % n + 1]) for (int...
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-read...
#include <bits/stdc++.h> using namespace std; int n, i, j, a[2001][2001], b[2001][2001], ans, J, C, A[2001][2001], B[2001][2001]; char c[2001][2001]; int main() { cin >> n; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) cin >> c[i][j]; memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(A, 0, ...
[THE SxPLAY & KIVΛ - 漂流](https://soundcloud.com/kivawu/hyouryu) [KIVΛ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives) With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space. The space can be considered a 2D plane,...
// javac d.java && java d import java.io.*; import java.util.*; public class d { public static void main(String[] args) { new d(); } FS in = new FS(); PrintWriter out = new PrintWriter(System.out); int sz; long t; long[] pt0, a, b, s; long[][] all, dist; d() { pt0 = new long[2]; for (int i = 0; i < 2; ...
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can: * either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i; * or not choose any posit...
#include <bits/stdc++.h> using namespace std; const int GO_MAX = 26; const int ESP = 1e-9; const int MAX = 100001; const int INF = 1e9; int n, m, k, p, q, t; bool chk[100]; int main() { scanf("%d", &t); while (t--) { scanf("%d %d", &n, &k); bool trig = true; memset(chk, 0, sizeof chk); for (int i = ...
You are given a permutation p consisting of exactly 26 integers from 1 to 26 (since it is a permutation, each integer from 1 to 26 occurs in p exactly once) and two strings s and t consisting of lowercase Latin letters. A substring t' of string t is an occurence of string s if the following conditions are met: 1. |...
#include <bits/stdc++.h> using namespace std; const int N = 3e5 + 10; const long long mod = 998244353; inline long long gcd(long long a, long long b) { return !b ? a : gcd(b, a % b); } inline long long q_pow(long long a, long long x) { long long ans = 1, tmp = a; while (x) { if (x & 1) (ans *= tmp) %= mod; ...
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties... Most of the young explorer...
for i in range(int(input())): n=int(input()) l=list(map(int,input().split())) l.sort() i1,i2=1,0 for j in l: if j==i1: i2+=1 i1=0 i1+=1 print(i2)
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
#!/usr/bin/env python3 def ans(A): A = [abs(a) for a in A] for i in range(1, len(A), 2): if i+1 < len(A): [p, q, r] = A[i-1:i+2] if p <= q <= r: A[i] = -A[i] elif p >= q >= r: A[i] = -A[i] return ' '.join([str(a) for a in A]) T = int(input()) for _ in range(T):...
You are given three multisets of pairs of colored sticks: * R pairs of red sticks, the first pair has length r_1, the second pair has length r_2, ..., the R-th pair has length r_R; * G pairs of green sticks, the first pair has length g_1, the second pair has length g_2, ..., the G-th pair has length g_G; * B ...
import java.io.*; import java.util.*; import java.text.*; import java.lang.*; import java.math.*; public class Solution{ static ArrayList a[] = new ArrayList [3]; static long dp[][][] = new long [201][201][201]; static int len[] = new int [3]; static long f(int x , int y , int z) { if(dp[x][y...
While playing yet another strategy game, Mans has recruited n [Swedish heroes](https://www.youtube.com/watch?v=5sGOwFVUU0I), whose powers which can be represented as an array a. Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to ...
#include <bits/stdc++.h> using namespace std; int n, a[200005]; long long sum[200005], f[200005][3]; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); if (n == 1) { printf("%d", a[1]); return 0; } for (int i = 1; i <= n; i++) if (i & 1) sum[i] = sum[i - 1] + a[i]...
Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot h...
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.StringTokenizer; public class D102 { static StringTokenizer st; static BufferedReader in; public ...
What walks on four feet in the morning, two in the afternoon, and three at night? This is an interactive problem. This problem doesn't support hacks. Sphinx's duty is to guard the city of Thebes by making sure that no unworthy traveler crosses its gates. Only the ones who answer her riddle timely and correctly (or ge...
#include <bits/stdc++.h> #define rep(i,a,b) for(int i = (a); i < (b); ++i) #define rrep(i,a,b) for(int i = (b); i --> (a);) #define sz(v) int(v.size()) using namespace std; string inf, zero; string add(string x, string y, int init){ string res(sz(x), '?'); int todo = init; rrep(i,0,sz(x)){ todo += x[i] + y[i] - ...
There is a trampoline park with n trampolines in a line. The i-th of which has strength S_i. Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice. If at the moment Pekora jumps on trampoline i, the trampoline will launch her to position i + S_i, and S_i wi...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.*; public class Main { static class DisjointUnionSets { int[] rank, parent; int n; // Constructor public DisjointUnionSets(int n) { rank = new int[n];...
You are given 2 arrays a and b, both of size n. You can swap two elements in b at most once (or leave it as it is), and you are required to minimize the value $$$∑_{i}|a_{i}-b_{i}|.$$$ Find the minimum possible value of this sum. Input The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5). The second line c...
#pragma GCC optimize("Ofast") #pragma GCC optimization("unroll-loops, no-stack-protector") #pragma GCC target("avx,avx2,fma") #include <bits/stdc++.h> using namespace std; inline void prep () { cin.tie (0); cin.sync_with_stdio (0); }; // 32 mil = ~1 sec long long mod = 1e9+9; //998244353; const int biggg = 10000...
Note that the memory limit is unusual. There are n chefs numbered 1, 2, …, n that must prepare dishes for a king. Chef i has skill i and initially has a dish of tastiness a_i where |a_i| ≤ i. Each chef has a list of other chefs that he is allowed to copy from. To stop chefs from learning bad habits, the king makes sur...
#include <cstdio> #include <vector> #include <algorithm> #define pb push_back using std::vector; const int N=305, MOD=1000000007; inline int mval(int x) { return x>=MOD?x-MOD:x; } inline int fix(int x) { return x+(x>>31&MOD); } inline void inc(int &x, int a) { x=mval(x+a); } inline void dec(int &x, int a) { x=fix(x-a);...
One must train much to do well on wizardry contests. So, there are numerous wizardry schools and magic fees. One of such magic schools consists of n tours. A winner of each tour gets a huge prize. The school is organised quite far away, so one will have to take all the prizes home in one go. And the bags that you've b...
#include <bits/stdc++.h> using namespace std; template <typename T, typename TT> ostream& operator<<(ostream& s, pair<T, TT> t) { return s << "(" << t.first << "," << t.second << ")"; } template <typename T> ostream& operator<<(ostream& s, vector<T> t) { for (int i = 0; i < t.size(); i++) s << t[i] << " "; return...
You have two positive integers w and h. Your task is to count the number of rhombi which have the following properties: * Have positive area. * With vertices at integer points. * All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points (0, 0), (w, 0), (w, h), (0,...
#include <bits/stdc++.h> using namespace std; void FastInputOutput() { ios_base ::sync_with_stdio(0); cin.tie(0); cout.tie(0); } inline int D() { int t; scanf("%d", &t); return t; } inline long long LLD() { long long t; scanf("%lld", &t); return t; } long long power(long long x, long long p, long long...
We'll call string s[a, b] = sasa + 1... sb (1 ≤ a ≤ b ≤ |s|) a substring of string s = s1s2... s|s|, where |s| is the length of string s. The trace of a non-empty string t is a set of characters that the string consists of. For example, the trace of string "aab" equals {'a', 'b'}. Let's consider an arbitrary string s...
#include <bits/stdc++.h> using namespace std; short fst[1 << 26]; char S[1001000], s[30]; int n, len, a[30], p[30], cnt[10100], y[10100], nxt[10100]; bool cmp(int x, int y) { return a[x] > a[y]; } void add(int t, int i) { y[i] = t; nxt[i] = fst[t]; fst[t] = i; } int main() { scanf("%s%d", S, &n); len = strlen...
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 100). Output Print a singl...
a,b,c=map(int,input().split()) M=1073741824 n=a*b*c d=[1]*(n+1) for i in range(2,n+1): for j in range(i,n+1,i): d[j]+=1 r=0 for i in range(1,a+1): for j in range(1,b+1): for k in range(1,c+1): r+=(d[i*j*k])%M print(r%M)
A country called Flatland is an infinite two-dimensional plane. Flatland has n cities, each of them is a point on the plane. Flatland is ruled by king Circle IV. Circle IV has 9 sons. He wants to give each of his sons part of Flatland to rule. For that, he wants to draw four distinct straight lines, such that two of t...
#include <bits/stdc++.h> using namespace std; const int MAXN = 1e5 + 100; vector<int> seg[(int)(1e6 + 100)]; void add(int first, int second, int xb = 0, int xe = MAXN, int ind = 1) { if (first < xb or first > xe) return; seg[ind].push_back(second); if (xb != xe) { add(first, second, xb, (xb + xe) / 2, ((ind)*...
In the Isle of Guernsey there are n different types of coins. For each i (1 ≤ i ≤ n), coin of type i is worth ai cents. It is possible that ai = aj for some i and j (i ≠ j). Bessie has some set of these coins totaling t cents. She tells Jessie q pairs of integers. For each i (1 ≤ i ≤ q), the pair bi, ci tells Jessie ...
#include <bits/stdc++.h> using namespace std; int arr[310], nex[310], T, N; bool can, isRoot[310]; void dfs(int x, int val) { if (T < 0) return; arr[x] += val; if (nex[x] != -1) { T -= arr[x]; dfs(nex[x], arr[x]); } } long long int memo[310][100000 + 100]; long long int solve(int pos, int val) { if (p...
Information technologies are developing and are increasingly penetrating into all spheres of human activity. Incredible as it is, the most modern technology are used in farming! A large farm has a meadow with grazing sheep. Overall there are n sheep and each of them contains a unique number from 1 to n — because the s...
#include <bits/stdc++.h> using namespace std; int mx[4005], S[4005]; int n, l[4005], r[4005], a[4005]; bool inter(int i, int j) { if (l[i] >= l[j] && l[i] <= r[j]) return 1; if (r[i] >= l[j] && r[i] <= r[j]) return 1; if (l[j] >= l[i] && l[j] <= r[i]) return 1; if (r[j] >= l[i] && r[j] <= r[i]) return 1; retu...
A student's life is fraught with complications. Some Berland University students know this only too well. Having studied for two years, they contracted strong antipathy towards the chairperson of some department. Indeed, the person in question wasn't the kindest of ladies to begin with: prone to reforming groups, banni...
#include <bits/stdc++.h> using namespace std; struct Order { int a, b, id; } order[1000010]; bool cmp1(Order o1, Order o2) { if (o1.a == o2.a && o1.b == o2.b) { return o1.id < o2.id; } if (o2.b == o1.b) return o1.a > o2.a; return o1.b < o2.b; } bool cmp2(Order o1, Order o2) { if (o1.a == o2.a && o1.b ==...
Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms. Vasya needs to collect all these items, however he won't do it by himself. He us...
//Program by Matthew Savage //With help from the TJHSST SCT Grader Example Class import java.io.*; import java.util.*; public class C{ public static void main(String[] args) throws IOException{ //BufferedReader br = new BufferedReader(new FileReader("C.in")); //for testing BufferedReader br = new BufferedReader(...
Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas). ...
#include <bits/stdc++.h> using namespace std; const int N = 60; int k, x, n, m, c[N], s[N], e[N]; string ch = " ACB"; void print(int l, int c, int s, int e) { cout << ch[s]; if (l == 1) return; if (c <= (l - 2) / 2) { for (int i = 0; i < c; i++) cout << "AC"; for (int i = 0; i < l - 2 - 2 * c; i++) cout <...
You take part in the testing of new weapon. For the testing a polygon was created. The polygon is a rectangular field n × m in size, divided into unit squares 1 × 1 in size. The polygon contains k objects, each of which is a rectangle with sides, parallel to the polygon sides and entirely occupying several unit squares...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:16777216") using namespace std; struct rect { int i1, j1, i2, j2; }; int a, b, c, d, i, j, n, m, k; long long ans; char mas[1111][1111]; rect ob[111], ob2[111]; int beg[222]; inline bool cmp_left(const rect &a, const rect &b) { if (a.i1 != b.i1) return a....
Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties: * the upper half of matrix c (rows with numbers from 1 to x) exactly matches b; * the lower half of matrix c (rows with n...
n,m=map(int,raw_input().split()) lst2=[] for _ in range(0,n): lst=map(int,raw_input().split()) lst2.append(lst) if n%2: print n else: while n%2==0: c=0 for i in range(0,n/2): if lst2[i]==lst2[n-i-1]: c=c+1 if c==n/2: n=n/2 else: ...
Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human s...
k,a,b=map(int,input().split()) ss=input() h=len(ss) q,r=divmod(h,k) if q<a or q>b or (q==b and r>0): print('No solution') else: i=0 while r>0: print(ss[i:i+q+1]) r-=1 i=i+q+1 while i<h: print(ss[i:i+q]) i=i+q
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way: ...
l = raw_input().split() ll = [] for x in set(l) : ll.append(l.count(x)) if 6 in ll or ( 2 in ll and 4 in ll ) : print 'Elephant' elif 4 in ll or 5 in ll : print 'Bear' else : print 'Alien'