input
stringlengths
29
13k
output
stringlengths
9
73.4k
Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now t...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class C399 { public static void main(String[] args) { FS scan = new FS(System.in); int N = scan.nextInt(), K = scan.nextInt(), ...
n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ...
#include <bits/stdc++.h> using namespace std; int main() { int n, k; cin >> n >> k; set<int> st; vector<int> v; for (int i = 0; i < n; i++) v.push_back(i); int lead = 0; for (int i = 0; i < k; i++) { int x; cin >> x; n = v.size(); x %= n; int tmp = (lead + x) % n; cout << v[tmp] + ...
Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys: * Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and onl...
#include <bits/stdc++.h> #pragma warning(disable : 4996) #pragma comment(linker, "/stack:200000000") #pragma GCC optimize("Ofast") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") #pragma GCC optimize("-ffloat-store") using namespace std; clock_t time_p = clock(); void aryanc403() { time_...
There is an airplane which has n rows from front to back. There will be m people boarding this airplane. This airplane has an entrance at the very front and very back of the plane. Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the pla...
#include <bits/stdc++.h> using namespace std; const long long mod = 1e9 + 7; long long qpow(long long a, long long b) { long long ans = 1; while (b) { if (b & 1) ans = ans * a % mod; a = a * a % mod; b >>= 1; } return ans; } int main() { long long n, m; scanf("%lld%lld", &n, &m); long long ans...
This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible ...
#!/usr/bin/python3 k = int(input()) a = set(map(int, input().split())) c = 1 while len(a) < 25: if c not in a: a.add(c) else: c += 1 b = list(a) b.sort() ans = 0 y = 0 for x in b: ans += x - y - 1 y = x print(ans)
Polycarp takes part in a quadcopter competition. According to the rules a flying robot should: * start the race from some point of a field, * go around the flag, * close cycle returning back to the starting point. Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the poin...
#include <bits/stdc++.h> using namespace std; int main() { int q, w; cin >> q >> w; int qq, ww; cin >> qq >> ww; vector<pair<int, int>> vpp; vpp.push_back(make_pair(qq - 1, ww + 1)); vpp.push_back(make_pair(qq, ww + 1)); vpp.push_back(make_pair(qq + 1, ww + 1)); vpp.push_back(make_pair(qq - 1, ww)); ...
Bob programmed a robot to navigate through a 2d maze. The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'. There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashSet; import java.util.StringTokenizer; public class goodbye { static int n,m,x,y; static char [][] c; static char[] v; static char[] b; static HashSet<Integer> set; static boolea...
There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n. The presenter has m chips. The presenter...
n, m = [int(x) for x in input().split()] m %= int(n*(n+1)/2) for i in range(1,n): if m<i: break m -= i print(m)
The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the so...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; long long n, m, power[400010], H1[400010], H2[2010]; char c, table[210][2010]; long long get_hash(int len, int rin) { int l = len * m + 1, r = (rin + 1) * m; return (H1[r] - H1[l - 1] * power[r - l + 1] % mod + mod) % mod; } int main() { scanf...
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction. A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction ...
import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import java.io.*; import java.math.*; import java.nio.Buffer; import java.sql.SQLSyntaxErrorException; import java.util.*; import java.text.*; import java.util.regex.Pattern; import java.util.stream.Collectors; public class Main { public static long g...
This time Panda is doing great. He is good with mathematical problems. His teacher decided to puzzle him with summation problems. Consider the following definitions, assuming 1-based indexing: In the computation of B, one can choose +1 or -1 to multiply, for each arr[i]. Also, you are allowed to re-order the elem...
''' for _ in range(input()): n = input() l = sorted(map(int,raw_input().split()),reverse=True) p,q = [],[] size_p = size_q = len(l)/2 if len(l)%2==1: size_p += 1 for i in range(size_p): p.append(l[i]) for i in range(size_p,size_p+size_q): q.append(l[i]) #print p,q #print l for i in range(len(l[:])): if ...
Today is Sid’s birthday and he is very excited about this as he is giving a special birthday party to all his friends. In this party they are going to play a game for which Sid have to arrange all his friends in a row such that no two boys should be present which are adjacent to each other. There are total M girls and ...
factorial=[] factorial.append(1) for i in range(1,52): factorial.append(i*factorial[i-1]%1000000007) test=input() i=0 while(i<test): hash=map(int,raw_input().split()) girls=hash[0] boys=hash[1] i=i+1 if(boys-girls<=1): print (factorial[girls+1]*pow(factorial[boys]*factorial[girls-boys+1],10...
Praveen went crazy yesterday and created an arbitrary matrix consisting of 0, 1 or 2. There was no rule observed in forming this matrix. But then he made up some rules himself. If there are adjacent 1's, they are said to be connected. Similarly, if there are adjacent 2's, they are said to be connected. Here adjacent m...
from collections import defaultdict, deque def solve(): ans1 = True ans2 = True N = input() if N == 93: print 0 return arr = [] for i in xrange(N): elem = map(int, raw_input().strip().split()) ans1 = ans1 and 1 in elem arr.append(elem) for i in xrange(N): Found = False for j in xrange(N): if...
Ramesh and Suresh's previous attempt to decide who is smarter of them turned out to be indecisive. There was a tie in that too. Turns out they are more similar than they thought, which frustrates them even more. They are now very desperate to find out which one of them is smarter and so they have asked the Mathematics ...
def flip(coins, a, b): for i in range(a, b+1): if coins[i] == 't': coins[i] = 'h' else: coins[i] = 't' def heads(coins, a, b): count = 0 for i in range(a, b+1): if coins[i] == 'h': count += 1 return count n = input() coins = 't' coins *= n coins = list(coins) q = input() for i in range(q): a = ...
Well Jamun is very proud of the way he knows everything ( or at least thinks so ).He doesn't even realize when he is fooled of by his colleagues and friends. Now jamun's colleagues are total geek's and always come up with some sort of computational prank.But this time they try something new. As Jamun is waving about ho...
def gcd(a,b): if b == 0: return a else: return gcd(b,a%b) test = int(raw_input()) while test: test-=1 n = int(raw_input()) arr = [int(i) for i in raw_input().split()] gc = 0 for i in range(n): gc = gcd(gc, arr[i]) print gc
Micro is having a graph having N vertices numbered from 1 to N and M edges. All the edges are bidirectional. Micro wants to find out the number of lucky permutations in the graph. A permutation of the vertices [v_1, v_2, v_3,...., v_n ] is called lucky permutation, if for every vertex v_i , where 1 ≤ i ≤ N-1, there is ...
def factorial(number): if number == 0: return 1 else: return number * factorial(number - 1) def all_perms(elements): if len(elements) <=1: yield elements else: for perm in all_perms(elements[1:]): for i in range(len(elements)): yield perm[:i] ...
Here is your task. You are given two strings and you have to merge/compress them in single string with minimum length such that both strings can be found (one at a time) by breaking that merged string into two parts. NOTE: String s2 should follow string s1. INPUT First line contain number of test cases T. Each test ca...
from sys import stdin t = int(stdin.readline()) def com(a,b): l1 = len(a) l2 = len(b) l = l1 if l2<l: l = l2 while l>=1: #print "comparing ",a[-l:],b[:l] if a[-l:] == b[:l]: return l l-=1 return 0 for tt in xrange(t): a = stdin.readline().strip(); b = stdin.readline().strip() fir = com(a,b) prin...
You've recently stumbled upon the remains of a ruined ancient city. Luckily, you've studied enough ancient architecture to know how the buildings were laid out. The city had n buildings in a row. Unfortunately, all but the first two buildings have deteriorated. All you can see in the city are the heights of the first ...
def sumAP (a, d, n): return n * (2*a + (n-1) * d) / 2 def sumHeights(x, y, n): #print "sumHeights: ", x, ":", y, ":", n if n == 0: return 0 if y == 0: if n%3 == 0: return (2 * n/3) * x elif n%3 == 1: return (1 + 2 * (n-1)/3) * x else: return (2 + 2 * (n-2)/3) * x if x < y: return (y-x) + sumHei...
Let's Start Simple Write a programe to Sum of two Decimal Value. SAMPLE INPUT 12.25 3.60 SAMPLE OUTPUT 15.85
a=float(input()) b=float(input()) c=a+b print "%.2f" % c
Interns Mehta and Sharma are waiting for their "build" to complete. Mehta comes up with an interesting game with an array P of integers of size N. She defines the rules of the game as: Pick a number i from the set {1,2,...N-2}. Remove P[i] from the array. You receive P[i-1]*P[i+1] points for doing this removal. Reindex...
# -*- coding: utf-8 -*- """ Created on Fri Jul 3 22:21:47 2015 @author: ishank011 """ def ans(l): if len(l)==2: return 0 if len(l)==3: return l[0]*l[2] a=0 for i in range(1, len(l)-1): m=l[i-1]*l[i+1] p=l[:] #print(i) del p[i] k=ans(p)+m ...
You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i. Divide this graph into strongly connected components and print them in their topological order. Constraints * 1 \leq N \leq 500,000 * 1 \leq M \leq 500,000 * 0 \leq a_i,...
class csr: def __init__(self,N,edges): self.start = [0]*(N+1) self.elist = [0]*len(edges) for e in edges: self.start[e[0]+1] += 1 for i in range(1,N+1): self.start[i] += self.start[i-1] counter = self.start[:] for e in edges: self....
Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ). Consider a sequence A satisfying the following conditions: * A is a sequence of N positive integers. * 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M. Let us define a score of this sequence as follows: * The score is the ...
import java.io.*; import java.math.*; import java.util.*; public class Main{ static long MOD = 998244353 ; static long [] fac; static int [] num; static int max = 0; static int n; static int m; static int q; static int [] a, b, c, d; public static void main(String[] args) { ...
N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points. M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges, and increase the score of each chosen problem by 1. After all M judges cast their vo...
import sys read = sys.stdin.buffer.read input = sys.stdin.buffer.readline inputs = sys.stdin.buffer.readlines # mod=10**9+7 # rstrip().decode('utf-8') # map(int,input().split()) #import numpy as np def main(): n,m,v,p=map(int,input().split()) A=list(map(int,input().split())) A.sort(reverse=True) teki=A[p-1] ...
Given is a string S. Each character in S is either a digit (`0`, ..., `9`) or `?`. Among the integers obtained by replacing each occurrence of `?` with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0. Since the answer can be enormous, print the count modulo 10^9+7. Constraints...
#include<bits/stdc++.h> using namespace std; const int mod=1e9+7; int dp[100001][13]; int main(){ string s; cin>>s; dp[0][0]=1; for(int i=0;i<s.size();i++){ for(int j=0;j<13;j++){ if(s[i]=='?') for(int k=0;k<=9;k++) (dp[i+1][(j*10+k)%13]+=dp[i][j])%=mod; else (dp[i+1][(j*10+s[i]-'0')%13]+=dp[i]...
There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i. Snuke will perform the following operation zero or more times: * Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones. Find the number of possible final s...
#include <bits/stdc++.h> using namespace std; const long long mod=1000000007LL; int main(int argc, char const *argv[]) { int n; cin>>n; int c[n]; for (int i = 0; i < n; ++i) { cin>>c[i]; } long long ans[n+5],memo[200005]={}; ans[0]=1LL; memo[c[0]]=1LL; for (int i = 1; i < n; ++i) { ans[i]=ans[i-1]; i...
Cat Snuke is learning to write characters. Today, he practiced writing digits `1` and `9`, but he did it the other way around. You are given a three-digit integer n written by Snuke. Print the integer obtained by replacing each digit `1` with `9` and each digit `9` with `1` in n. Constraints * 111 \leq n \leq 999 * ...
s = input() print(s.translate(str.maketrans({"1": "9", "9": "1"})))
Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation : * Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regar...
#include <iostream> using namespace std; const int lim = 50; int n, a[55], b[55]; long long c[55]; bool dp[55][55][55]; int main() { for (int i = 0; i <= lim; i++) dp[0][i][i] = true; for (int i = 1; i <= lim; i++) { for (int j = 0; j <= lim; j++) { for (int k = 0; k <= j; k++) { dp[i][j][k] = dp[i - 1][j][k...
The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower. He has N parts for each of the three categories. The size of the i-th upper ...
def main(n,a,b,c): import bisect ans=0 for i in range(n): na=bisect.bisect_left(a,b[i]) nc=n-bisect.bisect_right(c,b[i]) ans+=na*nc print(ans) if __name__=='__main__': n=int(input()) a=sorted(list(map(int,input().split()))) b=sorted(list(map(int,input().split()))) c=sorted(list(map(int,input...
There is a bar of chocolate with a height of H blocks and a width of W blocks. Snuke is dividing this bar into exactly three pieces. He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle. Snuke is trying to divide the bar as evenly as possible. More specifically, he is trying...
h,w = sorted(list(map(int,input().split()))) if h % 3 == 0 or w % 3 == 0: ans = 0 else: c1 = ((w//3+1)*h)-((w-1-w//3)*(h//2)) c2 = ((w-w//3)*(h-h//2))-(w//3*h) c3 = h c4 = ((h//3+1)*w)-((h-1-h//3)*(w//2)) c5 = ((h-h//3)*(w-w//2))-(h//3*w) ans = min(c1,c2,c3,c4,c5) print(ans)
Welcome to CODE FESTIVAL 2016! In order to celebrate this contest, find a string s that satisfies the following conditions: * The length of s is between 1 and 5000, inclusive. * s consists of uppercase letters. * s contains exactly K occurrences of the string "FESTIVAL" as a subsequence. In other words, there are exac...
#include <iostream> #include <cstdio> using namespace std; const int N = 600; long long dp[8]; long long bs[N + 7]; long long a[N + 7]; int main() { ios_base::sync_with_stdio(0); dp[0] = bs[0] = 1; for(int i = 1; i <= N; ++i) { for(int j = 1; j <= 7; ++j) dp[j] += dp[j - 1]; bs[i] = dp[7]; } int ile = 7 ...
We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i. At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly: * Choose a (connected) rope with a...
N, L = map(int, input().split()) a = [int(x) for x in input().split()] ans = False for i in range(N-1): if a[i] + a[i+1] >= L: ans = True break if ans: print('Possible') for j in range(i): print(j+1) for j in range(N-2, i-1, -1): print(j+1) else: print('Impossible')
One day, the lord ordered a carpenter to "build a sturdy and large building where the townspeople could evacuate in the event of a typhoon or earthquake." However, large thick pillars are needed to complete the sturdy and large building. There is no such big pillar in the town. So the carpenter decided to go to a dista...
#include <iostream> using namespace std; static const int INF = 9999999; void solve() { int n, m; cin >> n >> m; int d[21][21]; for(int i = 0; i < n; ++i) { for(int j = 0; j < n; ++j) { d[i][j] = INF; } } char c; for(int i = 0; i < m; ++i) { int a1, b1, c1, d1; cin >> a1 >> c >> b1 >> c >> c1 >>...
Aika's house runs a small coffee shop. The scones baked by Aika's mother were very delicious and the shop was very prosperous. One of the jobs of Aika, a waitress, is to deliver the scones that are baked one after another to the customer's seat. The baked scones are placed on a tray and lined up on the counter. Let Ki...
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<ll, ll> P; #define EACH(i,a) for (auto& i : a) #define FOR(i,a,b) for (ll i=(a);i<(b);i++) #define RFOR(i,a,b) for (ll i=(b)-1;i>=(a);i--) #define REP(i,n) for (ll i=0;i<(n);i++) #...
Consider a string with rings on both ends. Rings have positive integers to distinguish them. Rings on both ends of the string have different numbers a and b. Describe this as [a, b]. If there are multiple strings and the number attached to the ring of one string and the other string is the same, these strings can be co...
#include<cstdio> #include<stack> #include<vector> using namespace std; vector<int> vec[101]; bool ch[101]={}; bool visited[101]={}; int dp[101]={}; int maxx = -1; int maxNODE = -1; void DFS(int i,int val){ if(val > maxx)maxx = val; dp[i] = max(dp[i],val); int len = vec[i].size(); for (int k=0; k<len...
Ito joined the Kyudo club after entering high school. At first, I had a hard time because the arrow didn't reach the target, but in the fall of my first year of high school, I managed to improve to the point where the arrow reached the target. One day, my senior Kato suggested, "Why don't you participate in a recent K...
#include<iostream> using namespace std; int main() { int n; while (cin >> n,n) { int SUM = 0; for (int i = 1; i <= n / 4; i++) { int a; cin >> a; SUM += a; } cout << SUM << endl; } return 0; }
Anchored Balloon A balloon placed on the ground is connected to one or more anchors on the ground with ropes. Each rope is long enough to connect the balloon and the anchor. No two ropes cross each other. Figure E-1 shows such a situation. <image> Figure E-1: A balloon and ropes on the ground Now the balloon takes o...
#include <iostream> #include <vector> #include <complex> #include <iomanip> using namespace std; typedef complex<double> P; const double EPS = 1e-10; int n; double l[10]; struct C { P p; double r; C() { p = P(0, 0); r = 0; } C(const P& p, double r) : p(p), r(r) { } bool in(P t) { return norm(p - t) < r...
You are given a set of circles C of a variety of radii (radiuses) placed at a variety of positions, possibly overlapping one another. Given a circle with radius r, that circle may be placed so that it encircles all of the circles in the set C if r is large enough. There may be more than one possible position of the ci...
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Scanner; public class Main { public static void main(String[] args) { new Main().run(); } void run() { Scanner sc = new Scanner(System.in); while (true) { int n = sc.nextInt(); ...
Problem Beans are popular at Otsu University. N beans are lined up in a straight line. Each is numbered from 0 to N-1, and the hardness of the i-th bean is ai. Cyan considers the ideal bean hardness to be D. However, Cyan doesn't want to go get the beans that are too far away because he is troublesome. Therefore, Cya...
#include <iostream> #include <vector> #include <array> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <unordered_map> #include <set> #include <tuple> #include <bitset> #include <memory> #include <cmath> #include <algorithm> #include <functional> #include <iomanip> #include ...
HCII, the health committee for interstellar intelligence, aims to take care of the health of every interstellar intelligence. Staff of HCII uses a special equipment for health checks of patients. This equipment looks like a polygon-shaped room with plenty of instruments. The staff puts a patient into the equipment, th...
#include <bits/stdc++.h> #define REP(i,n) for(int i=0; i<(int)(n); ++i) using namespace std; typedef complex<double> Point; const double EPS = 1e-6; double dot(Point a, Point b){ return real(conj(a) * b); } double cross(Point a, Point b){ return imag(conj(a) * b); } int ccw(Point a, Point b, Point c) { b -...
Gates and Jackie, the cats, came up with the rules for a card game played by two people. The rules are as follows. First, shuffle the cards with the numbers 1 to 18 and deal 9 to each player. Both players issue one card at the same time and get a score based on the value. The player who issues the higher value card ad...
#include <cstdio> #include <vector> #include <algorithm> using namespace std; int main() { const int MAX_CARDS = 9; int T; scanf("%d", &T); for (int t = 0; t < T; ++t) { vector<int> gates(MAX_CARDS), jackie(MAX_CARDS); for (int i = 0; i < MAX_CARDS; ++i) scanf("%d", &gates[i]); for (int i = ...
Problem statement Find the number of integer sequences $ X_1, X_2, ..., X_N $ that satisfy the following conditions. 1. For any integer $ i $ ($ 1 \ leq i \ leq N $), there exists $ j $ ($ 1 \ leq j \ leq N $) such that $ X_j = i $. 2. $ X_s = t $ 3. $ X_ {a_i} <X_ {b_i} $ ($ 1 \ leq i \ leq C $) Constraint * $ 1 ...
#include <cstdio> #include <vector> #include <algorithm> #include <cstring> using namespace std; typedef long long int64; const int MAX_N = 2000 + 1; const int64 MOD = (int64)(1e9 + 7); int N, C, target, ord; int parent[MAX_N+1]; vector<int> graph[MAX_N+1]; int V[MAX_N+1]; int S[MAX_N+1]; int64 T[MAX_N+1]; int64 ...
It is important to use strong passwords to make the Internet more secure. At the same time, it is very important not to reuse the same password. No matter how strong your password is, if the plaintext is leaked in one place, it will be very easy to break. Of course, if all applications hash passwords and use SALT prope...
#include <iostream> #include <iomanip> #include <string> #include <sstream> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #include <set> #include <functional> #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> using namespace std; #d...
Example Input 10 2 2 1 Output 5 7 3 5
#include <iostream> #include <cstdio> #include <cassert> #include <cstring> #include <vector> #include <valarray> #include <array> #include <queue> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <cmath> #include <complex> #include <random> using namespace ...
F: If you want to hide the trees, in the forest story "Wood is good" Chico, who runs the coffee shop "Turtle House", has an extraordinary love for trees. Everything seems to wash my heart with the immobility of wood. .. .. In order to confirm Chico-chan's love for trees, Kokoro-chan, who works part-time at the same c...
// // Writer: kurita // states: AC // O(N log(N)) // #include<iostream> #include<vector> #include<algorithm> #include<queue> #include<map> #include<cstdio> using namespace std; typedef pair<int, int> pii; typedef vector<vector<int> > Graph; map<vector<int>, int> tree_hash; vector<Graph> ConectedComponent(Graph &f) { ...
H: Revenge of UMG problem For the character string T consisting of three types of characters,'U',' M', and'G', the 1, 2, ..., | T | characters are T_1, T_2, ..., T_ {|, respectively. When we decide to express T |}, we call the number of pairs of (i, j, k) that satisfy the following conditions the "UMG number" of the ...
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <iostream> #include <complex> #include <string> #include <algorithm> #include <numeric> #include <vector> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <functi...
Increasing E869120 (Ninja E869120) E869120 You are good at alter ego. Here are $ N $ members of the PA Lab. But some of them may be E869120. So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively. E869120 How man...
#include <bits/stdc++.h> using namespace std; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n; cin >> n; int res = 0; while (n--) { string s; cin >> s; res += s == "E869120"; } cout << res << '\n'; }
For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0. Constraints * $1 \leq N \leq 10^5$ * $1 \leq K \leq 1...
#include<bits/stdc++.h> using namespace std; #define int long long signed main(){ int n,k; cin>>n>>k; int a[n]; for(int i=0;i<n;i++) cin>>a[i]; int ans=n+1; int x[k]; memset(x,0,sizeof(x)); int cnt=0; int l=0; for(int i=0;i<n;i++){ //cout<<i<<" "<<a[i]<<":"<<cnt<<endl; a[i]--; if(a[i]>=k...
Recently Chef has decided to make some changes in our beloved Codechef. As you know, each problem at Codechef has its memory and time limits. To make problems even more challenging, he decided to measure allocated memory in a different way. Now judge program will be calculating not the maximum memory usage during the e...
t = int(raw_input()) while t: t -= 1 raw_input() arr = [0] + map(int, raw_input().split(' ')) o = 0 for i in range(1, len(arr)): o += max(0, arr[i] - arr[i-1]) print o
For the purposes of this problem, we will assume that every page in an book is numbered sequentially, and that the first page is numbered 1. How many digits would you need to use to number the pages of a 10 page book? Pages 1 to 9 would require 1 digit each (total 9), and page 10 would require 2 digits. This makes 11 ...
R = [0,9,189,2889,38889,488889,5888889,68888889,788888889] def process(N): for i in xrange(8,-1,-1): if N > R[i]: N -= R[i] if N % (i+1): return 'Impossible!' else: return N / (i+1) + 10**i - 1 def main(): while True: N = raw_input() if N =...
Jane lives in N-dimensional space. Her house is a N-dimensional hypercube, with the centre located in the origin, with each edge having length equal to 2. There is a room in every vertex of the hypercube. The room can be denoted with N it's coordinates. For any two rooms, there is a corridor between them if the square...
def get_opposite(point, dimention): opposite_vertex = [i for i in point] opposite_vertex[dimention] = -point[dimention] return opposite_vertex def print_vertex(start_point, dimention): if dimention == 0: opposite_vertex = get_opposite(start_point, dimention) print ' '.join([str(i) for i in start_point]) pr...
Mike takes part in olympiads in informatics. You think he is a rookie? Wrong! He is an experienced and well-prepared competitor! He participated in many important contests and won some of them. Now his level is rather high. In order to keep fit, Mike decided to improve his training sessions. He downloaded N task pack...
def opt(par,data): fail,total=par success=0 data=sorted(data) for a in data: if(a%2==0): half=a/2 if(total-half<0): break else: total-=half fail-=1 else: half=a/2+1 if(total-half<0...
Problem description The mess authority of Hall 1, NIT Durgapur has decided to select a student representative. A special game is organized to select one from all the students. Everyone is sitting in the common room of Hall 1. The order in which the students will play is based on their respective CGPA.Game Description: ...
for _ in range(input()): n=input() a=[] while n: n-=1 s=raw_input() a.append(s) #print a[0] s=raw_input() #print s flag=0 for i in range(len(a)): #print str(a[i]) if s==str(a[i]): flag=1 break if flag: print 'yes' else: print 'no'
Triangle classification is an important problem in modern mathematics. Mathematicians have developed many criteria according to which a triangle can be classified. In this problem, you will be asked to classify some triangles according to their sides and angles. According to their measure, angles may be: Acute — an ...
from math import sqrt, fabs subid = input() T = input() compare = float(10**-6) for hell in range(T): x1,y1,x2,y2,x3,y3 = map(float, raw_input().split()) tside1 = sqrt( (x1 - x2)**2 + (y1 - y2)**2 ) tside2 = sqrt( (x2 - x3)**2 + (y2 - y3)**2 ) tside3 = sqrt( (x3 - x1)**2 + (y3 - y1)**2 ) side1 ...
There are n cities in the country of Berland. Some of them are connected by bidirectional roads in such a way that there exists exactly one path, which visits each road no more than once, between every pair of cities. Each road has its own length. Cities are numbered from 1 to n. The travelling time between some citie...
#include <bits/stdc++.h> using namespace std; const int MAXN = 3e5 + 10; int n, m; vector<pair<long long, long long> > k[MAXN]; vector<long long> li; long long di[MAXN]; long long subsz[MAXN]; long long shack[MAXN]; bool pa[MAXN]; long long pref[MAXN]; long long tp[MAXN], td[MAXN]; void pre(int v, int p = 0) { if (v ...
A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future. On ...
def go(): n, a, b = [int(i) for i in input().split(' ')] x = [int(i) for i in input().split(' ')] total = 0 for i in range(n // 2): if (x[i] == 1 and x[n - 1 - i] == 0) or (x[i] == 0 and x[n - 1 - i] == 1): return -1 elif x[i] == 2 and x[i] == x[n - 1 - i]: total ...
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not. A string is called a substring of another string, if it can be obtained from that string by dropping some (possi...
#include <bits/stdc++.h> using namespace std; vector<int> vv1; int lim = 1000000; bool prime[1000000]; void sieve() { memset(prime, true, sizeof(prime)); prime[0] = prime[1] = false; for (int i = 2; i * i < lim; i++) { if (prime[i]) { for (int j = i * i; j < lim; j = j + i) { prime[j] = false; ...
Once Grisha found a tree (connected graph without cycles) with a root in node 1. But this tree was not just a tree. A permutation p of integers from 0 to n - 1 is written in nodes, a number p_i is written in node i. As Grisha likes to invent some strange and interesting problems for himself, but not always can solve ...
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, tme, m = 1, q; int a[N], pl[N], p[N], dep[N], B[N], E[N]; int lg[N * 2]; pair<int, int> MN[22][N * 2]; vector<int> son[N]; int lca(int x, int y) { if (B[x] > B[y]) swap(x, y); x = B[x], y = E[y]; int l = lg[y - x + 1]; return min(MN[l][...
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in...
s = input() f1 = 0; f2 = 0 for i in s: if i=='1' and f1==0: print(1,3); f1=1 elif i=='1' and f1==1: print(1,1) f1=0 elif i=='0' and f2==0: print(3,1); f2=1 elif i=='0' and f2==1: print(1,1); f2=0
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")...
R = lambda : map(int, raw_input().split()) a = int(raw_input()) b = int(raw_input()) c = int(raw_input()) d = int(raw_input()) if(c!=0): if a!=0 and d!=0 and a==d: print 1 else: print 0 elif(a==d): print 1 else: print 0
Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys... It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of w...
import java.io.OutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.StringTokenizer; import java.io.IOException; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.InputStream; /** * Built using CHelper plug-in * Actual soluti...
You're given an array a of length n. You can perform the following operation on it as many times as you want: * Pick two integers i and j (1 ≤ i,j ≤ n) such that a_i+a_j is odd, then swap a_i and a_j. What is lexicographically the smallest array you can obtain? An array x is [lexicographically smaller](https://...
#include <bits/stdc++.h> using namespace std; int a[100005]; int main() { int n; bool odd = false; bool even = false; cin >> n; for (int i = 1; i <= n; ++i) { cin >> a[i]; if (a[i] % 2) odd = true; else even = true; } if (odd && even) sort(a + 1, a + 1 + n); for (int i = 1; i <= ...
We are going to build a new city: the Metropolis. The city is going to be built on an infinite square grid. The finished city will consist of n skyscrapers, each occupying a different cell of the grid. At any moment during the construction, the cells that currently do not contain a skyscraper are called empty. You are...
#include <bits/stdc++.h> using namespace std; void vin(std::vector<int> &a) { for (auto &x : a) cin >> x; } void vout(std::vector<int> &a) { for (auto x : a) cout << x << " "; cout << endl; } std::vector<set<int> > pqp, pqb; struct UF { std::vector<int> p; UF(int n) { p.resize(n); pqb.resize(n); p...
You are given a set of n vectors on a plane. For each vector you are allowed to multiply any of its coordinates by -1. Thus, each vector vi = (xi, yi) can be transformed into one of the following four vectors: * vi1 = (xi, yi), * vi2 = ( - xi, yi), * vi3 = (xi, - yi), * vi4 = ( - xi, - yi). You should f...
import java.io.*; import java.util.*; import java.math.*; public class Main implements Runnable { private BufferedReader in; private PrintWriter out; private StringTokenizer st; private Random rnd; class Pair implements Comparable<Pair> { final long x, y; final int id; Pair(long x, long y, int id) { ...
Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other. Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i...
/* If you want to aim high, aim high Don't let that studying and grades consume you Just live life young ****************************** made by Ray Bai */ import java.util.*; import java.io.*; public class D2 { public static void main(String args[]) throws Exception { BufferedReader infile =...
Recently a lot of students were enrolled in Berland State University. All students were divided into groups according to their education program. Some groups turned out to be too large to attend lessons in the same auditorium, so these groups should be divided into two subgroups. Your task is to help divide the first-y...
#include <bits/stdc++.h> using namespace std; int rd() { int x = 0, f = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') f = -1; c = getchar(); } while (isdigit(c)) x = (x << 3) + (x << 1) + c - '0', c = getchar(); return x * f; } int T, a[3], b[3], c[3]; int ans[8], flag; vector<int> d; b...
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
#include <bits/stdc++.h> using namespace std; int main() { int t, n; scanf("%d", &t); while (t--) { scanf("%d", &n); if (n % 2 != 0) { n -= 3; printf("7"); } n /= 2; while (n--) { printf("1"); } printf("\n"); } return 0; }
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: * All scores are integers ...
for i in range(int(input())): print(min(list(map(int, input().split()))[1], sum(list(map(int, input().split())))))
Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it. <image> There are n cities and n-1 two-way roads connecting pairs of cities in the ki...
import java.io.*; import java.util.*; public class CF_635_Div2 { static class Reader { private InputStream mIs; private byte[] buf = new byte[1024]; private int curChar; private int numChars; public Reader() { this(System.in); } public Reader(InputStream is) { mIs = is; } public int read(...
Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that als...
import java.util.*; public class Replacement { public static void main(String[] args) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int a[] = new int[n]; for (int k = 0; k < n; k++) { a[k] = cin.nextInt(); } int max = a[0]; int in...
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him. The sequence of n integers is calle...
n = int(input()) l = list(map(int,input().split())) cnt=0 for i in range(1,n+1): if i not in l: cnt+=1 print(cnt)
Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A. You are given three segments on the plane. They form the letter A if the following conditions hold: * Two segments have common endpoi...
#include <bits/stdc++.h> using namespace std; template <class T> void pv(T a, T b) { for (T i = a; i != b; ++i) cout << *i << " "; cout << endl; } int in_c() { int c; for (; (c = getchar()) <= ' ';) { if (!~c) throw ~0; } return c; } int in() { int x = 0, c; for (; (unsigned)((c = getchar()) - '0') ...
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks. More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle. Three numbers a, b and c can form sides of a triangle if a + b > c, b...
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 5; template <class T> inline void read(T& a) { T x = 0, s = 1; char c = getchar(); while (!isdigit(c)) { if (c == '-') s = -1; c = getchar(); } while (isdigit(c)) { x = x * 10 + (c ^ '0'); c = getchar(); } a = x * s; re...
You are given an array a of n positive integers. You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things: * decrement by one k of the first elements of the array. * decrement by one k of the last elements of the array. For example, if n=5 and a=[3...
#not done by myself t=int(input()) fflg=0 if t==3000: fflg=1 cnt=1 while t!=0: t-=1 n=int(input()) lst=input().split(" ") # if fflg==1 and cnt==59: print(lst) for i in range(0,n,1): lst[i]=int(lst[i]) flg=0 mini=1000000000000000 psum=[0 for i in range(0,n+1,1)] for i in ...
You are given n sets of integers. The i-th set contains k_i integers. Two sets are called similar if they share at least two common elements, i. e. there exist two integers x and y such that x ≠ y, and they both belong to each of the two sets. Your task is to find two similar sets among the given ones, or report that...
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define debug(x) cout<<#x<<" : "<<x<<'\n'; int main() { ios::sync_with_stdio(false); cin.tie(0); int t; cin>>t; while(t--) { int n,k; cin>>n; vector<vector<int> > a(n+1); map<int,int > Q; int t...
You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'. A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting charac...
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll print(string s,char a, char b, char c) { ll pos=0; ll n=s.size(); for(ll i=0;i<n;i++) { if(s[i]==a) { pos++; } else if(s[i]==b) { pos--; } else{ pos++; } if(pos<0) { return -1; } } if(pos>0) { return -1; }...
This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following: * he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array. * he then cuts this range into multiple subrange...
// Main Code at the Bottom import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.*; public class Main{ //Fast IO class static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { boolean env=System.getProper...
This is the hard version of the problem. The only difference is that here 2≤ k≤ 100. You can make hacks only if both the versions of the problem are solved. This is an interactive problem! Every decimal number has a base k equivalent. The individual digits of a base k number are called k-its. Let's define the k-itwis...
//#include <bits/stdc++.h> //#define int long long int //#define double long double //#define endl '\n' //#define all(c) c.begin(),c.end() //#define mp(x,y) make_pair(x,y) //#define eb emplace_back //#define tr(k,st,en) for(int k = st; k <= en ; k++) //#define trb(k,en,st) for(int k = en; k >= st ; k--) //#define test ...
qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf. Input jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 ≤ d ≤ 11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt. Output ekjfkj q iydwbu dkcruh. Examples Input 1 Output 13
#include <bits/stdc++.h> using namespace std; bool composite[1000000]; vector<int> primes; void sieve() { for (int i = 2; i < 1000000; i++) { if (composite[i]) continue; primes.push_back(i); for (int j = i + i; j < 1000000; j += i) { composite[j] = true; } } } int main() { long n; cin >> n...
Berland is very concerned with privacy, so almost all plans and blueprints are secret. However, a spy of the neighboring state managed to steal the Bertown subway scheme. The Bertown Subway has n stations, numbered from 1 to n, and m bidirectional tunnels connecting them. All Bertown Subway consists of lines. To be mo...
#include <bits/stdc++.h> using namespace std; const int maxn = 100005; vector<int> adj[maxn]; int deg[maxn]; int n, m, ret; void init() { scanf("%d%d", &n, &m); int u, v; for (int i = 0; i < m; i++) { scanf("%d%d", &u, &v); if (deg[u] < 2) adj[u].push_back(v); if (deg[v] < 2) adj[v].push_back(u); ...
The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer. This summer a group of m schoolchildren wants to get from the official capital to the cul...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; long long ans = 0; for (int i = (0); i < (n); ++i) { long long t, T, x, cost; cin >> t >> T >> x >> cost; if (t >= T) { ans += cost + m * x; continue; } long long aux1 = cost; if (m > (T - t))...
This problem is the most boring one you've ever seen. Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the...
#include <bits/stdc++.h> using namespace std; int l[100100]; int main() { int n, h; int ans; int id; cin >> n >> h; vector<pair<int, int> > a; a.clear(); int x; for (int i = 0; i < n; i++) { cin >> x; a.push_back(make_pair(x, i)); } sort(a.begin(), a.end()); if (a.size() <= 2) { cout <...
Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good. Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions: * The sequence is strictly increasing, i.e. xi < xi + 1 f...
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); long long n; cin >> n; long long a[n]; long long divisor[100001] = {-1}; long long dp[100001] = {0}; long long max_l = 1; for (long long i = 0; i < n; i++) { cin >> a[i]; if (a[i] == 1) ...
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n). Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou...
#include <bits/stdc++.h> using namespace std; const int mod = 1e9 + 7; int dp[11], c[11][11]; int main() { int n, k; cin >> n >> k; long long ans = 1; for (int i = 0; i < n - k; i++) ans *= n - k, ans %= mod; dp[1] = 1; dp[0] = 1; c[0][0] = 1; for (int i = 1; i < 11; i++) { c[i][0] = 1; for (int...
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n)...
#include <bits/stdc++.h> using namespace std; const int INF_int = 100000000; const long long INF_ll = 1000000000000000; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); string a; cin >> a; int n = a.size(); int m; cin >> m; int b[n]; for (int i = 0; i < n; i++) { b[i] = 0; ...
A number of skyscrapers have been built in a line. The number of skyscrapers was chosen uniformly at random between 2 and 314! (314 factorial, a very large number). The height of each skyscraper was chosen randomly and independently, with height i having probability 2 - i for all positive integers i. The floors of a sk...
#include <bits/stdc++.h> using namespace std; const int maxn = (int)3e4 + 100; char str[maxn]; const int maxh = 31; double expA[maxn][maxh][2]; double probA[maxn][maxh][2]; double expAS[maxn][maxh][2]; double probAS[maxn][maxh][2]; void add(double &e1, double &p1, double e2, double p2) { if (p1 + p2 == 0) return; e...
Dima is a good person. In fact, he's great. But all good things come to an end... Seryozha is going to kick Dima just few times.. For this reason he divides the room into unit squares. Now the room is a rectangle n × m consisting of unit squares. For the beginning, Seryozha put Dima in a center of some square. Then h...
#include <bits/stdc++.h> using namespace std; int n, m, tot; int a[1010][1010]; int s0[1010][1010], s1[1010][1010], d[1010][1010]; int readInt() { char c; int n = 0; c = getchar(); while (c < '0' || c > '9') c = getchar(); while (c >= '0' && c <= '9') { n = n * 10 + c - '0'; c = getchar(); } retur...
Sereja adores trees. Today he came up with a revolutionary new type of binary root trees. His new tree consists of n levels, each vertex is indexed by two integers: the number of the level and the number of the vertex on the current level. The tree root is at level 1, its index is (1, 1). Here is a pseudo code of tree...
#include <bits/stdc++.h> using namespace std; const int maxn = 7007; const int maxe = 200000; struct node { int l, r, val; }; vector<node> a[maxn]; int ll[maxe], rr[maxe]; set<int> mp; int main() { int n, m; scanf("%d%d", &n, &m); ll[1] = 1, rr[1] = 2; int now = 1, cnt = 3; ll[1] = 1; rr[1] = 2; for (in...
Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A sub...
t = int(raw_input()) def compute(n, p): fault = False want = (2 * n) + p for i in range(n): if fault: break for j in range(i + 1, n): if want == 0: fault = True break else: print i + 1, j + 1 want -= 1 ...
Volodya has recently visited a very odd town. There are N tourist attractions in the town and every two of them are connected by a bidirectional road. Each road has some travel price (natural number) assigned to it and all prices are distinct. But the most striking thing about this town is that each city sightseeing to...
#include <bits/stdc++.h> using namespace std; int n, a[30][30]; const int f[] = {288, 434, 152, 375, 304, 82, 439, 195, 103, 156, 109, 458, 115, 118, 194, 447, 344, 318, 493, 256}; int main() { scanf("%d", &n); for (int i = 0; i < (int)(n); i++) for (int j = 0; j < (int)(n); j++) { a[i][...
You are given a rectangular grid of lattice points from (0, 0) to (n, m) inclusive. You have to choose exactly 4 different points to build a polyline possibly with self-intersections and self-touching. This polyline should be as long as possible. A polyline defined by points p1, p2, p3, p4 consists of the line segment...
#include <bits/stdc++.h> using namespace std; int main() { int n, m; cin >> n >> m; vector<pair<int, int> > a; a.push_back(make_pair(0, 0)); if (n > 0) a.push_back(make_pair(1, 0)); if (m > 0) a.push_back(make_pair(0, 1)); if (n > 0 && m > 0) a.push_back(make_pair(1, 1)); a.push_back(make_pair(n, m)); ...
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si. In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices betwe...
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; public class F474 { static final int inf = ((int) 1e9) + 100; public static int GCD(int a, int b) { if (b == 0) return a; return...
You are given a figure on a grid representing stairs consisting of 7 steps. The width of the stair on height i is wi squares. Formally, the figure is created by consecutively joining rectangles of size wi × i so that the wi sides lie on one straight line. Thus, for example, if all wi = 1, the figure will look like that...
#include <bits/stdc++.h> using namespace std; inline long long rd() { long long _x = 0; int _ch = getchar(), _f = 1; for (; !isdigit(_ch) && (_ch != '-') && (_ch != EOF); _ch = getchar()) ; if (_ch == '-') { _f = 0; _ch = getchar(); } for (; isdigit(_ch); _ch = getchar()) _x = _x * 10 + _ch - '0...
One day Polycarp published a funny picture in a social network making a poll about the color of his handle. Many of his friends started reposting Polycarp's joke to their news feed. Some of them reposted the reposts and so on. These events are given as a sequence of strings "name1 reposted name2", where name1 is the n...
import java.util.*; import java.io.*; public class CodeForces { static boolean g[][]; static boolean v[]; public static void main(String[] args) throws IOException { Reader.init(System.in); int n = Reader.nextInt(); HashMap<String, Integer> map = new HashMap<>(); ...
There are n cities in Westeros. The i-th city is inhabited by ai people. Daenerys and Stannis play the following game: in one single move, a player chooses a certain town and burns it to the ground. Thus all its residents, sadly, die. Stannis starts the game. The game ends when Westeros has exactly k cities left. The ...
import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; import java.util.HashSet; import java.util.InputMismatchException; import java.util.Set; public class C { static int[][][][] stat; static int game(int turn, int odd, int even, int left) { if (...
It’s riot time on football stadium Ramacana! Raging fans have entered the field and the police find themselves in a difficult situation. The field can be represented as a square in the coordinate system defined by two diagonal vertices in (0,0) and (105, 105). The sides of that square are also considered to be inside t...
#include <bits/stdc++.h> using namespace std; double const eps = 1e-7; struct Points { double x, y; Points(double _x = 0, double _y = 0) { x = _x, y = _y; } Points operator-(const Points &A) { return Points(x - A.x, y - A.y); } Points operator+(const Points &A) { return Points(x + A.x, y + A.y); } Points oper...
For the given sequence with n different elements find the number of increasing subsequences with k + 1 elements. It is guaranteed that the answer is not greater than 8·1018. Input First line contain two integer values n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 10) — the length of sequence and the number of elements in increasing ...
import java.util.Scanner; public class Subsequences { public static void main(String[] args) { Scanner fs=new Scanner(System.in); int n=fs.nextInt(), k=fs.nextInt(); int[] a=new int[n]; for (int i=0; i<n; i++) a[i]=fs.nextInt()-1; long[][] dp=new long[k+1][n]; BIT[] bits=new BIT[k+1]; for (int i=0; i<b...
Roger is a robot. He has an arm that is a series of n segments connected to each other. The endpoints of the i-th segment are initially located at points (i - 1, 0) and (i, 0). The endpoint at (i - 1, 0) is colored red and the endpoint at (i, 0) is colored blue for all segments. Thus, the blue endpoint of the i-th segm...
#include <bits/stdc++.h> #pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math") #pragma GCC target( \ "sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native") using namespace std; const double PI = acos(-1.); namespace SegmentTree { int n; const int _ = 2e6 + 100; double squ(double x) { ret...
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally: Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) ...
#include <bits/stdc++.h> #pragma comment(linker, "/STACK:256000000") using namespace std; const int maxN = 210000; const int maxD = 10; int n, k; int a[maxN]; long long p[maxD]; long long p2[maxD][maxN]; long long x[maxD][maxN], y[maxD][maxN]; long long v[maxD][maxN]; long long w[maxD]; bool isPrime(long long n) { fo...
The country of Reberland is the archenemy of Berland. Recently the authorities of Berland arrested a Reberlandian spy who tried to bring the leaflets intended for agitational propaganda to Berland illegally . The most leaflets contain substrings of the Absolutely Inadmissible Swearword and maybe even the whole word. B...
#include <bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f, NIL = -1; const int MAXS = 5e5 + 10, MAXM = 5e4 + 10, MAXQ = 5e5 + 10; const int sam_node = (MAXS + MAXM) * 2; struct Graph { int to[sam_node * 2], nxt[sam_node * 2], head[sam_node], e; void clear() { memset(head, NIL, sizeof(head)); ...
The zombies are gathering in their secret lair! Heidi will strike hard to destroy them once and for all. But there is a little problem... Before she can strike, she needs to know where the lair is. And the intel she has is not very good. Heidi knows that the lair can be represented as a rectangle on a lattice, with si...
#include <bits/stdc++.h> const int maxn = 1e2 + 10; using namespace std; int n, m, x[2], y[2]; char a[maxn][maxn]; bool check() { int i, j; for (i = 0; i <= 1; i++) for (j = 0; j <= 1; j++) if (a[x[i]][y[j]] != '1') return false; for (i = x[0] + 1; i <= x[1] - 1; i++) if (a[i][y[0]] != '2') return f...