src_uid
stringlengths
32
32
prob_desc_description
stringlengths
63
2.99k
tags
stringlengths
6
159
source_code
stringlengths
29
58.4k
lang_cluster
stringclasses
1 value
categories
listlengths
1
5
desc_length
int64
63
3.13k
code_length
int64
29
58.4k
games
int64
0
1
geometry
int64
0
1
graphs
int64
0
1
math
int64
0
1
number theory
int64
0
1
probabilities
int64
0
1
strings
int64
0
1
trees
int64
0
1
labels_dict
dict
__index_level_0__
int64
0
4.98k
b4ac594755951e84001dfd610d420eb5
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β€” the probability that this friend will come up with a problem if Andrey asks him.Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset.
['greedy', 'probabilities', 'math']
def C(): n = int(input()) tmp = input() tmp = tmp.split() probability = list(map(float,tmp)) probability.sort() current = probability[n-1] pre = 1 - probability[n-1] for i in range(n-2,-1,-1): tmp = current * (1-probability[i]) + pre * (probability[i]) if (tmp > current): current = tmp pre = pre * (1-probability[i]) print("%.12f" % current) if __name__ == "__main__": C()
Python
[ "math", "probabilities" ]
582
463
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
2,248
c3cd949c99e96c9da186a34d49bd6197
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.Alice is given a sequence of n composite numbers a_1,a_2,\ldots,a_n.She wants to choose an integer m \le 11 and color each element one of m colors from 1 to m so that: for each color from 1 to m there is at least one element of this color; each element is colored and colored exactly one color; the greatest common divisor of any two elements that are colored the same color is greater than 1, i.e. \gcd(a_i, a_j)>1 for each pair i, j if these elements are colored the same color. Note that equal elements can be colored different colors β€” you just have to choose one of m colors for each of the indices from 1 to n.Alice showed already that if all a_i \le 1000 then she can always solve the task by choosing some m \le 11.Help Alice to find the required coloring. Note that you don't have to minimize or maximize the number of colors, you just have to find the solution with some m from 1 to 11.
['greedy', 'constructive algorithms', 'number theory', 'math', 'brute force']
def answer(n,A): dp=[1]*32 dp[0]=dp[1]=0 for i in range(2,32): if dp[i]==1: p=2*i while p<=31: if dp[p]==1: dp[p]=0 p+=i count=1 res=[0]*n for i in range(2,32): if dp[i]==1: flag=0 for j in range(n): if res[j]==0 and A[j]%i==0: flag=1 res[j]=count if flag==1: count+=1 return count,res t=int(input()) for i in range(t): n=int(input()) arr=list(map(int,input().split())) a,b=answer(n,arr) print(a-1) print(*b)
Python
[ "number theory", "math" ]
1,311
677
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,979
ad4bdd6cee78cbcd357e048cd342a42b
In the probability theory the following paradox called Benford's law is known: "In many lists of random numbers taken from real sources, numbers starting with digit 1 occur much more often than numbers starting with any other digit" (that's the simplest form of the law).Having read about it on Codeforces, the Hedgehog got intrigued by the statement and wishes to thoroughly explore it. He finds the following similar problem interesting in particular: there are N random variables, the i-th of which can take any integer value from some segment [Li;Ri] (all numbers from this segment are equiprobable). It means that the value of the i-th quantity can be equal to any integer number from a given interval [Li;Ri] with probability 1 / (Ri - Li + 1).The Hedgehog wants to know the probability of the event that the first digits of at least K% of those values will be equal to one. In other words, let us consider some set of fixed values of these random variables and leave only the first digit (the MSD β€” most significant digit) of each value. Then let's count how many times the digit 1 is encountered and if it is encountered in at least K per cent of those N values, than such set of values will be called a good one. You have to find the probability that a set of values of the given random variables will be a good one.
['dp', 'probabilities', 'math']
import math def get_count(x): if x == 0: return 0 y = 10 ** (len(str(x)) - 1) d = x // y if d == 1: count = x - y + 1 else: count = y #print(x, math.log10(x), int(math.log10(x)), y, d, count) while y > 1: y //= 10 count += y #print('get_count(%d) -> %d' % (x, count)) return count n = int(input()) total = [ 1.0 ] for i in range(n): low, high = map(int, input().split()) count = get_count(high) - get_count(low - 1) p = count / (high - low + 1) new_total = [ 0.0 for i in range(len(total) + 1) ] for i, q in enumerate(total): new_total[i] += (1 - p) * q new_total[i + 1] += p * q total = new_total k = int(input()) result = 1.0 for i in range(math.ceil(n * k / 100)): result -= total[i] #print(total) print(result)
Python
[ "math", "probabilities" ]
1,325
843
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
3,341
43081557fe2fbac39dd9b72b137b8fb0
Polycarp has a string s consisting of lowercase Latin letters.He encodes it using the following algorithm.He goes through the letters of the string s from left to right and for each letter Polycarp considers its number in the alphabet: if the letter number is single-digit number (less than 10), then just writes it out; if the letter number is a two-digit number (greater than or equal to 10), then it writes it out and adds the number 0 after. For example, if the string s is code, then Polycarp will encode this string as follows: 'c' β€” is the 3-rd letter of the alphabet. Consequently, Polycarp adds 3 to the code (the code becomes equal to 3); 'o' β€” is the 15-th letter of the alphabet. Consequently, Polycarp adds 15 to the code and also 0 (the code becomes 3150); 'd' β€” is the 4-th letter of the alphabet. Consequently, Polycarp adds 4 to the code (the code becomes 31504); 'e' β€” is the 5-th letter of the alphabet. Therefore, Polycarp adds 5 to the code (the code becomes 315045). Thus, code of string code is 315045.You are given a string t resulting from encoding the string s. Your task is to decode it (get the original string s by t).
['greedy', 'strings']
import string q = int(input()) for i in range(q): n = int(input()) str = list(input()) def my_function(x): return x[::-1] str = my_function(str) ans = [] while(len(str)): if int(str[0]) == 0: ans.append(string.ascii_lowercase[int(str[2] + str[1])-1]) del str[0:3] else: ans.append(string.ascii_lowercase[int(str[0])-1]) del str[0] answer = "".join(ans) print(my_function(answer))
Python
[ "strings" ]
1,231
433
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
77
cb8895ddd54ffbd898b1bf5e169feb63
You are given a tree consisting of n vertices. A tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a color assigned to it (a_v = 1 if the vertex v is white and 0 if the vertex v is black).You have to solve the following problem for each vertex v: what is the maximum difference between the number of white and the number of black vertices you can obtain if you choose some subtree of the given tree that contains the vertex v? The subtree of the tree is the connected subgraph of the given tree. More formally, if you choose the subtree that contains cnt_w white vertices and cnt_b black vertices, you have to maximize cnt_w - cnt_b.
['dp', 'dfs and similar', 'trees', 'graphs']
# NOT MY CODE # https://codeforces.com/contest/1324/submission/73179914 ## PYRIVAL BOOTSTRAP # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py # This decorator allows for recursion without actually doing recursion from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc ###################### import math from bisect import bisect_left, bisect_right from sys import stdin, stdout, setrecursionlimit from collections import Counter input = lambda: stdin.readline().strip() print = stdout.write #setrecursionlimit(10**6) n = int(input()) ls = list(map(int, input().split())) children = {} for i in range(1, n+1): children[i] = [] for i in range(n-1): a, b = map(int, input().split()) children[a].append(b) children[b].append(a) parent = [-1] ans = [-1] for i in range(1, n+1): parent.append(-1) ans.append(-1) visited = [False] for i in range(1, n+1): visited.append(False) @bootstrap def dfs(node): visited[node] = True ans[node] = 1 if ls[node-1] else -1 for i in children[node]: if not visited[i]: parent[i] = node tmp = (yield dfs(i)) if tmp>0: ans[node]+=tmp ans[node] = max(ans[node], 1 if ls[node-1] else -1) yield ans[node] dfs(1) visited = [False] for i in range(1, n+1): visited.append(False) @bootstrap def dfs(node): visited[node] = True if node!=1: ans[node] = max(ans[node], ans[parent[node]] if ans[node]>=0 else ans[parent[node]]-1) for i in children[node]: if not visited[i]: yield dfs(i) yield dfs(1) for i in range(1, n+1): print(str(ans[i])+' ') print('\n')
Python
[ "graphs", "trees" ]
739
2,185
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,666
c6c4a833843d479c94f9ebd3e2774775
A boy named Ayrat lives on planet AMI-1511. Each inhabitant of this planet has a talent. Specifically, Ayrat loves running, moreover, just running is not enough for him. He is dreaming of making running a real art.First, he wants to construct the running track with coating t. On planet AMI-1511 the coating of the track is the sequence of colored blocks, where each block is denoted as the small English letter. Therefore, every coating can be treated as a string.Unfortunately, blocks aren't freely sold to non-business customers, but Ayrat found an infinite number of coatings s. Also, he has scissors and glue. Ayrat is going to buy some coatings s, then cut out from each of them exactly one continuous piece (substring) and glue it to the end of his track coating. Moreover, he may choose to flip this block before glueing it. Ayrat want's to know the minimum number of coating s he needs to buy in order to get the coating t for his running track. Of course, he also want's to know some way to achieve the answer.
['dp', 'greedy', 'trees', 'strings']
s = input() t = input() revS = s[::-1] n = len(s) cur=1 start=-1 end=-1 revFlag=0 errFlag=0 i=0 res=[] while i < len(t): if s.find(t[i:i+cur]) != -1 and i+cur <= len(t) and s.find(t[i:i+cur]) + cur <= n: start = s.find(t[i:i+cur]) + 1 end = start + cur - 1 cur += 1 elif revS.find(t[i:i+cur]) != -1 and i+cur <= len(t) and revS.find(t[i:i+cur]) + cur <= n: start = n - revS.find(t[i:i+cur]) end = start - cur + 1 cur += 1 else: if (start == -1 and end == -1) and (s.find(t[i:i+cur]) == -1 and revS.find(t[i:i+cur]) == -1): errFlag = 1 break i += cur - 1 cur = 1 res.append(str(start) + " " + str(end)) start = -1 end = -1 if errFlag != 1: print(len(res)) for p in res: print(p) else: print(-1)
Python
[ "strings", "trees" ]
1,020
847
0
0
0
0
0
0
1
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 1 }
2,336
9a5bd9f937da55c3d26d5ecde6e50280
Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1Β·p2Β·...Β·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.
['number theory', 'math']
from collections import Counter from operator import __mul__ mod = 10 ** 9 + 7 n = input() p = map(int, raw_input().split()) p = Counter(p) prod = 1 exp = 1 perfsq=1 fl=0 for x,a in p.items(): if(a%2==1): fl=1 if(fl): for x,a in p.items(): exp*=(a+1) prod *= pow(x,(a),mod) prod%=mod print pow(prod,exp/2,mod) else: for x,a in p.items(): exp*=(a+1) prod *= pow(x,a/2,mod) prod%=mod print pow(prod,exp,mod)
Python
[ "math", "number theory" ]
268
498
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,755
801bf7c73c44c68eaa61c714d5aedf50
A string s of length n (1 \le n \le 26) is called alphabetical if it can be obtained using the following algorithm: first, write an empty string to s (i.e. perform the assignment s := ""); then perform the next step n times; at the i-th step take i-th lowercase letter of the Latin alphabet and write it either to the left of the string s or to the right of the string s (i.e. perform the assignment s := c+s or s := s+c, where c is the i-th letter of the Latin alphabet). In other words, iterate over the n first letters of the Latin alphabet starting from 'a' and etc. Each time we prepend a letter to the left of the string s or append a letter to the right of the string s. Strings that can be obtained in that way are alphabetical.For example, the following strings are alphabetical: "a", "ba", "ab", "bac" and "ihfcbadeg". The following strings are not alphabetical: "z", "aa", "ca", "acb", "xyz" and "ddcba".From the given string, determine if it is alphabetical.
['greedy', 'implementation', 'strings']
t = int(input()) import string def is_abc(S): abc = list(string.ascii_lowercase) del abc[0] if S == 'a': return True if S == '': return True if len(set(S)) == len(S) and 'a' in S: a = S.index('a') prev_S = list(reversed(S[:a])) post_S = S[a+1:] c = len(prev_S) + len(post_S) for i in range(c): current_S = abc[i] prev = prev_S[0] if prev_S else None post = post_S[0] if post_S else None if current_S == prev: del prev_S[0] elif current_S == post: del post_S[0] else: return False return True else: return False for i in range(t): S = list(input()) if is_abc(S): print('YES') else: print('NO')
Python
[ "strings" ]
1,087
866
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,795
9dc956306e2826229e393657f2d0d9bd
Professor GukiZ doesn't accept string as they are. He likes to swap some letters in string to obtain a new one.GukiZ has strings a, b, and c. He wants to obtain string k by swapping some letters in a, so that k should contain as many non-overlapping substrings equal either to b or c as possible. Substring of string x is a string formed by consecutive segment of characters from x. Two substrings of string x overlap if there is position i in string x occupied by both of them.GukiZ was disappointed because none of his students managed to solve the problem. Can you help them and find one of possible strings k?
['constructive algorithms', 'implementation', 'brute force', 'strings']
__author__ = 'trunghieu11' from string import ascii_lowercase def main(): s = raw_input() a = raw_input() b = raw_input() totalS = dict() totalA = dict() totalB = dict() for c in ascii_lowercase: totalS.setdefault(c, s.count(c)) totalA.setdefault(c, a.count(c)) totalB.setdefault(c, b.count(c)) maxA = min(totalS[c] / totalA[c] for c in ascii_lowercase if totalA[c] > 0) maxVal = [0, 0] for i in range(maxA + 1): tempS = totalS.copy() for c in ascii_lowercase: if totalA[c] > 0: tempS[c] -= totalA[c] * i remainB = min(tempS[c] / totalB[c] for c in ascii_lowercase if totalB[c] > 0) for c in ascii_lowercase: if totalB[c] > 0: tempS[c] -= totalB[c] * remainB if maxVal[0] + maxVal[1] < i + remainB: maxVal = [i, remainB] answer = maxVal[0] * a + maxVal[1] * b for c in ascii_lowercase: answer += c * (totalS[c] - totalA[c] * maxVal[0] - totalB[c] * maxVal[1]) print answer if __name__ == '__main__': main()
Python
[ "strings" ]
613
1,109
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,556
a4f183775262fdc42dc5fc621c196ec9
You have a string s β€” a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands: 'W' β€” move one cell up; 'S' β€” move one cell down; 'A' β€” move one cell left; 'D' β€” move one cell right. Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = \text{DSAWWAW} then Grid(s) is the 4 \times 3 grid: you can place the robot in the cell (3, 2); the robot performs the command 'D' and moves to (3, 3); the robot performs the command 'S' and moves to (4, 3); the robot performs the command 'A' and moves to (4, 2); the robot performs the command 'W' and moves to (3, 2); the robot performs the command 'W' and moves to (2, 2); the robot performs the command 'A' and moves to (2, 1); the robot performs the command 'W' and moves to (1, 1). You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).What is the minimum area of Grid(s) you can achieve?
['dp', 'greedy', 'math', 'implementation', 'data structures', 'brute force', 'strings']
import sys import math import bisect import atexit import io import heapq from collections import defaultdict, Counter MOD = int(1e9+7) # n = map(int, raw_input().split()) # input = map(int, raw_input().split()) def main(): n = map(int, raw_input().split())[0] for i in range(n): st = raw_input() dx, dy = defaultdict(list), defaultdict(list) x, y = 0, 0 mxx, mix, mxy, miy = 0, 0, 0, 0 dy[0].append(0) dx[0].append(0) for idx, c in enumerate(st): if c=='A': y-=1 dy[y].append(idx) if c=='D': y+=1 dy[y].append(idx) if c=='W': x+=1 dx[x].append(idx) if c=='S': x-=1 dx[x].append(idx) mxx = max(x, mxx) mix = min(mix, x) mxy = max(mxy, y) miy = min(miy, y) # print mxx,mix,mxy,miy xx, yy = 0, 0 if mxx!=0: if mxx - mix >1 and dx[mxx] and dx[mix] and dx[mxx][0] > dx[mix][-1]: xx = 1 if mix!=0: if mxx - mix >1 and dx[mxx] and dx[mix] and dx[mix][0] > dx[mxx][-1]: xx = 1 # print dy[mxy],mxy if mxy!=0: if mxy - miy >1 and dy[mxy] and dy[miy] and dy[mxy][0]>dy[miy][-1]: yy = 1 if miy!=0: if mxy - miy >1 and dy[mxy] and dy[miy] and dy[mxy][-1]<dy[miy][0]: yy = 1 print min((mxx-mix+1-xx)*(mxy-miy+1), (mxx-mix+1)*(mxy-miy+1-yy)) main()
Python
[ "math", "strings" ]
1,323
1,606
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,435
a9fd2e4bc5528a34f1f1b869cd391d71
You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?
['geometry']
from __future__ import division import sys n = int(raw_input()) if n <= 4: print "YES" sys.exit() pts = [] for i in range(n): pts.append(list(map(int,raw_input().split()))) def solve(c1, c2): taken = [0 for x in range(n)] ext = [] for i in range(n): if (pts[c2][1]-pts[c1][1])*(pts[i][0]-pts[c2][0])==(pts[i][1]-pts[c2][1])*(pts[c2][0]-pts[c1][0]): taken[i] = 1 if not taken[i]: ext.append(i) if len(ext) <= 2: return 1 c1 = ext[0] c2 = ext[1] for i in range(n): if (pts[c2][1]-pts[c1][1])*(pts[i][0]-pts[c2][0])==(pts[i][1]-pts[c2][1])*(pts[c2][0]-pts[c1][0]): taken[i] = 1 if sum(taken)==n: return 1 return 0 if solve(0,1) or solve(0,2) or solve(1,2): print "YES" else: print "NO"
Python
[ "geometry" ]
301
750
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,920
c0998741424cd53de41d31f0bbaef9a2
You've got string s, consisting of small English letters. Some of the English letters are good, the rest are bad.A substring s[l...r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2...s|s| (where |s| is the length of string s) is string slsl + 1...sr.The substring s[l...r] is good, if among the letters sl, sl + 1, ..., sr there are at most k bad ones (look at the sample's explanation to understand it more clear).Your task is to find the number of distinct good substrings of the given string s. Two substrings s[x...y] and s[p...q] are considered distinct if their content is different, i.e. s[x...y] β‰  s[p...q].
['data structures', 'strings']
s = input() L = input() k = int(input()) l=len(s) good = set() string = set() LIST = [chr(i) for i in range(97, 123)] for i in range(26): if L[i] == '1': good.add(LIST[i]) t = [s[i] not in good for i in range(l)] end = [0]*l sumbad = 0 i,j=0,0 while i<l: if j<l: sumbad+=t[j] if sumbad>k or j==l: sumbad-=t[i] end[i]=j i+=1 if sumbad>k: sumbad-=t[j] continue if j<l: j+=1 for i in range(len(s)): t = 0 for j in range(i, end[i]): t = (t*29 + ord(s[j])-96)&1152921504606846975 string.add(t) print(len(string))
Python
[ "strings" ]
609
627
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,935
d4774270c77128b1cc4a8f454ee544bd
Consider a sequence of distinct integers a_1, \ldots, a_n, each representing one node of a graph. There is an edge between two nodes if the two values are not coprime, i. e. they have a common divisor greater than 1.There are q queries, in each query, you want to get from one given node a_s to another a_t. In order to achieve that, you can choose an existing value a_i and create new value a_{n+1} = a_i \cdot (1 + a_i), with edges to all values that are not coprime with a_{n+1}. Also, n gets increased by 1. You can repeat that operation multiple times, possibly making the sequence much longer and getting huge or repeated values. What's the minimum possible number of newly created nodes so that a_t is reachable from a_s?Queries are independent. In each query, you start with the initial sequence a given in the input.
['brute force', 'constructive algorithms', 'dsu', 'graphs', 'hashing', 'math', 'number theory']
import itertools from sys import stdin def input(): # credits to https://codeforces.com/profile/aberent # wouldn't solve without this return next(stdin)[:-1] def readline(): return map(int, input().split()) primes = [2] primes.extend(q for q in range(3, 10**3, 2) if all(q % p for p in primes)) def prime_divisors(n): for p in primes: if p * p > n: break if n % p == 0: yield p while n % p == 0: n //= p if n > 1: yield n class DSU: # naΓ―ve implementation, no optimizations def __init__(self): self.p = dict() # parent def _get_root(self, a): while a in self.p: a = self.p[a] return a def __setitem__(self, a, b): r = self._get_root(b) while a != r: # attach all ancestors of a to root(b) self.p[a], a = r, self.p.get(a, a) def __getitem__(self, a): self[a] = a # flatten, attach all ancestors of a to root(a) return self.p.get(a, a) def main(): n, q = readline() a = list(readline()) queries = (readline() for __ in range(q)) # overriding q later :P min_divisor = list() dsu = DSU() for ai in a: p, *rest = prime_divisors(ai) min_divisor.append(p) for q in rest: dsu[q] = p def sorted_tuple(t): return tuple(sorted(t)) one = set() # pairs of components reachable with 1 operation for (ai, p) in zip(a, min_divisor): new_node = {dsu[p], *(dsu[q] for q in prime_divisors(ai + 1))} one.update(map(sorted_tuple, itertools.combinations(new_node, 2))) for (s, t) in queries: p = dsu[min_divisor[s-1]] q = dsu[min_divisor[t-1]] if p == q: print(0) elif sorted_tuple((p, q)) in one: print(1) else: print(2) if __name__ == '__main__': main() # t.me/belkka
Python
[ "graphs", "number theory", "math" ]
903
1,953
0
0
1
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
424
66e86d612d676068689ae714b453ef32
This is an interactive problem!Ehab has a hidden permutation p of length n consisting of the elements from 0 to n-1. You, for some reason, want to figure out the permutation. To do that, you can give Ehab 2 different indices i and j, and he'll reply with (p_i|p_j) where | is the bitwise-or operation.Ehab has just enough free time to answer 4269 questions, and while he's OK with answering that many questions, he's too lazy to play your silly games, so he'll fix the permutation beforehand and will not change it depending on your queries. Can you guess the permutation?
['constructive algorithms', 'bitmasks', 'probabilities', 'divide and conquer', 'interactive']
from random import sample import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] memo={} def ask(i,j): if i>j:i,j=j,i if (i,j) in memo:return memo[i,j] print("?",i+1,j+1,flush=True) res=II() memo[i,j]=res return res n=II() a,b=0,1 for c in sample(range(2,n),n-2): ab=ask(a,b) bc=ask(b,c) if ab==bc:b=c if ab>bc:a=c ab=ask(a,b) for (i,j),v in memo.items(): if ab&v!=ab: if i in [a,b]:i=j if i in [a,b]:continue ac = ask(a, i) bc = ask(b, i) if ac < bc: z = a else: z = b break else: for c in sample(range(n),n): if a==c or b==c:continue ac=ask(a,c) bc=ask(b,c) if ac==bc:continue if ac<bc:z=a else:z=b break ans=[] for i in range(n): if i==z:ans.append(0) else:ans.append(ask(z,i)) print("!",*ans,flush=True)
Python
[ "probabilities" ]
632
1,200
0
0
0
0
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
1,322
79d26192a25cd51d27e916adeb97f9d0
Two soldiers are playing a game. At the beginning first of them chooses a positive integer n and gives it to the second soldier. Then the second one tries to make maximum possible number of rounds. Each round consists of choosing a positive integer x &gt; 1, such that n is divisible by x and replacing n with n / x. When n becomes equal to 1 and there is no more possible valid moves the game is over and the score of the second soldier is equal to the number of rounds he performed.To make the game more interesting, first soldier chooses n of form a! / b! for some positive integer a and b (a β‰₯ b). Here by k! we denote the factorial of k that is defined as a product of all positive integers not large than k.What is the maximum possible score of the second soldier?
['dp', 'constructive algorithms', 'number theory', 'math']
''' def isPrime(n) : # Corner cases if (n <= 1) : return False if (n <= 3) : return True # This is checked so that we can skip # middle five numbers in below loop if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True cnt = 0 for i in range(2,5*10**6+1): if isPrime(i): cnt+=1 print(cnt) ''' ''' n = 5*10**6+1 N = 5*10**6 prime = [False] * (N+1) s = [0] * (N+1) def sieveOfEratosthenes(): # Create a boolean array # "prime[0..n]" and initialize # all entries in it as false. # Initializing smallest factor # equal to 2 for all the even # numbers for i in range(2, N+1, 2): s[i] = 2 # For odd numbers less then # equal to n for i in range(3, N+1, 2): if (prime[i] == False): # s(i) for a prime is # the number itself s[i] = i # For all multiples of # current prime number for j in range(i, int(N / i) + 1, 2): if (prime[i*j] == False): prime[i*j] = True # i is the smallest # prime factor for # number "i*j". s[i * j] = i # Function to generate prime # factors and its power def generatePrimeFactors(x): # s[i] is going to store # smallest prime factor # of i. # s = [0] * (N+1) # Filling values in s[] # using sieve # sieveOfEratosthenes(N, s) # print("Factor Power") # Current prime factor of N curr = s[x] # Power of current prime factor cnt = 1 # Printing prime factors and #their powers ans = 0 while (x > 1): x //= s[x] # N is now N/s[N]. If new N # als has smallest prime # factor as curr, increment # power if (curr == s[x]): cnt += 1 continue ans += cnt # print(str(curr) + "\t" + str(cnt)) # Update current prime factor # as s[N] and initializing # count as 1. curr = s[x] cnt = 1 # print(x) return ans sieveOfEratosthenes() # print(s[2],s[8],generatePrimeFactors(8)) dp = [0]*n for i in range(2,n): dp[i] = generatePrimeFactors(i) # if dp[i]!=0: # continue # for j in range(i,n): # if i*j>=n: # break # if # dp[i*j] += 1 # dp[i]=1 dp[i]+=dp[i-1] # for i in range(1,10): # print(dp[i],i) ''' from sys import stdin, stdout r = map(int,stdin.read().split()) n = 5*10**6+1 dp = [0]*n for i in range(2,n): if dp[i]==0: for j in range(i,n,i): dp[j] = dp[j//i]+1 for i in range(1,n): dp[i] += dp[i-1] t = next(r) while t>0: t-=1 a = next(r) b = next(r) # print(dp[a],dp[b]) print(dp[a]-dp[b])
Python
[ "number theory", "math" ]
770
3,116
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,596
5be268e0607f2d654d7f5ae4f11e2f08
Pak Chanek has n blank heart-shaped cards. Card 1 is attached directly to the wall while each of the other cards is hanging onto exactly one other card by a piece of string. Specifically, card i (i &gt; 1) is hanging onto card p_i (p_i &lt; i).In the very beginning, Pak Chanek must write one integer number on each card. He does this by choosing any permutation a of [1, 2, \dots, n]. Then, the number written on card i is a_i.After that, Pak Chanek must do the following operation n times while maintaining a sequence s (which is initially empty): Choose a card x such that no other cards are hanging onto it. Append the number written on card x to the end of s. If x \neq 1 and the number on card p_x is larger than the number on card x, replace the number on card p_x with the number on card x. Remove card x. After that, Pak Chanek will have a sequence s with n elements. What is the maximum length of the longest non-decreasing subsequence^\dagger of s at the end if Pak Chanek does all the steps optimally?^\dagger A sequence b is a subsequence of a sequence c if b can be obtained from c by deletion of several (possibly, zero or all) elements. For example, [3,1] is a subsequence of [3,2,1], [4,3,1] and [3,1], but not [1,3,3,7] and [3,10,4].
['constructive algorithms', 'data structures', 'dfs and similar', 'dp', 'greedy', 'trees']
import sys, threading from collections import defaultdict def main(): def dfs(node): d = 1 childs_sum = 0 for adj in tree[node]: child_depth,childs_val = dfs(adj) d = max(d, 1 + child_depth) childs_sum += childs_val return (d,max(childs_sum,d)) n = int(input()) pars = list(map(int, input().split())) tree = defaultdict(list) for i in range(n - 1): v = pars[i] tree[v].append(i + 2) res = dfs(1) print(max(*res)) sys.setrecursionlimit(1 << 30) threading.stack_size(1 << 27) main_thread = threading.Thread(target = main) main_thread.start() main_thread.join()
Python
[ "graphs", "trees" ]
1,471
720
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,496
732b5f6aeec05b721122e36116c7ab0c
Sam has been teaching Jon the Game of Stones to sharpen his mind and help him devise a strategy to fight the white walkers. The rules of this game are quite simple: The game starts with n piles of stones indexed from 1 to n. The i-th pile contains si stones. The players make their moves alternatively. A move is considered as removal of some number of stones from a pile. Removal of 0 stones does not count as a move. The player who is unable to make a move loses.Now Jon believes that he is ready for battle, but Sam does not think so. To prove his argument, Sam suggested that they play a modified version of the game.In this modified version, no move can be made more than once on a pile. For example, if 4 stones are removed from a pile, 4 stones cannot be removed from that pile again.Sam sets up the game and makes the first move. Jon believes that Sam is just trying to prevent him from going to battle. Jon wants to know if he can win if both play optimally.
['dp', 'bitmasks', 'games']
ans=0 for _ in range(int(input())): ans^=int((8*int(input())+1)**0.5-1)//2 print(['YES', 'NO'][ans>0])
Python
[ "games" ]
968
106
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,137
83ec573ad007d9385d6f0bb8f02b24e2
Heidi's friend Jenny is asking Heidi to deliver an important letter to one of their common friends. Since Jenny is Irish, Heidi thinks that this might be a prank. More precisely, she suspects that the message she is asked to deliver states: "Send the fool further!", and upon reading it the recipient will ask Heidi to deliver the same message to yet another friend (that the recipient has in common with Heidi), and so on.Heidi believes that her friends want to avoid awkward situations, so she will not be made to visit the same person (including Jenny) twice. She also knows how much it costs to travel between any two of her friends who know each other. She wants to know: what is the maximal amount of money she will waste on travel if it really is a prank?Heidi's n friends are labeled 0 through n - 1, and their network of connections forms a tree. In other words, every two of her friends a, b know each other, possibly indirectly (there is a sequence of friends starting from a and ending on b and such that each two consecutive friends in the sequence know each other directly), and there are exactly n - 1 pairs of friends who know each other directly.Jenny is given the number 0.
['dfs and similar', 'trees', 'graphs']
# maa chudaaye duniya from collections import defaultdict graph = defaultdict(list) n = int(input()) weights = {} for _ in range(n-1): a, b, w = map(int, input().split()) edge1 = '{} : {}'.format(a, b) edge2 = '{} : {}'.format(b, a) graph[a].append(b) graph[b].append(a) weights[edge1] = w weights[edge2] = w maxsf = [-10**9] visited = [False for i in range(n+1)] def dfs(node, parent, dist): visited[node] = True # print(maxsf) # print('checking ', node, parent) # print(visited) if parent != -1: e ='{} : {}'.format(parent, node) e1 = '{} : {}'.format(node, parent) if e in weights: dist += weights[e] # print(e, dist) else: dist += weights[e1] # print(e1, dist) if dist > maxsf[0]: maxsf[0] = dist for children in graph[node]: if not visited[children]: dfs(children, node, dist) dfs(0, -1, 0) print(*maxsf)
Python
[ "graphs", "trees" ]
1,191
856
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,741
c207550a5a74098c1d50407d12a2baec
A permutation of length k is a sequence of k integers from 1 to k containing each integer exactly once. For example, the sequence [3, 1, 2] is a permutation of length 3.When Neko was five, he thought of an array a of n positive integers and a permutation p of length n - 1. Then, he performed the following: Constructed an array b of length n-1, where b_i = \min(a_i, a_{i+1}). Constructed an array c of length n-1, where c_i = \max(a_i, a_{i+1}). Constructed an array b' of length n-1, where b'_i = b_{p_i}. Constructed an array c' of length n-1, where c'_i = c_{p_i}. For example, if the array a was [3, 4, 6, 5, 7] and permutation p was [2, 4, 1, 3], then Neko would have constructed the following arrays: b = [3, 4, 5, 5] c = [4, 6, 6, 7] b' = [4, 5, 3, 5] c' = [6, 7, 4, 6] Then, he wrote two arrays b' and c' on a piece of paper and forgot about it. 14 years later, when he was cleaning up his room, he discovered this old piece of paper with two arrays b' and c' written on it. However he can't remember the array a and permutation p he used.In case Neko made a mistake and there is no array a and permutation p resulting in such b' and c', print -1. Otherwise, help him recover any possible array a.
['constructive algorithms', 'dfs and similar', 'graphs']
class multiset: def __init__(self): self.contenido = dict() self.len = 0 def add(self, x): self.contenido[x] = self.contenido.get(x, 0)+1 self.len += 1 def remove(self, x): valor = self.contenido.get(x, 1)-1 if valor == 0: del self.contenido[x] else: self.contenido[x] = valor self.len -= 1 def pop(self): x = next(iter(self.contenido.keys())) self.remove(x) return x def __len__(self): return self.len def __str__(self): return str(self.contenido) n = int(input()) b = [int(a) for a in input().split()] c = [int(a) for a in input().split()] for x, y in zip(b, c): if x > y: print(-1) exit() trad = dict() contador = 0 for a in b+c: if not a in trad: trad[a] = contador contador += 1 v = [multiset() for _ in range(contador)] auxb = [trad[a] for a in b] auxc = [trad[a] for a in c] for x, y in zip(auxb, auxc): v[x].add(y) v[y].add(x) impares = [] for i, a in enumerate(v): if len(a)%2: impares.append(i) primero = 0 if len(impares) == 2: primero = impares[0] elif len(impares) != 0: print(-1) exit() stack = [primero] sol = [] while len(stack): p = stack[-1] if len(v[p]) == 0: sol.append(p) stack.pop() else: h = v[p].pop() v[h].remove(p) stack.append(h) tradaux = {v: k for k, v in trad.items()} if len(sol) != n: print(-1) exit() for i in sol: print(tradaux[i])
Python
[ "graphs" ]
1,462
1,355
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,244
cb05d81d82d16ac3fdf8ec33e69d5ae8
This is an interactive problem.Given a simple undirected graph with n vertices numbered from 1 to n, your task is to color all the vertices such that for every color c, the following conditions hold: The set of vertices with color c is connected; s_c \leq n_c^2, where n_c is the number of vertices with color c, and s_c is the sum of degrees of vertices with color c. It can be shown that there always exists a way to color all the vertices such that the above conditions hold. Initially, you are only given the number n of vertices and the degree of each vertex. In each query, you can choose a vertex u. As a response, you will be given the k-th edge incident to u, if this is the k-th query on vertex u. You are allowed to make at most n queries.An undirected graph is simple if it does not contain multiple edges or self-loops.The degree of a vertex is the number of edges incident to it. A set S of vertices is connected if for every two different vertices u, v \in S, there is a path, which only passes through vertices in S, that connects u and v. That is, there is a sequence of edges (u_1, v_1), (u_2, v_2), \dots, (u_k, v_k) with k \geq 1 such that u_1 = u, v_k = v, and v_i = u_{i+1} for every 1 \leq i &lt; k; and u_k \in S and v_k \in S for every 1 \leq i \leq k. Especially, a set containing only one vertex is connected.
['constructive algorithms', 'dsu', 'graphs', 'greedy', 'interactive', 'shortest paths', 'trees']
#!/usr/bin/env python3 import sys, getpass import math, random import functools, itertools, collections, heapq, bisect from collections import Counter, defaultdict, deque input = sys.stdin.readline # to read input quickly # available on Google, AtCoder Python3, not available on Codeforces # import numpy as np # import scipy m9 = 10**9 + 7 # 998244353 # d4 = [(1,0),(0,1),(-1,0),(0,-1)] # d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)] # d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout MAXINT = sys.maxsize e18 = 10**18 + 10 # if testing locally, print to terminal with a different color OFFLINE_TEST = getpass.getuser() == "htong" # OFFLINE_TEST = False # codechef does not allow getpass def log(*args): if OFFLINE_TEST: print('\033[36m', *args, '\033[0m', file=sys.stderr) # ---------------------------- template ends here ---------------------------- def query(pos): print("? {}".format(pos+1), flush=True) response = int(input()) - 1 assert response >= 0 return response def alert(arr): print("! {}".format(" ".join(str(x) for x in arr)), flush=True) # ----------------------------------------------------------------------------- class DisjointSet: # github.com/not522/ac-library-python/blob/master/atcoder/dsu.py def __init__(self, n: int = 0) -> None: if n > 0: # constant size DSU self.parent_or_size = [-1]*n else: self.parent_or_size = defaultdict(lambda: -1) def union(self, a: int, b: int) -> int: x = self.find(a) y = self.find(b) if x == y: return x if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def find(self, a: int) -> int: parent = self.parent_or_size[a] while parent >= 0: if self.parent_or_size[parent] < 0: return parent self.parent_or_size[a], a, parent = ( self.parent_or_size[parent], self.parent_or_size[parent], self.parent_or_size[self.parent_or_size[parent]] ) return a def size(self, a: int) -> int: return -self.parent_or_size[self.find(a)] import random # get highest degree # get adjacent nodes # if nodes is in previous group, join for case_num in range(int(input())): # read line as an integer n = int(input()) # read line as a string # srr = input().strip() # read one line and parse each word as a string # lst = input().split() ds = DisjointSet(n) for i in range(n): ds.find(i) # read one line and parse each word as an integer # a,b,c = list(map(int,input().split())) degrees = list(map(int,input().split())) taken = set() arr = [(x,i) for i,x in enumerate(degrees)] # random.shuffle(arr) arr.sort() # arr.reverse() # log(arr) query_cnt = 0 while arr: x,cur = arr.pop() if cur in taken: continue taken.add(cur) for _ in range(x): nex = query(cur) query_cnt += 1 ds.union(cur, nex) if nex in taken: break taken.add(nex) assert query_cnt <= n for i in range(n): ldr = ds.find(i) cntr = 1 val_to_cntr = {} for i in range(n): ldr = ds.find(i) if ldr not in val_to_cntr: val_to_cntr[ldr] = cntr cntr += 1 res = [-1 for _ in range(n)] for i in range(n): res[i] = val_to_cntr[ds.find(i)] assert max(res) <= n assert min(res) >= 1 cnt_nodes = defaultdict(int) cnt_edges = defaultdict(int) for i,x in enumerate(res): cnt_nodes[x] += 1 cnt_edges[x] += degrees[i] for i in cnt_nodes.keys(): assert cnt_edges[i] <= cnt_nodes[i]**2 alert(res) # ----------------------------------------------------------------------------- # your code here sys.exit()
Python
[ "graphs", "trees" ]
1,531
4,111
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,104
81f4bc9ac72ed39da8614131954d0d99
You are given array a_1, a_2, \ldots, a_n, consisting of non-negative integers.Let's define operation of "elimination" with integer parameter k (1 \leq k \leq n) as follows: Choose k distinct array indices 1 \leq i_1 &lt; i_2 &lt; \ldots &lt; i_k \le n. Calculate x = a_{i_1} ~ \&amp; ~ a_{i_2} ~ \&amp; ~ \ldots ~ \&amp; ~ a_{i_k}, where \&amp; denotes the bitwise AND operation (notes section contains formal definition). Subtract x from each of a_{i_1}, a_{i_2}, \ldots, a_{i_k}; all other elements remain untouched. Find all possible values of k, such that it's possible to make all elements of array a equal to 0 using a finite number of elimination operations with parameter k. It can be proven that exists at least one possible k for any array a.Note that you firstly choose k and only after that perform elimination operations with value k you've chosen initially.
['bitmasks', 'math', 'number theory']
def getint(): return [int(i) for i in input().split()] def get(): return int(input()) def getstr(): return [i for i in input().split()] def S(): for test in range(int(input())): solve() import math import itertools as it import bisect import time import collections as ct def solve(): b=[0]*32 n=get() a=getint() for i in a: x=bin(i)[2:] x=x[::-1] for j in range(len(x)): b[j]+=int(x[j]) ans=[int(i) for i in range(1,n+1)] for i in range(1,n+1): for j in range(0,31): if b[j]%i: ans[i-1]=0 for i in range(n): if ans[i]: print(ans[i],end=" ") print() S()
Python
[ "math", "number theory" ]
977
737
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,336
e2dc3de62fc45c7e9ddb92daa5c5d8de
A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you dΓ©jΓ  vu.There is a string s. You must insert exactly one character 'a' somewhere in s. If it is possible to create a string that is not a palindrome, you should find one example. Otherwise, you should report that it is impossible.For example, suppose s= "cbabc". By inserting an 'a', you can create "acbabc", "cababc", "cbaabc", "cbabac", or "cbabca". However "cbaabc" is a palindrome, so you must output one of the other options.
['constructive algorithms', 'strings']
n = int(input()) while n > 0: s = input() if "a" + s != s[::-1] + "a": print("YES") print("a" + s) elif s + "a" != "a" + s[::-1]: print("YES") print(s + "a") else: print("NO") n -= 1
Python
[ "strings" ]
666
244
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
260
711896281f4beff55a8826771eeccb81
You're given a tree with n vertices.Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
['dp', 'greedy', 'graphs', 'dfs and similar', 'trees']
from collections import deque f=[(1,-1)] def bfs(x): dist=[-1]*(n+2) dist[x]=0 q=deque() q.append(x) while q: t=q.popleft() for i in dp[t]: # print i,"i",dist[t],t if dist[i]==-1: q.append(i) f.append((i,t)) dist[i]=dist[t]+1 m=max(dist) #print dist #return dist.index(m),m n=input() dist=[0]*(n+2) dp=[] m=n-1 for i in range(0,m+2): dp.append([]) for _ in range(0,m): a,b=map(int,raw_input().split()) dp[a].append(b) dp[b].append(a) #print dp bfs(1) ans=0 for i in dist: if i!=0 and i%2==0: ans=ans+1 if n%2==1: print -1 else: # print ans-1 f.reverse() dp2=[1]*(n+2) for i in f: child=i[0] parent=i[1] if parent!=-1: dp2[parent]=dp2[parent]+dp2[child] s=0 for i in dp2: if i%2==0: s=s+1 print s-1
Python
[ "graphs", "trees" ]
203
934
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
390
3a305e2cc38ffd3dc98f21209e83b68d
Diana loves playing with numbers. She's got n cards with positive integer numbers a_i written on them. She spends her free time multiplying the numbers on the cards. She picks a non-empty subset of the cards and multiplies all the numbers a_i written on them.Diana is happy when the product of the numbers ends with her favorite digit d. Now she is curious what cards she should pick so that the product of the numbers on them is the largest possible and the last decimal digit of the product is d. Please, help her.
['dp', 'math', 'number theory']
S_133 = [ (0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (0, 1, 0), (0, 2, 0), (0, 3, 0), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (1, 1, 0), (1, 2, 0), (1, 3, 0), ] def pow_mod10(b, p): if p == 0: return 1 return pow(b, 4 + p % 4, 10) def solve(a, d): nums_by_units = [] for i in range(10): nums_by_units.append([]) overall_p_mod = 1 odd_prod_mod = 1 for x in a: r = x % 10 nums_by_units[r].append(x) overall_p_mod = (overall_p_mod * r) % 10 if r % 2 == 1 and r != 5: odd_prod_mod = (odd_prod_mod * r) % 10 for i in range(10): nums_by_units[i].sort() if d == overall_p_mod: return a if d == 0: if d != overall_p_mod: return [] return a if d == 5: if len(nums_by_units[5]) == 0: return [] return sum([nums_by_units[r] for r in [1, 3, 5, 7, 9]], []) if d in [1, 3, 7, 9]: if all(len(nums_by_units[r]) == 0 for r in [1, 3, 7, 9]): return [] if d == odd_prod_mod: return sum([nums_by_units[r] for r in [1, 3, 7, 9]], []) f = [0] * 10 f[0] = len(nums_by_units[0]) f[5] = len(nums_by_units[5]) if d % 2 == 1: f[6] = len(nums_by_units[6]) f428_set = [(len(nums_by_units[4]), len(nums_by_units[2]), len(nums_by_units[8]))] else: f[6] = 0 f428_set = S_133[:] f937_set = S_133[:] min_f = None min_removed_prod = None p_mod_init = pow_mod10(6, len(nums_by_units[6]) - f[6]) I = [4, 2, 8, 9, 3, 7] for f[4], f[2], f[8] in f428_set: for f[9], f[3], f[7] in f937_set: if all(f[i] <= len(nums_by_units[i]) for i in I): p_mod = p_mod_init removed_prod = 1 for i in I: if d % 2 == 0 or i % 2 == 1: p_mod = (p_mod * pow_mod10(i, len(nums_by_units[i]) - f[i])) % 10 for j in range(f[i]): removed_prod *= nums_by_units[i][j] if p_mod == d and (min_removed_prod is None or min_removed_prod > removed_prod): min_removed_prod = removed_prod min_f = f[:] if min_removed_prod == 1: break if min_f: return sum([nums_by_units[i][min_f[i]:] for i in range(10)], []) return [] if __name__ == "__main__": n, d = map(int, input().split()) a = [*map(int, input().split())] ans = solve(a, d) if not ans: print(-1) else: print(len(ans)) print(*ans)
Python
[ "math", "number theory" ]
546
2,325
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,325
55c692d380a4d1c0478ceb7cffde342f
You are given a rooted tree. Each vertex contains a_i tons of gold, which costs c_i per one ton. Initially, the tree consists only a root numbered 0 with a_0 tons of gold and price c_0 per ton.There are q queries. Each query has one of two types: Add vertex i (where i is an index of query) as a son to some vertex p_i; vertex i will have a_i tons of gold with c_i per ton. It's guaranteed that c_i &gt; c_{p_i}. For a given vertex v_i consider the simple path from v_i to the root. We need to purchase w_i tons of gold from vertices on this path, spending the minimum amount of money. If there isn't enough gold on the path, we buy all we can. If we buy x tons of gold in some vertex v the remaining amount of gold in it decreases by x (of course, we can't buy more gold that vertex has at the moment). For each query of the second type, calculate the resulting amount of gold we bought and the amount of money we should spend.Note that you should solve the problem in online mode. It means that you can't read the whole input at once. You can read each query only after writing the answer for the last query, so don't forget to flush output after printing answers. You can use functions like fflush(stdout) in C++ and BufferedWriter.flush in Java or similar after each writing in your program. In standard (if you don't tweak I/O), endl flushes cout in C++ and System.out.println in Java (or println in Kotlin) makes automatic flush as well.
['binary search', 'data structures', 'dp', 'greedy', 'interactive', 'trees']
from array import array import math import os import sys input = sys.stdin.buffer.readline q, a0, c0 = map(int, input().split()) mod = pow(10, 9) + 7 n = q + 5 pow2 = [1] for _ in range(20): pow2.append(2 * pow2[-1]) cnt = [0] * n cost = [0] * n cnt[0], cost[0] = a0, c0 dp = array("l", [-1] * (20 * n)) dist = [-1] * n dist[0] = 1 l0 = [-1] * n for i in range(1, q + 1): t = list(map(int, input().split())) if t[0] == 1: p, a, c = t[1], t[2], t[3] cnt[i] = a cost[i] = c j = 0 dp[20 * i] = p while dp[20 * dp[20 * i + j] + j] ^ -1: dp[20 * i + j + 1] = dp[20 * dp[20 * i + j] + j] j += 1 dist[i] = dist[p] + 1 else: v, w = t[1], t[2] if not v: u = 0 x = min(w, cnt[u]) cnt[u] -= x ans = [str(x), str(x * cost[0])] os.write(1, b"%d %d\n" % (x, x * cost[0])) continue d, j, l = 0, v, int(math.log2(dist[v])) + 1 for k in range(l - 1, -1, -1): m = dp[20 * j + k] if cnt[m]: d += pow2[k] j = m u0 = j ans0, ans1, ans2 = 0, 0, 0 for j in range(d, -1, -1): if j ^ d: d0, u, k = j, v, 0 while d0: if d0 & pow2[k]: d0 ^= pow2[k] u = dp[20 * u + k] k += 1 else: u = u0 x = min(w - ans0, cnt[u]) cnt[u] -= x ans0 += x ans1 += x * cost[u] % mod ans2 += x * cost[u] // mod ans2 += ans1 // mod ans1 %= mod if not ans0 ^ w: break ans = [str(ans0), str(ans1 + ans2 * mod)] os.write(1, b"%d %d\n" % (ans0, ans1 + ans2 * mod))
Python
[ "trees" ]
1,561
1,947
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,298
a4101af56ea6afdfaa510572eedd6320
You are given a tree with n nodes, numerated from 0 to n-1. For each k between 0 and n, inclusive, you have to count the number of unordered pairs (u,v), u \neq v, such that the MEX of all the node labels in the shortest path from u to v (including end points) is k.The MEX of a sequence of integers is the smallest non-negative integer that does not belong to the sequence.
['combinatorics', 'dfs and similar', 'implementation', 'math', 'trees']
import sys input = sys.stdin.buffer.readline class RangeQuery: def __init__(self, data, func=min): self.func = func self._data = _data = [list(data)] i, n = 1, len(_data[0]) while 2 * i <= n: prev = _data[-1] _data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)]) i <<= 1 def query(self, begin, end): depth = (end - begin).bit_length() - 1 return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)]) class LCA: def __init__(self, root, graph): self.time = [-1] * len(graph) self.path = [-1] * len(graph) P = [-1] * len(graph) t = -1 dfs = [root] while dfs: node = dfs.pop() self.path[t] = P[node] self.time[node] = t = t + 1 for nei in graph[node]: if self.time[nei] == -1: P[nei] = node dfs.append(nei) self.rmq = RangeQuery(self.time[node] for node in self.path) def __call__(self, a, b): if a == b: return a a = self.time[a] b = self.time[b] if a > b: a, b = b, a return self.path[self.rmq.query(a, b)] def process(n, G): g = [[] for i in range(n)] for u, v in G: g[u].append(v) g[v].append(u) """ Step One: Generate LCA and size of all subtrees rooted at zero. """ L = LCA(0, g) size = [0 for i in range(n)] parent = [None for i in range(n)] depth = [[0]] parent[0] = -1 while True: next_s = [] for x in depth[-1]: for y in g[x]: if parent[y] is None: parent[y] = x next_s.append(y) if len(next_s)==0: break depth.append(next_s) while len(depth) > 0: for x in depth.pop(): size[x]+=1 if parent[x] != -1: size[parent[x]]+=size[x] seen_yet = [0 for i in range(n+2)] """ Step 2: answer1[i] = number of pairs with mex >= i IE number of pairs whose path includes everything from 0 to i-1 """ answer1 = [None for i in range(n+1)] """ Step 3: answer1[0] = all possible pairs. """ answer1[0] = n*(n-1)//2 """ Step 4: answer1[1] = all possible pairs except those in the same subtree of 0 """ answer1[1] = n*(n-1)//2 for x in g[0]: s1 = size[x] answer1[1]-=(s1*(s1-1))//2 """ Step 5: answer1[2] = all possible pairs where one is a descendant of 1 and the other is a descendant of 0 (but on another subtree) """ path = [1] while path[-1] != 0: x = path[-1] path.append(parent[x]) s1 = size[1] s0 = 1 for x in g[0]: if x != path[-2]: s0+=size[x] answer1[2] = s1*s0 """ Step 6: Everything on the path from 1 to 0 if we have say, 2, 3, 4, 5 then they are the same as 2 """ for x in path: seen_yet[x] = 1 smallest_unseen = 1 while seen_yet[smallest_unseen]==1: answer1[smallest_unseen+1] = answer1[2] smallest_unseen+=1 """ Step 7: we have a path from 1 to 0 that also contains 2, ..., I-1, if anything find the first my_mex after that such that my_mex-1 is not a descendant of 1 or on that series of paths. """ p1 = 0 p2 = 1 """ Step 8: Similar but now separate subtrees. """ last_bad = None while smallest_unseen <= n-1: if answer1[smallest_unseen+1] is None: if L(smallest_unseen, p2)==p2: path = [smallest_unseen] while path[-1] != p2: x2 = path[-1] path.append(parent[x2]) s1 = size[smallest_unseen] if p1==0: s2 = s0 else: s2 = size[p1] for x2 in path: seen_yet[x2] = 1 p2 = smallest_unseen while seen_yet[smallest_unseen]==1: answer1[smallest_unseen+1] = s1*s2 smallest_unseen+=1 elif L(smallest_unseen, p1)==p1 and (p1 > 0 or L(smallest_unseen, p2)==p1): path = [smallest_unseen] while path[-1] != p1: x2 = path[-1] path.append(parent[x2]) s1 = size[smallest_unseen] s2 = size[p2] p1 = smallest_unseen for x2 in path: seen_yet[x2] = 1 while seen_yet[smallest_unseen]==1: answer1[smallest_unseen+1] = s1*s2 smallest_unseen+=1 else: last_bad = smallest_unseen+1 break if last_bad is not None: for i in range(last_bad, n+1): answer1[i] = 0 answer = [None for i in range(n+1)] for i in range(n): answer[i] = answer1[i]-answer1[i+1] answer[n] = answer1[n] answer = ' '.join(map(str, answer)) sys.stdout.write(f'{answer}\n') t = int(input()) for i in range(t): n = int(input()) G = [] for i in range(n-1): u, v = [int(x) for x in input().split()] G.append([u, v]) process(n, G)
Python
[ "math", "graphs", "trees" ]
440
5,767
0
0
1
1
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
965
85f43628bec7e9b709273c34b894df6b
In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.One example of a grid path is (0, 0) β†’ (0, 1) β†’ (0, 2) β†’ (1, 2) β†’ (1, 1) β†’ (0, 1) β†’ ( - 1, 1). Note that squares in this sequence might be repeated, i.e. path has self intersections.Movement within a grid path is restricted to adjacent squares within the sequence. That is, from the i-th square, one can only move to the (i - 1)-th or (i + 1)-th squares of this path. Note that there is only a single valid move from the first and last squares of a grid path. Also note, that even if there is some j-th square of the path that coincides with the i-th square, only moves to (i - 1)-th and (i + 1)-th squares are available. For example, from the second square in the above sequence, one can only move to either the first or third squares.To ensure that movement is not ambiguous, the two grid paths will not have an alternating sequence of three squares. For example, a contiguous subsequence (0, 0) β†’ (0, 1) β†’ (0, 0) cannot occur in a valid grid path.One marble is placed on the first square of each grid path. Genos wants to get both marbles to the last square of each grid path. However, there is a catch. Whenever he moves one marble, the other marble will copy its movement if possible. For instance, if one marble moves east, then the other marble will try and move east as well. By try, we mean if moving east is a valid move, then the marble will move east.Moving north increases the second coordinate by 1, while moving south decreases it by 1. Similarly, moving east increases first coordinate by 1, while moving west decreases it.Given these two valid grid paths, Genos wants to know if it is possible to move both marbles to the ends of their respective paths. That is, if it is possible to move the marbles such that both marbles rest on the last square of their respective paths.
['hashing', 'strings']
from time import time opposite = { 'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E' } otr = str.maketrans(opposite) bits = { 'N': 0, 'S': 1, 'E': 2, 'W': 3, } Q = 4294967291 def combine(h, v, q): return (h<<2 | v) % q def combinel(h, v, q, s): return (v*s + h) % q def flip(s): return ''.join(reversed(s.translate(otr))) def solvable(p1, p2): h1 = 0 h2 = 0 s = 1 for i in reversed(range(len(p1))): n1 = bits[p1[i]] n2 = bits[opposite[p2[i]]] h1 = combine(h1, n1, Q) h2 = combinel(h2, n2, Q, s) if h1 == h2 and p1[i:] == flip(p2[i:]): return False s = (s<<2) % Q return True if __name__ == '__main__': n = int(input()) p1 = input() p2 = input() print('YES' if solvable(p1, p2) else 'NO')
Python
[ "strings" ]
2,047
831
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
415
001ac8bce4e44e9266a13eb27760906c
You are given a string s consisting of the characters '0', '1', and '?'. You need to replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'. Note that each of the characters '?' is replaced independently from the others.A string t of length n is called a palindrome if the equality t[i] = t[n-i+1] is true for all i (1 \le i \le n).For example, if s="01?????0", a=4 and b=4, then you can replace the characters '?' in the following ways: "01011010"; "01100110". For the given string s and the numbers a and b, replace all the characters with '?' in the string s by '0' or '1' so that the string becomes a palindrome and has exactly a characters '0' and exactly b characters '1'.
['constructive algorithms', 'implementation', 'strings']
for _ in range(int(input())): a,b=[int(x) for x in input().split()] s=[x for x in input()] needa=a-s.count('0') needb=b-s.count('1') n=(a+b) done=True direct=False a=a-s.count('0') b=b-s.count('1') for i in range(n): if s[i]!='?': if s[n-1-i]=='?': s[n-1-i]=s[i] if s[i]=='0': a-=1 if s[i]=='1': b-=1 elif s[i]!=s[n-1-i]: direct=True print(-1) break if direct: continue if n%2!=0: if s[n//2]=='?': if a%2!=0: s[n//2]='0' a-=1 elif b%2!=0: s[n//2]='1' b-=1 else: print(-1) continue for i in range(n): if s[i]=='?': if a>1: s[i]='0' s[n-1-i]='0' a-=2 elif b>1: s[i]='1' s[n-1-i]='1' b-=2 if s != s[::-1]: print(-1) continue if a!=0 or b!=0: print(-1) continue else: for i in s: print(i,end="") print()
Python
[ "strings" ]
902
1,372
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
2,628
465f1c612fa43313005d90cc8e9e6a24
You have a connected undirected graph made of n nodes and m edges. The i-th node has a value v_i and a target value t_i.In an operation, you can choose an edge (i, j) and add k to both v_i and v_j, where k can be any integer. In particular, k can be negative.Your task to determine if it is possible that by doing some finite number of operations (possibly zero), you can achieve for every node i, v_i = t_i.
['constructive algorithms', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'math']
import bisect import copy import decimal import fractions import heapq import itertools import math import random import sys from collections import Counter, deque,defaultdict from functools import lru_cache,reduce from heapq import heappush,heappop,heapify,heappushpop,_heappop_max,_heapify_max def _heappush_max(heap,item): heap.append(item) heapq._siftdown_max(heap, 0, len(heap)-1) def _heappushpop_max(heap, item): if heap and item < heap[0]: item, heap[0] = heap[0], item heapq._siftup_max(heap, 0) return item from math import gcd as GCD read=sys.stdin.read readline=sys.stdin.readline readlines=sys.stdin.readlines class Graph: def __init__(self,V,edges=False,graph=False,directed=False,weighted=False): self.V=V self.directed=directed self.weighted=weighted if not graph: self.edges=edges self.graph=[[] for i in range(self.V)] if weighted: for i,j,d in self.edges: self.graph[i].append((j,d)) if not self.directed: self.graph[j].append((i,d)) else: for i,j in self.edges: self.graph[i].append(j) if not self.directed: self.graph[j].append(i) else: self.graph=graph self.edges=[] for i in range(self.V): if self.weighted: for j,d in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j,d)) else: for j in self.graph[i]: if self.directed or not self.directed and i<=j: self.edges.append((i,j)) def SS_BFS(self,s,bipartite_graph=False,linked_components=False,parents=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V seen[s]=True if linked_components: lc=[s] if parents: ps=[None]*self.V ps[s]=s if unweighted_dist or bipartite_graph: uwd=[float('inf')]*self.V uwd[s]=0 if weighted_dist: wd=[float('inf')]*self.V wd[s]=0 queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if linked_components: lc.append(y) if parents: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if type(uwd[i])==float or type(uwd[j])==float: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if type(uwd[x])==float: continue bg[uwd[x]%2].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if unweighted_dist: tpl+=(uwd,) if weighted_dist: tpl+=(wd,) if len(tpl)==1: tpl=tpl[0] return tpl def AP_BFS(self,bipartite_graph=False,linked_components=False,parents=False): seen=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if linked_components: lc=[] if parents: ps=[None]*self.V for s in range(self.V): if seen[s]: continue seen[s]=True if bipartite_graph: cnt+=1 bg[s]=(cnt,s&2) if linked_components: lc.append([s]) if parents: ps[s]=s queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if linked_components: lc[-1].append(y) if parents: ps[y]=x if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if len(tpl)==1: tpl=tpl[0] return tpl def SS_DFS(self,s,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False,unweighted_dist=False,weighted_dist=False): seen=[False]*self.V finished=[False]*self.V if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if parents or cycle_detection: ps=[None]*self.V ps[s]=s if postorder or topological_sort: post=[] if preorder: pre=[] if unweighted_dist or bipartite_graph: uwd=[float('inf')]*self.V uwd[s]=0 if weighted_dist: wd=[float('inf')]*self.V wd[s]=0 stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc.append(x) if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if parents or cycle_detection: ps[y]=x if unweighted_dist or bipartite_graph: uwd[y]=uwd[x]+1 if weighted_dist: wd[y]=wd[x]+d elif not finished[y]: if (directed_acyclic or cycle_detection or topological_sort) and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if postorder or topological_sort: post.append(x) if bipartite_graph: bg=[[],[]] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if type(uwd[i])==float or type(uwd[j])==float: continue if not uwd[i]%2^uwd[j]%2: bg=False break else: for x in range(self.V): if type(uwd[x])==float: continue bg[uwd[x]%2].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) tpl+=(cd,) if directed_acyclic: tpl+=(dag,) if euler_tour: tpl+=(et,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if postorder: tpl+=(post,) if preorder: tpl+=(pre,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] tpl+=(tp_sort,) if unweighted_dist: tpl+=(uwd,) if weighted_dist: tpl+=(wd,) if len(tpl)==1: tpl=tpl[0] return tpl def AP_DFS(self,bipartite_graph=False,cycle_detection=False,directed_acyclic=False,euler_tour=False,linked_components=False,parents=False,postorder=False,preorder=False,topological_sort=False): seen=[False]*self.V finished=[False]*self.V if bipartite_graph: bg=[None]*self.V cnt=-1 if directed_acyclic or cycle_detection or topological_sort: dag=True if euler_tour: et=[] if linked_components: lc=[] if parents or cycle_detection: ps=[None]*self.V if postorder or topological_sort: post=[] if preorder: pre=[] for s in range(self.V): if seen[s]: continue if bipartite_graph: cnt+=1 bg[s]=(cnt,s&2) if linked_components: lc.append([]) if parents: ps[s]=s stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) if euler_tour: et.append(x) if linked_components: lc[-1].append(x) if preorder: pre.append(x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) if bipartite_graph: bg[y]=(cnt,bg[x][1]^1) if parents or cycle_detection: ps[y]=x elif not finished[y]: if directed_acyclic and dag: dag=False if cycle_detection: cd=(y,x) elif not finished[x]: finished[x]=True if euler_tour: et.append(~x) if postorder or topological_sort: post.append(x) if bipartite_graph: bg_=bg bg=[[[],[]] for i in range(cnt+1)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl if not bg_[i][1]^bg_[j][1]: bg[bg_[i][0]]=False for x in range(self.V): if bg[bg_[x][0]]: bg[bg_[x][0]][bg_[x][1]].append(x) tpl=() if bipartite_graph: tpl+=(bg,) if cycle_detection: if dag: cd=[] else: y,x=cd cd=self.Route_Restoration(y,x,ps) tpl+=(cd,) if directed_acyclic: tpl+=(dag,) if euler_tour: tpl+=(et,) if linked_components: tpl+=(lc,) if parents: tpl+=(ps,) if postorder: tpl+=(post,) if preorder: tpl+=(pre,) if topological_sort: if dag: tp_sort=post[::-1] else: tp_sort=[] tpl+=(tp_sort,) if len(tpl)==1: tpl=tpl[0] return tpl def Tree_Diameter(self,weighted=False): def Farthest_Point(u): dist=self.SS_BFS(u,weighted_dist=True) if self.weighted else self.SS_BFS(u,unweighted_dist=True) fp=0 for i in range(self.V): if dist[fp]<dist[i]: fp=i return fp,dist[fp] u,d=Farthest_Point(0) v,d=Farthest_Point(u) return u,v,d def SCC(self): reverse_graph=[[] for i in range(self.V)] for tpl in self.edges: i,j=tpl[:2] if self.weighted else tpl reverse_graph[j].append(i) postorder=self.AP_DFS(postorder=True) scc=[] seen=[False]*self.V for s in postorder[::-1]: if seen[s]: continue queue=deque([s]) seen[s]=True lst=[] while queue: x=queue.popleft() lst.append(x) for y in reverse_graph[x]: if self.weighted: y=y[0] if not seen[y]: seen[y]=True queue.append(y) scc.append(lst) return scc def Build_LCA(self,s): self.euler_tour,self.parents,depth=self.SS_DFS(s,euler_tour=True,parents=True,unweighted_dist=True) self.dfs_in_index=[None]*self.V self.dfs_out_index=[None]*self.V for i,x in enumerate(self.euler_tour): if x>=0: self.dfs_in_index[x]=i else: self.dfs_out_index[~x]=i self.ST=Segment_Tree(2*self.V,lambda x,y:min(x,y),float('inf')) lst=[None]*2*self.V for i in range(2*self.V): if self.euler_tour[i]>=0: lst[i]=depth[self.euler_tour[i]] else: lst[i]=depth[self.parents[~self.euler_tour[i]]] self.ST.Build(lst) def LCA(self,a,b): m=min(self.dfs_in_index[a],self.dfs_in_index[b]) M=max(self.dfs_in_index[a],self.dfs_in_index[b]) x=self.euler_tour[self.ST.Fold_Index(m,M+1)] if x>=0: return x else: return self.parents[~x] def Dijkstra(self,s,route_restoration=False): dist=[float('inf')]*self.V dist[s]=0 hq=[(0,s)] if route_restoration: parents=[None]*self.V parents[s]=s while hq: dx,x=heapq.heappop(hq) if dist[x]<dx: continue for y,dy in self.graph[x]: if dist[y]>dx+dy: dist[y]=dx+dy if route_restoration: parents[y]=x heapq.heappush(hq,(dist[y],y)) if route_restoration: return dist,parents else: return dist def Bellman_Ford(self,s,route_restoration=False): dist=[float('inf')]*self.V dist[s]=0 if route_restoration: parents=[s]*self.V for _ in range(self.V-1): for i,j,d in self.edges: if dist[j]>dist[i]+d: dist[j]=dist[i]+d if route_restoration: parents[j]=i if not self.directed and dist[i]>dist[j]+d: dist[i]=dist[j]+d if route_restoration: parents[i]=j negative_cycle=[] for i,j,d in self.edges: if dist[j]>dist[i]+d: negative_cycle.append(j) if not self.directed and dist[i]>dist[j]+d: negative_cycle.append(i) if negative_cycle: is_negative_cycle=[False]*self.V for i in negative_cycle: if is_negative_cycle[i]: continue else: queue=deque([i]) is_negative_cycle[i]=True while queue: x=queue.popleft() for y,d in self.graph[x]: if not is_negative_cycle[y]: queue.append(y) is_negative_cycle[y]=True if route_restoration: parents[y]=x for i in range(self.V): if is_negative_cycle[i]: dist[i]=-float('inf') if route_restoration: return dist,parents else: return dist def Warshall_Floyd(self,route_restoration=False): dist=[[float('inf')]*self.V for i in range(self.V)] for i in range(self.V): dist[i][i]=0 if route_restoration: parents=[[j for j in range(self.V)] for i in range(self.V)] for i,j,d in self.edges: if dist[i][j]>d: dist[i][j]=d if route_restoration: parents[i][j]=i if not self.directed and dist[j][i]>d: dist[j][i]=d if route_restoration: parents[j][i]=j for k in range(self.V): for i in range(self.V): for j in range(self.V): if dist[i][j]>dist[i][k]+dist[k][j]: dist[i][j]=dist[i][k]+dist[k][j] if route_restoration: parents[i][j]=parents[k][j] for i in range(self.V): if dist[i][i]<0: for j in range(self.V): if dist[i][j]!=float('inf'): dist[i][j]=-float('inf') if route_restoration: return dist,parents else: return dist def Route_Restoration(self,s,g,parents): route=[g] while s!=g and parents[g]!=g: g=parents[g] route.append(g) route=route[::-1] return route def Kruskal(self): UF=UnionFind(self.V) sorted_edges=sorted(self.edges,key=lambda x:x[2]) minimum_spnning_tree=[] for i,j,d in sorted_edges: if not UF.Same(i,j): UF.Union(i,j) minimum_spnning_tree.append((i,j,d)) return minimum_spnning_tree def Ford_Fulkerson(self,s,t): max_flow=0 residual_graph=[defaultdict(int) for i in range(self.V)] if self.weighted: for i,j,d in self.edges: if not d: continue residual_graph[i][j]+=d if not self.directed: residual_graph[j][i]+=d else: for i,j in self.edges: residual_graph[i][j]+=1 if not self.directed: residual_graph[j][i]+=1 while True: parents=[None]*self.V parents[s]=s seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in residual_graph[x].keys(): if not seen[y]: seen[y]=True queue.append(y) parents[y]=x if y==t: tt=t while tt!=s: residual_graph[parents[tt]][tt]-=1 residual_graph[tt][parents[tt]]+=1 if not residual_graph[parents[tt]][tt]: residual_graph[parents[tt]].pop(tt) tt=parents[tt] max_flow+=1 break else: continue break else: break return max_flow def BFS(self,s): seen=[False]*self.V seen[s]=True queue=deque([s]) while queue: x=queue.popleft() for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: seen[y]=True queue.append(y) return def DFS(self,s): seen=[False]*self.V finished=[False]*self.V stack=[(s,0)] if self.weighted else [s] while stack: if self.weighted: x,d=stack.pop() else: x=stack.pop() if not seen[x]: seen[x]=True stack.append((x,d) if self.weighted else x) for y in self.graph[x]: if self.weighted: y,d=y if not seen[y]: stack.append((y,d) if self.weighted else y) elif not finished[x]: finished[x]=True return t=int(readline()) for _ in range(t): N,M=map(int,readline().split()) edges=[] v=list(map(int,readline().split())) t=list(map(int,readline().split())) for _ in range(M): a,b=map(int,readline().split()) a-=1;b-=1 edges.append((a,b)) if sum(v)%2!=sum(t)%2: ans='NO' else: G=Graph(N,edges=edges) bg=G.AP_DFS(bipartite_graph=True)[0] if not bg: ans='YES' else: v=sum(v[a] for a in bg[0])-sum(v[b] for b in bg[1]) t=sum(t[a] for a in bg[0])-sum(t[b] for b in bg[1]) if v==t: ans='YES' else: ans='NO' print(ans)
Python
[ "graphs", "math" ]
486
23,146
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
434
f596e0bcefde8227e8a7b9d923da828a
You are given two sets of positive integers A and B. You have to find two non-empty subsets S_A \subseteq A, S_B \subseteq B so that the least common multiple (LCM) of the elements of S_A is equal to the least common multiple (LCM) of the elements of S_B.
['data structures', 'math', 'number theory']
import math for _ in range(int(input())): n, m = [*map(int, input().split())] N, M = 1<<(len(bin(n-1))-2), 1<<(len(bin(m-1))-2) a = [*map(int, input().split())] b = [*map(int, input().split())] d = [[math.gcd(i,j) for i in b] for j in a] d1, d2 = [[0]*(M<<1) for i in range(n)], [[0]*(N<<1) for i in range(m)] def upd(d, i): while i>1: d[i>>1]=math.gcd(d[i], d[i^1]); i>>=1 s1, s2 = set(range(n)), set(range(m)) def updr(s1, s2, d1, d2, t, i, now): s1.discard(i) for idx in list(s2): if idx > now: break x=d2[idx] if x[1] == 1: x[i+t]=0 upd(x,i+t) if x[1] != 1: updr(s2, s1, d2, d1, M+N-t, idx, now) for i in range(max(m,n)): if i < n: for j in s2: d1[i][j+M] = a[i] // d[i][j] for j in range(M-1, 0, -1): d1[i][j] = math.gcd(d1[i][j<<1], d1[i][j<<1|1]) if d1[i][1] != 1: updr(s1, s2, d1, d2, N, i, i) if i < m: for j in s1: d2[i][j+N] = b[i] // d[j][i] for j in range(N-1, 0, -1): d2[i][j] = math.gcd(d2[i][j<<1], d2[i][j<<1|1]) if d2[i][1] != 1: updr(s2, s1, d2, d1, M, i, i) # print(i, len(s1), len(s2)) if len(s1): print('YES'); print(len(s1), len(s2)); print(*[a[i] for i in s1]); print(*[b[i] for i in s2]) else: print('NO')
Python
[ "math", "number theory" ]
291
1,414
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,960
6c71c828553e43c699237211005873e5
Given a string s of length n and integer k (1 \le k \le n). The string s has a level x, if x is largest non-negative integer, such that it's possible to find in s: x non-intersecting (non-overlapping) substrings of length k, all characters of these x substrings are the same (i.e. each substring contains only one distinct character and this character is the same for all the substrings). A substring is a sequence of consecutive (adjacent) characters, it is defined by two integers i and j (1 \le i \le j \le n), denoted as s[i \dots j] = "s_{i}s_{i+1} \dots s_{j}".For example, if k = 2, then: the string "aabb" has level 1 (you can select substring "aa"), the strings "zzzz" and "zzbzz" has level 2 (you can select two non-intersecting substrings "zz" in each of them), the strings "abed" and "aca" have level 0 (you can't find at least one substring of the length k=2 containing the only distinct character). Zuhair gave you the integer k and the string s of length n. You need to find x, the level of the string s.
['implementation', 'brute force', 'strings']
n, k = map(int, input().split()) seq = input() sseq = {} cur = 1 for i in range(1, len(seq)): s = seq[i] if s == seq[i - 1]: cur += 1 else: try: # print(s, cur, k) sseq[seq[i - 1]] += cur // k except KeyError: sseq[seq[i - 1]] = cur // k cur = 1 try: sseq[seq[-1]] += cur // k except KeyError: sseq[seq[-1]] = cur // k # print(sseq) mx = 0 for key, val in sseq.items(): mx = max(val, mx) print(mx)
Python
[ "strings" ]
1,180
496
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,927
55099493c66b003d4261310bf2cc8f93
There are n stone quarries in Petrograd.Each quarry owns mi dumpers (1 ≀ i ≀ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.Two oligarchs play a well-known game Nim. Players take turns removing stones from dumpers. On each turn, a player can select any dumper and remove any non-zero amount of stones from it. The player who cannot take a stone loses.Your task is to find out which oligarch will win, provided that both of them play optimally. The oligarchs asked you not to reveal their names. So, let's call the one who takes the first stone Β«tolikΒ» and the other one Β«bolikΒ».
['games']
def f(x): if x%4==0: return x elif x%4==1: return 1 elif x%4==2: return x+1 return 0 n = int(input()) res = 0 for i in range(n): x,m = input().split() x,m = int(x),int(m) res ^= f(x-1)^f(x+m-1) if res == 0: print("bolik") else: print("tolik")
Python
[ "games" ]
755
304
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,305
71b4674e91e0bc5521c416cfc570a090
Email address in Berland is a string of the form A@B, where A and B are arbitrary strings consisting of small Latin letters. Bob is a system administrator in Β«BersoftΒ» company. He keeps a list of email addresses of the company's staff. This list is as a large string, where all addresses are written in arbitrary order, separated by commas. The same address can be written more than once.Suddenly, because of unknown reasons, all commas in Bob's list disappeared. Now Bob has a string, where all addresses are written one after another without any separators, and there is impossible to determine, where the boundaries between addresses are. Unfortunately, on the same day his chief asked him to bring the initial list of addresses. Now Bob wants to disjoin addresses in some valid way. Help him to do that.
['implementation', 'greedy', 'strings']
import sys, re s = raw_input().strip() match = re.match('^(\w+@\w+)+$', s) if not match: print('No solution') sys.exit() previous = 0 last_at = None result = [] for pos, ch in enumerate(s): if ch == '@': result.append(s[previous:pos + 2]) previous = pos + 2 last_at = pos result[-1] += s[last_at + 2:] print(','.join(result))
Python
[ "strings" ]
807
365
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,140
ad5ec7026cbefedca288df14c2bc58e5
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 containing two (or more) balls of different colors (each set contains only balls of one color), there are no two sets such that the difference between their sizes is greater than 1. Print the minimum possible number of sets.
['number theory', 'greedy', 'math']
# Returns the number of coins that is necessary for paying the amount # with the two types of coins that have value of coin and coin + 1 def pay(coin, amount): if amount // coin < amount % coin: return -1; if amount < coin * (coin + 1): return amount // coin return (amount - 1) // (coin + 1) + 1; def pay_all(coin): sum = 0 for i in range(n): p = pay(coin, a[i]) if p == -1: return -1 sum += p return sum n = int(input()) a = list(map(int, input().split())) amin = min(a) coin = amin k = 1 p = -1 while p == -1: p = pay_all(coin) if p == -1 and amin % coin == 0: p = pay_all(coin - 1) k += 1 coin = amin // k print(p)
Python
[ "math", "number theory" ]
530
720
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,657
bb3fc45f903588baf131016bea175a9f
Iahub has drawn a set of n points in the cartesian plane which he calls "special points". A quadrilateral is a simple polygon without self-intersections with four sides (also called edges) and four vertices (also called corners). Please note that a quadrilateral doesn't have to be convex. A special quadrilateral is one which has all four vertices in the set of special points. Given the set of special points, please calculate the maximal area of a special quadrilateral.
['geometry', 'brute force']
# calculate convex of polygon v. # v is list of complexes stand for points. def convex(v, eps=1e-8): # fetch the seed point v.sort(key=lambda x:(x.real,x.imag)) v = v[0:1] + sorted(v[1:], key=lambda x:(x-v[0]).imag/abs(x-v[0])) n = 1 for i in range(2, len(v)): while n > 1 and ((v[n]-v[n-1])*(v[i]-v[n]).conjugate()).imag>-eps: n -= 1 else: n += 1 v[n] = v[i] v[n+1:] = [] return v # calculate the area of a polygon v, anti-clockwise. # v is list of complexes stand for points. def area(v): ans = 0 for i in range(2, len(v)): ans += ((v[i]-v[i-1])*(v[i-1]-v[0]).conjugate()).imag return ans * 0.5 n = int(input()) v = [complex(*tuple(map(int, input().split()))) for i in range(0, n)] w = convex(v) n = len(w) ans = 0 def tri(i, j, k): return abs(((w[i]-w[j])*(w[i]-w[k]).conjugate()).imag) * 0.5 for i in range(0, n): for j in range(i+2, n): if i == 0 and j == n-1: continue l = i + 1 r = j while l < r-1: k = l+r>>1 if tri(i, j, k) > tri(i, j, k-1): l = k else: r = k s1 = tri(i, j, l) l = j - n + 1 r = i while l < r-1: k = l+r>>1 if tri(i, j, k) > tri(i, j, k-1): l = k else: r = k s2 = tri(i, j, l) ans = max(ans, s1 + s2) if n == 3: for p in v: if not p in w: w.append(p) ans = max(ans, area(w)) w.pop() print(ans)
Python
[ "geometry" ]
474
1,651
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
0
ad2c4d07da081505fa251ba8c27028b1
Toastman came up with a very complicated task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?Given a n Γ— n checkerboard. Each cell of the board has either character 'x', or character 'o', or nothing. How many ways to fill all the empty cells with 'x' or 'o' (each cell must contain only one character in the end) are there, such that for each cell the number of adjacent cells with 'o' will be even? Find the number of ways modulo 1000000007 (109 + 7). Two cells of the board are adjacent if they share a side.
['dsu', 'math']
from sys import stdin def main(): n, k = map(int, stdin.readline().split()) par = [range(n+10), range(n+10)] def find(i, x): if par[i][x] == x: return x else: par[i][x] = find(i, par[i][x]) return par[i][x] def unite(i, x, y): x, y = find(i, x), find(i, y) par[i][x] = y mod = 1000000007 m = (n + 1) / 2 for _ in xrange(k): l = stdin.readline().split() r, c, b = int(l[0]) - 1, int(l[1]) - 1, int(l[2] == 'o') p = (r + c) % 2 if r > m: r, c = n - 1 - r, n - 1 - c L, R = c - r, c + r if L < 0: L = -L if R >= n: R = 2 * (n - 1) - R unite(p, L+b, R+2) unite(p, L+1-b, R+3) c = 0 for p in [0, 1]: for i in xrange([m, n-m][p]+1): L, R = p+i+i, p+i+i+1 l, r = find(p, L), find(p, R) if l == r: print 0 return if l == L: c += 1 print pow(2, c - 2, mod) main()
Python
[ "graphs", "math" ]
549
1,074
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,409
b85c8bfbe67a23a81bef755f9313115a
It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh. In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he removes the first and the second integer of the remaining sequence from the board, and so on. Bimokh stops when the board contains less than two numbers. When Bimokh removes numbers x and y from the board, he gets gcd(x, y) points. At the beginning of the game Bimokh has zero points.Mashmokh wants to win in the game. For this reason he wants his boss to get exactly k points in total. But the guy doesn't know how choose the initial sequence in the right way. Please, help him. Find n distinct integers a1, a2, ..., an such that his boss will score exactly k points. Also Mashmokh can't memorize too huge numbers. Therefore each of these integers must be at most 109.
['constructive algorithms', 'number theory']
n,k=map(int, input().split(' ')) if k<n//2 : print(-1) elif n==1: if k == 0: print(1) else: print(-1) else: x=(k-n//2)+1 ans=[x,2*x] for i in range(n-2): ans.append(200000001 + i) print(*ans)
Python
[ "number theory" ]
984
248
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,359
2d1ad0dc72496b767b9f3d901b6aa36a
Welcome! Everything is fine.You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity.You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident.Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree.The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses.As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B?
['greedy', 'dfs and similar', 'trees', 'graphs']
from collections import Counter,defaultdict from sys import stdin, stdout raw_input = stdin.readline pr = stdout.write for t in xrange(input()): n=input() d=defaultdict(list) n*=2 for i in xrange(n-1): u,v,w=map(int, raw_input().split()) d[u].append((v,w)) d[v].append((u,w)) par=[0]*(n+1) cst=[0]*(n+1) q=[1] pos=0 par[1]=1 while len(q)>pos: x=q[pos] pos+=1 for i,dis in d[x]: if par[i]: continue par[i]=x cst[i]=dis q.append(i) dp=[1]*(n+1) mx,mn=0,0 for i in q[::-1]: dp[par[i]]+=dp[i] mx+=cst[i]*min(dp[i],n-dp[i]) mn+=cst[i]*(dp[i]%2) pr(str(mn)+' '+str(mx)+'\n')
Python
[ "graphs", "trees" ]
1,988
767
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,564
7421b2392cb40f1cf0b7fd93c287f1eb
There are n bricks numbered from 1 to n. Brick i has a weight of a_i.Pak Chanek has 3 bags numbered from 1 to 3 that are initially empty. For each brick, Pak Chanek must put it into one of the bags. After this, each bag must contain at least one brick.After Pak Chanek distributes the bricks, Bu Dengklek will take exactly one brick from each bag. Let w_j be the weight of the brick Bu Dengklek takes from bag j. The score is calculated as |w_1 - w_2| + |w_2 - w_3|, where |x| denotes the absolute value of x.It is known that Bu Dengklek will take the bricks in such a way that minimises the score. What is the maximum possible final score if Pak Chanek distributes the bricks optimally?
['constructive algorithms', 'games', 'greedy', 'sortings']
from sys import stdin, stdout t = int(stdin.readline()) for _ in range(t): n = int(stdin.readline()) a = [int(x) for x in stdin.readline().split()] a.sort() ans = 0 for i in range(n-2): ans = max(ans, a[n-1] - a[i] + a[i+1] - a[i]) for j in range(2, n): ans = max(ans, a[j] - a[0] + a[j] - a[j-1]) print(ans)
Python
[ "games" ]
765
369
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,277
d6e44bd8ac03876cb03be0731f7dda3d
Every superhero has been given a power value by the Felicity Committee. The avengers crew wants to maximize the average power of the superheroes in their team by performing certain operations.Initially, there are n superheroes in avengers team having powers a_1, a_2, \ldots, a_n, respectively. In one operation, they can remove one superhero from their team (if there are at least two) or they can increase the power of a superhero by 1. They can do at most m operations. Also, on a particular superhero at most k operations can be done.Can you help the avengers team to maximize the average power of their crew?
['implementation', 'brute force', 'math']
n,k,m = input().split() k = int(k) m = int(m) n = int(n) niz = [int(n) for n in input().split()] niz.sort() suma = sum(niz) curMax = (suma+min(m,n*k)) / n for i in range(1,min(n-1,m)+1): suma -= niz[i-1] tempMax = (suma + min(m-i, (n-i)*k)) /(n-i) if tempMax > curMax: curMax = tempMax print(curMax)
Python
[ "math" ]
643
320
0
0
0
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,526
1503f0379bf8d7f25c191ddea9278842
In the town of Aalam-Aara (meaning the Light of the Earth), previously there was no crime, no criminals but as the time progressed, sins started creeping into the hearts of once righteous people. Seeking solution to the problem, some of the elders found that as long as the corrupted part of population was kept away from the uncorrupted part, the crimes could be stopped. So, they are trying to set up a compound where they can keep the corrupted people. To ensure that the criminals don't escape the compound, a watchtower needs to be set up, so that they can be watched.Since the people of Aalam-Aara aren't very rich, they met up with a merchant from some rich town who agreed to sell them a land-plot which has already a straight line fence AB along which a few points are set up where they can put up a watchtower. Your task is to help them find out the number of points on that fence where the tower can be put up, so that all the criminals can be watched from there. Only one watchtower can be set up. A criminal is watchable from the watchtower if the line of visibility from the watchtower to him doesn't cross the plot-edges at any point between him and the tower i.e. as shown in figure 1 below, points X, Y, C and A are visible from point B but the points E and D are not. Figure 1 Figure 2 Assume that the land plot is in the shape of a polygon and coordinate axes have been setup such that the fence AB is parallel to x-axis and the points where the watchtower can be set up are the integer points on the line. For example, in given figure 2, watchtower can be setup on any of five integer points on AB i.e. (4, 8), (5, 8), (6, 8), (7, 8) or (8, 8). You can assume that no three consecutive points are collinear and all the corner points other than A and B, lie towards same side of fence AB. The given polygon doesn't contain self-intersections.
['geometry']
from math import floor,ceil n = input() x,y = zip(*[map(int,raw_input().split()) for _ in xrange(n)]) nr,mr=min(x[:2]),max(x[:2]) for j in xrange(3,n): i = j-1 dx = x[j]-x[i] dy = y[j]-y[i] t = 1.*(y[0]-y[i])*dx; r = t/dy+x[i] if dy else 1e9 if t-dy*(mr-x[i])>0 and r<mr: mr=r; if t-dy*(nr-x[i])>0 and r>nr: nr=r; mr = floor(mr)-ceil(nr) print "%.0f"%(0. if mr<-1e-14 else mr+1.1)
Python
[ "geometry" ]
1,868
410
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,795
905e3f3e6f7d8f13789b89e77a3ef65e
This is an interactive problem!In the last regional contest Hemose, ZeyadKhattab and YahiaSherif β€” members of the team Carpe Diem β€” did not qualify to ICPC because of some unknown reasons. Hemose was very sad and had a bad day after the contest, but ZeyadKhattab is very wise and knows Hemose very well, and does not want to see him sad.Zeyad knows that Hemose loves tree problems, so he gave him a tree problem with a very special device.Hemose has a weighted tree with n nodes and n-1 edges. Unfortunately, Hemose doesn't remember the weights of edges.Let's define Dist(u, v) for u\neq v as the greatest common divisor of the weights of all edges on the path from node u to node v.Hemose has a special device. Hemose can give the device a set of nodes, and the device will return the largest Dist between any two nodes from the set. More formally, if Hemose gives the device a set S of nodes, the device will return the largest value of Dist(u, v) over all pairs (u, v) with u, v \in S and u \neq v.Hemose can use this Device at most 12 times, and wants to find any two distinct nodes a, b, such that Dist(a, b) is maximum possible. Can you help him?
['binary search', 'dfs and similar', 'implementation', 'interactive', 'math', 'number theory', 'trees']
# import os,sys # from io import BytesIO, IOBase # from collections import defaultdict,deque,Counter # from bisect import bisect_left,bisect_right # from heapq import heappush,heappop # from functools import lru_cache # from itertools import accumulate # import math # # Fast IO Region # BUFSIZE = 8192 # class FastIO(IOBase): # newlines = 0 # def __init__(self, file): # self._fd = file.fileno() # self.buffer = BytesIO() # self.writable = "x" in file.mode or "r" not in file.mode # self.write = self.buffer.write if self.writable else None # def read(self): # while True: # b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) # if not b: # break # ptr = self.buffer.tell() # self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) # self.newlines = 0 # return self.buffer.read() # def readline(self): # while self.newlines == 0: # b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) # self.newlines = b.count(b"\n") + (not b) # ptr = self.buffer.tell() # self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) # self.newlines -= 1 # return self.buffer.readline() # def flush(self): # if self.writable: # os.write(self._fd, self.buffer.getvalue()) # self.buffer.truncate(0), self.buffer.seek(0) # class IOWrapper(IOBase): # def __init__(self, file): # self.buffer = FastIO(file) # self.flush = self.buffer.flush # self.writable = self.buffer.writable # self.write = lambda s: self.buffer.write(s.encode("ascii")) # self.read = lambda: self.buffer.read().decode("ascii") # self.readline = lambda: self.buffer.readline().decode("ascii") # sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # input = lambda: sys.stdin.readline().rstrip("\r\n") # for _ in range(int(input())): # n = int(input()) # a = list(map(int, input().split(' '))) # for _ in range(int(input())): # n, h = list(map(int, input().split(' '))) # a = list(map(int, input().split(' '))) # a.sort() # x, y = a[-2], a[-1] # if x == y: # print(math.ceil(h / x)) # else: # ans = h // (x + y) * 2 # h %= x + y # if h > 0: # ans += 1 # if h > y: # ans += 1 # print(ans) # for _ in range(int(input())): # n, x = list(map(int, input().split(' '))) # a = list(map(int, input().split(' '))) # b = sorted(a) # for i in range(n - x, x): # if a[i] != b[i]: # print('NO') # break # else: # print('YES') import sys from collections import deque n = int(input()) adj = [[] for _ in range(n + 1)] for _ in range(n - 1): u, v = list(map(int, input().split(' '))) adj[u].append(v) adj[v].append(u) q = deque([1]) order = [] parent = [-1] * (n + 1) vis = set() vis.add(1) while q: u = q.popleft() order.append(u) for v in adj[u]: if v not in vis: parent[v] = u q.append(v) vis.add(v) print("?", len(order), *order) sys.stdout.flush() mx = int(input()) l, r = 0, n - 1 while l < r - 1: mid = (l + r) // 2 print("?", len(order[:mid + 1]), *order[:mid + 1]) sys.stdout.flush() x = int(input()) if x == mx: r = mid else: l = mid print("!", order[r], parent[order[r]]) sys.stdout.flush()
Python
[ "graphs", "math", "number theory", "trees" ]
1,266
3,720
0
0
1
1
1
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 1 }
2,431
802e4d90444b371a1dbab10d3d589e55
This is the easy version of Problem F. The only difference between the easy version and the hard version is the constraints.We will call a non-empty string balanced if it contains the same number of plus and minus signs. For example: strings "+--+" and "++-+--" are balanced, and strings "+--", "--" and "" are not balanced.We will call a string promising if the string can be made balanced by several (possibly zero) uses of the following operation: replace two adjacent minus signs with one plus sign. In particular, every balanced string is promising. However, the converse is not true: not every promising string is balanced.For example, the string "-+---" is promising, because you can replace two adjacent minuses with plus and get a balanced string "-++-", or get another balanced string "-+-+".How many non-empty substrings of the given string s are promising? Each non-empty promising substring must be counted in the answer as many times as it occurs in string s.Recall that a substring is a sequence of consecutive characters of the string. For example, for string "+-+" its substring are: "+-", "-+", "+", "+-+" (the string is a substring of itself) and some others. But the following strings are not its substring: "--", "++", "-++".
['brute force', 'implementation', 'math', 'strings']
t = int(input()) for case in range(t): n = int(input()) s = input() counter = 0 for i in range(n): pos = 0 neg = 0 for j in range(i, n): if s[j] == '+': pos += 1 else: neg += 1 if i == j: continue if (pos <= neg and not (neg - pos)%3): counter += 1 print(counter)
Python
[ "math", "strings" ]
1,259
444
0
0
0
1
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,221
5e34b8ed812d392799f45c3c3fa1c979
This is an interactive problem.You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles.We chose a hidden node x. In order to find this node, you can ask queries of two types: d u (1 \le u \le n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them. s u (1 \le u \le n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict! Node a is called an ancestor of node b if a \ne b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself.Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
['graphs', 'constructive algorithms', 'implementation', 'divide and conquer', 'interactive', 'trees']
def sec(tup): return -tup[1] def do(graph,top,level): if level==0: print("!",top) return None curr=top for i in range(level): curr=graph[curr] print("d",curr) dist=int(input()) if dist==0: print("!",curr) return None newt=top for i in range(level-dist//2): newt=graph[newt] print("s",newt) v=int(input()) newt=v newl=dist//2-1 do(graph,newt,newl) return None def main(): n=int(input()) graph=[[] for i in range(n+1)] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) print("d",1) d=int(input()) layers=[[1]] layer=[1] lays=[None]*(n+1) lays[1]=0 for i in range(d): newlayer=[] for guy in layer: for neigh in graph[guy]: graph[neigh].remove(guy) newlayer.append(neigh) lays[neigh]=i+1 layers.append(newlayer) layer=newlayer des=[0]*(n+1) for guy in layers[-1]: des[guy]=1 for i in range(d): for guy in layers[-i-2]: des[guy]=sum(des[boi] for boi in graph[guy]) for guy in range(1,n+1): for i in range(len(graph[guy])): graph[guy][i]=(graph[guy][i],des[graph[guy][i]]) graph[guy].sort(key=sec) best=[0]*(n+1) for i in range(1,n+1): if len(graph[i])>0: best[i]=graph[i][0][0] do(best,1,d) main()
Python
[ "graphs", "trees" ]
1,007
1,498
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,117
d7c2789c5fb216f1de4a99657ffafb4d
This version of the problem differs from the next one only in the constraint on n.A tree is a connected undirected graph without cycles. A weighted tree has a weight assigned to each edge. The distance between two vertices is the minimum sum of weights on the path connecting them.You are given a weighted tree with n vertices, each edge has a weight of 1. Denote d(v) as the distance between vertex 1 and vertex v.Let f(x) be the minimum possible value of \max\limits_{1 \leq v \leq n} \ {d(v)} if you can temporarily add an edge with weight x between any two vertices a and b (1 \le a, b \le n). Note that after this operation, the graph is no longer a tree.For each integer x from 1 to n, find f(x).
['binary search', 'data structures', 'dfs and similar', 'graphs', 'shortest paths', 'trees']
from sys import stdin inp = stdin.readline t = int(inp()) for _ in range(t): n = int(inp()) tree = {i: [set(), 0, 0] for i in range(1, n+1)} for i in range(n-1): a, b = map(int, inp().split()) tree[a][0].add(b) tree[b][0].add(a) layer = 0 arr = [set(tree[1][0])] branch = [1] dist = 0 dBranch = [] while True: if not arr[layer]: if layer > dist: dBranch = branch[:] dist = layer for c in tree[branch[layer]][0]: if c != branch[layer-1] or layer == 0: if tree[c][1] + 1 > tree[branch[layer]][1]: tree[branch[layer]][2] = tree[branch[layer]][1] tree[branch[layer]][1] = tree[c][1] + 1 elif tree[c][1] + 1 > tree[branch[layer]][2]: tree[branch[layer]][2] = tree[c][1] + 1 layer -= 1 if layer == -1: break arr.pop() branch.pop() else: current = arr[layer].pop() arr.append(set(tree[current][0])) branch.append(current) arr[layer+1].discard(branch[layer]) layer += 1 longest = [] for i in range(len(dBranch)): longest.append([i + (dist - tree[dBranch[i]][2] - i)//2, tree[dBranch[i]][2], i]) longest.sort() ans = [0]*n x = 0 last = 0 for c in longest: while x+1 < 2*c[2] - c[0]: ans[x] = max(dist - c[0] + x + 1, last) x += 1 last = max(c[1]+c[2], last) while x < n: ans[x] = dist x += 1 print(*ans)
Python
[ "graphs", "trees" ]
798
1,775
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,658
58fa5c2f270e2c34e8f9671d5ffdb9c8
Coming up with a new problem isn't as easy as many people think. Sometimes it is hard enough to name it. We'll consider a title original if it doesn't occur as a substring in any titles of recent Codeforces problems. You've got the titles of n last problems β€” the strings, consisting of lowercase English letters. Your task is to find the shortest original title for the new problem. If there are multiple such titles, choose the lexicographically minimum one. Note, that title of the problem can't be an empty string.A substring s[l... r] (1 ≀ l ≀ r ≀ |s|) of string s = s1s2... s|s| (where |s| is the length of string s) is string slsl + 1... sr.String x = x1x2... xp is lexicographically smaller than string y = y1y2... yq, if either p &lt; q and x1 = y1, x2 = y2, ... , xp = yp, or there exists such number r (r &lt; p, r &lt; q), that x1 = y1, x2 = y2, ... , xr = yr and xr + 1 &lt; yr + 1. The string characters are compared by their ASCII codes.
['brute force', 'strings']
cs1 = {chr(x) for x in range(ord('a'), ord('z') + 1)} cs2 = {x + y for x in cs1 for y in cs1} for i in range(int(input())): s = input() for i in range(len(s) - 1): cs1.discard(s[i:i + 1]) cs2.discard(s[i:i + 2]) cs1.discard(s[len(s) - 1:len(s)]) print(min(cs1) if cs1 else min(cs2))
Python
[ "strings" ]
952
310
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,288
5d0a985a0dced0734aff6bb0cd1b695d
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l ≀ ai ≀ r and ai β‰  aj , where a1, a2, ..., an is the geometrical progression, 1 ≀ i, j ≀ n and i β‰  j.Geometrical progression is a sequence of numbers a1, a2, ..., an where each term after first is found by multiplying the previous one by a fixed non-zero number d called the common ratio. Note that in our task d may be non-integer. For example in progression 4, 6, 9, common ratio is .Two progressions a1, a2, ..., an and b1, b2, ..., bn are considered different, if there is such i (1 ≀ i ≀ n) that ai β‰  bi.
['number theory', 'brute force', 'math']
rr=raw_input rrI = lambda: int(rr()) rrM = lambda: map(int,rr().split()) debug=0 if debug: fi = open('t.txt','r') rr=lambda: fi.readline().replace('\n','') from fractions import gcd def multi(lower, upper, factor): #How many x: lower <= x <= upper #have factor divide them? return int(upper / factor) - int((lower-1)/factor) def solve(N, L, R): if N > 24: return 0 if N == 1: return R-L+1 if N == 2: Z = R-L+1 return Z*(Z-1) zeta = int( R**(1/float(N-1)) ) while (zeta+1)**(N-1) <= R: zeta += 1 ans = 0 for p in xrange(1, zeta+1): for q in xrange(p+1, zeta+1): if gcd(p,q) == 1: numer = R * p**(N-1) denom = q**(N-1) upper = numer / denom #print 'ya', L, upper, denom count = multi(L, upper, p**(N-1)) count = max(count, 0) #print 'yo', count, p, q ans += count return ans * 2 print solve(*rrM())
Python
[ "math", "number theory" ]
729
1,044
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,591
e8f12eb9144ac2ea1c18fbfb15a84a0e
You're given Q queries of the form (L, R). For each query you have to find the number of such x that L ≀ x ≀ R and there exist integer numbers a &gt; 0, p &gt; 1 such that x = ap.
['binary search', 'number theory', 'math']
import math from sys import stdin, stdout q = int(stdin.readline()) D = set() #v.append(1) mv = int(1e18) for i in range(2,1000001): j = i*i*i while(j<=mv): y = int(math.sqrt(j)) if(y*y == j): j=j*i continue D.add(j) j = j*i v=[] for key in D: v.append(key) v.sort() final=[] while(q): q-=1 L = (stdin.readline()).split() l = int(L[0]) r = int(L[1]) root_r = int(math.sqrt(r)) root_l = int(math.sqrt(l-1)) if(root_r*root_r > r): root_r-=1 if(root_l*root_l > (l-1) ): root_l -= 1 #print(root_l,root_r) ans = root_r-root_l #print(ans) be = 0 en = len(v)-1 ind = -1 while(be<=en): mid = (be+en)/2 if(v[mid]<=r): ind=mid be=mid+1 else: en=mid-1 if(ind==-1): final.append(ans) continue in2 = -1 be = 0 en = len(v)-1 while(be<=en): mid = (be+en)/2 if(v[mid]>=l): in2 = mid en=mid-1 else: be=mid+1 if(in2==-1): final.append(ans) continue # print(ind,v[ind],in2,v[in2]) ans += (ind-in2+1) final.append(ans) for i in final: stdout.write(str(i)+'\n')
Python
[ "number theory", "math" ]
179
1,278
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
1,117
739e60a2fa71aff9a5c7e781db861d1e
We had a really tough time generating tests for problem D. In order to prepare strong tests, we had to solve the following problem.Given an undirected labeled tree consisting of n vertices, find a set of segments such that: both endpoints of each segment are integers from 1 to 2n, and each integer from 1 to 2n should appear as an endpoint of exactly one segment; all segments are non-degenerate; for each pair (i, j) such that i \ne j, i \in [1, n] and j \in [1, n], the vertices i and j are connected with an edge if and only if the segments i and j intersect, but neither segment i is fully contained in segment j, nor segment j is fully contained in segment i. Can you solve this problem too?
['constructive algorithms', 'divide and conquer', 'trees', 'dfs and similar']
import sys import os range = xrange input = raw_input S = sys.stdin.read() n = len(S) A = [] i = 0 while i < n: c = 0 while ord(S[i]) >= 48: c = 10 * c + ord(S[i]) - 48 i += 1 A.append(c) i += 1 + (S[i] == '\r') inp = A; ii = 0 n = inp[ii]; ii += 1 coupl = [[] for _ in range(n)] for _ in range(n - 1): u = inp[ii] - 1; ii += 1 v = inp[ii] - 1; ii += 1 coupl[u].append(v) coupl[v].append(u) bfs = [0] found = [0]*n children = coupl for node in bfs: found[node] = 1 for nei in coupl[node]: bfs.append(nei) coupl[nei].remove(node) family = [1]*n for node in reversed(bfs): for child in children[node]: family[node] += family[child] out = inp out.append(0) out[1] = 2 * n - 1 mark = [0]*n for node in bfs: l = mark[node] r = l + 2 * family[node] - 1 for child in children[node]: mark[child] = l l += 2 * family[child] - 1 r -= 1 out[2 * child + 1] = r out[2 * node] = r - 1 os.write(1, ' '.join(str(x + 1) for x in out))
Python
[ "graphs", "trees" ]
802
1,058
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,568
a0e738765161bbbfe8e7c5abaa066b0d
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia.The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N gold coins. The game ends if there are no more gold coins in the chest. In each turn, the players can make one of the following moves: Take one gold coin from the chest. Take half of the gold coins on the chest. This move is only available if the number of coins in the chest is even. Both players will try to maximize the number of coins they have. Mr. Chanek asks your help to find the maximum number of coins he can get at the end of the game if both he and the opponent plays optimally.
['greedy', 'games']
import os,io input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline def fnxn(n): n1 = n ans = 0 while n: if n in dp: ans += dp[n] n = 0 elif n%4 == 0: ans += 1 n -= 2 elif n%2 == 0: n//=2 ans += n n -= 1 else: ans += 1 n -= 1 dp[n1] = ans return ans cases = int(input()) dp = {1:1,2:1,3:2,4:3} for t in range(cases): n = int(input()) if n%2 == 0: print(fnxn(n)) else: print(n-fnxn(n-1))
Python
[ "games" ]
817
581
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,877
1321013edb706b2e3f3946979c4a5916
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.Last evening Roma started to play poker. He decided to spend no more than k virtual bourles β€” he will stop immediately if the number of his loses exceeds the number of his wins by k. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by k.Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won k bourles or he lost.The sequence written by Roma is a string s consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met: In the end the absolute difference between the number of wins and loses is equal to k; There is no hand such that the absolute difference before this hand was equal to k. Help Roma to restore any such sequence.
['dp', 'graphs']
n, k = [int(i) for i in input().split()] s = input() dp = [[False] * 2100 for i in range(1001)] dp[0][0] = True for i in range(n): l = -k + 1 r = k if i == n - 1: l -= 1 r += 1 for b in range(l, r): if s[i] == 'L': dp[i + 1][b] = dp[i][b + 1] elif s[i] == 'W': dp[i + 1][b] = dp[i][b - 1] elif s[i] == 'D': dp[i + 1][b] = dp[i][b] else: dp[i + 1][b] = dp[i][b + 1] or dp[i][b - 1] or dp[i][b] ans = [] i = n b = -1 if dp[i][k]: b = k elif dp[i][-k]: b = -k if b == -1: print("NO") else: while i > 0: if (s[i - 1] == 'L' or s[i - 1] == '?') and dp[i][b] == dp[i - 1][b + 1]: ans.append('L') b += 1 elif (s[i - 1] == 'W' or s[i - 1] == '?') and dp[i][b] == dp[i - 1][b - 1]: ans.append('W') b -= 1 else: ans.append('D') i -= 1 for j in reversed(ans): print(j, end='')
Python
[ "graphs" ]
1,356
1,031
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,467
3858151e51f6c97abe8904628b70ad7f
You are given n dominoes. Each domino has a left and a right cell. Each cell can be colored either black or white. Some cells are already colored, while some aren't yet.The coloring is said to be valid if and only if it is possible to rearrange the dominoes in some order such that for each 1 \le i \le n the color of the right cell of the i-th domino is different from the color of the left cell of the ((i \bmod n)+1)-st domino. Note that you can't rotate the dominoes, so the left cell always remains the left cell, and the right cell always remains the right cell.Count the number of valid ways to color the yet uncolored cells of dominoes. Two ways are considered different if there is a cell that is colored white in one way and black in the other. In particular, colorings BW WB and WB BW different (and both invalid).As this number can be very big, output it modulo 998\,244\,353.
['combinatorics', 'fft', 'graphs', 'math', 'number theory']
MOD = 998244353 facts = [1] for i in range(1, 100001): facts.append(facts[-1] * i % MOD) def qpow(x, y): ret = 1 b = x while y > 0: if y & 1: ret = ret * b % MOD b = b * b % MOD y >>= 1 return ret def inv(x): return qpow(x, MOD - 2) def CC(n, m): return facts[n] * inv(facts[m]) % MOD * inv(facts[n - m]) % MOD n = int(input()) rec = {} WL, WR, BL, BR = 0, 0, 0, 0 for i in range(n): d = input().strip() if d[0] == 'W': WL += 1 if d[0] == 'B': BL += 1 if d[1] == 'W': WR += 1 if d[1] == 'B': BR += 1 rec[d] = rec.get(d, 0) + 1 QL = n - BL - WL QR = n - BR - WR ans = 0 for i in range(BL, n - WL + 1): j = n - i if BR + QR < j or BR > j: continue else: cnt = CC(QL, i - BL) % MOD * CC(QR, j - BR) % MOD ans = (ans + cnt) % MOD if rec.get('BB', 0) == 0 and rec.get('WW', 0) == 0: ans += (MOD - qpow(2, rec.get('??', 0))) % MOD if BL == 0 and WR == 0 or WL == 0 and BR == 0: if BL > 0 or BR > 0 or WL > 0 or WR > 0: ans += 1 else: ans += 2 print(ans % MOD)
Python
[ "math", "number theory", "graphs" ]
918
1,207
0
0
1
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
441
e744184150bf55a30568060cca69de04
You had n positive integers a_1, a_2, \dots, a_n arranged in a circle. For each pair of neighboring numbers (a_1 and a_2, a_2 and a_3, ..., a_{n - 1} and a_n, and a_n and a_1), you wrote down: are the numbers in the pair equal or not.Unfortunately, you've lost a piece of paper with the array a. Moreover, you are afraid that even information about equality of neighboring elements may be inconsistent. So, you are wondering: is there any array a which is consistent with information you have about equality or non-equality of corresponding pairs?
['constructive algorithms', 'dsu', 'implementation']
from collections import Counter for _ in range(int(input())): S = input() S = list(S) a = Counter(S) if a['N']==1: print("NO") else: print("YES")
Python
[ "graphs" ]
619
195
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
732
dd3ba43eb0261ccdb7269a2696a042da
Lord Omkar would like to have a tree with n nodes (3 \le n \le 10^5) and has asked his disciples to construct the tree. However, Lord Omkar has created m (\mathbf{1 \le m &lt; n}) restrictions to ensure that the tree will be as heavenly as possible. A tree with n nodes is an connected undirected graph with n nodes and n-1 edges. Note that for any two nodes, there is exactly one simple path between them, where a simple path is a path between two nodes that does not contain any node more than once.Here is an example of a tree: A restriction consists of 3 pairwise distinct integers, a, b, and c (1 \le a,b,c \le n). It signifies that node b cannot lie on the simple path between node a and node c. Can you help Lord Omkar and become his most trusted disciple? You will need to find heavenly trees for multiple sets of restrictions. It can be shown that a heavenly tree will always exist for any set of restrictions under the given constraints.
['constructive algorithms', 'trees']
import os import sys import math from io import BytesIO, IOBase from collections import deque,defaultdict,OrderedDict,Counter from heapq import heappush,heappop,heapify from bisect import bisect_right,insort,bisect_left from functools import lru_cache from itertools import permutations sys.setrecursionlimit(10**6) def STRIN():return input() def INTIN():return int(input()) def LINT():return list(map(int,input().split())) def LSTR():return list(map(str,input().split())) def MINT():return map(int,input().split()) def MSTR():return map(str,input().split()) def divisors(n) : c=0 i=1 while i <= int(math.sqrt(n)): if (n % i == 0) : if (n // i == i): c+=1 else : c+=2 i = i + 1 return c def isValid(x,y,n,m,graph,vis): if x<0 or x>=n or y<0 or y>=m or graph[x][y]=='#' or vis[x][y]: return False return True def dfs(u,graph,vis,parent,p,vertex): vis[u]=1 parent[u]=p for v in graph[u]: if vis[v]: if p!=v: vertex[0]=v vertex[1]=u return True if not vis[v]: if dfs(v,graph,vis,parent,u,vertex): return True return False def bfs(u,graph,vis,teams): pass def palin(s): s=str(s) i=0 j=len(s)-1 while i<=j: if s[i]!=s[j]: return False i+=1 j-=1 return True def solve(): n,m=MINT() ans=[] st=set() nodes=[] for i in range(m): a,b,c=MINT() nodes.append((a,b,c)) st.add(b) for i in range(1,n+1): if i not in st: node=i break for i in range(1,n+1): if i!=node: ans.append([node,i]) for i in range(len(ans)): print(*ans[i],end="\n") def main(): for _ in range(INTIN()): solve() # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
Python
[ "trees" ]
1,039
3,832
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,958
dc225c801f55b8d7b40ebcc71b417edb
Tokitsukaze and CSL are playing a little game of stones.In the beginning, there are n piles of stones, the i-th pile of which has a_i stones. The two players take turns making moves. Tokitsukaze moves first. On each turn the player chooses a nonempty pile and removes exactly one stone from the pile. A player loses if all of the piles are empty before his turn, or if after removing the stone, two piles (possibly empty) contain the same number of stones. Supposing that both players play optimally, who will win the game?Consider an example: n=3 and sizes of piles are a_1=2, a_2=3, a_3=0. It is impossible to choose the empty pile, so Tokitsukaze has two choices: the first and the second piles. If she chooses the first pile then the state will be [1, 3, 0] and it is a good move. But if she chooses the second pile then the state will be [2, 2, 0] and she immediately loses. So the only good move for her is to choose the first pile. Supposing that both players always take their best moves and never make mistakes, who will win the game?Note that even if there are two piles with the same number of stones at the beginning, Tokitsukaze may still be able to make a valid first move. It is only necessary that there are no two piles with the same number of stones after she moves.
['greedy', 'games']
from collections import defaultdict FIRST = "sjfnb" SECOND = "cslnb" n = int(input()) arr = list(map(int, input().split())) m = len(set(arr)) if sum(arr) == 0 or arr.count(0) >= 2: print(SECOND) exit() elif m <= n - 2: print(SECOND) exit() elif m == n - 1: d = defaultdict(int) for i in arr: d[i] += 1 for i, j in d.items(): if j == 2: if i-1 in d: print(SECOND) exit() s = 0 for i, j in enumerate(sorted(arr)): s += j - i if s % 2 == 1: print(FIRST) exit() else: print(SECOND) exit()
Python
[ "games" ]
1,338
556
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,383
930365b084022708eb871f3ca2f269e4
You're given a list of n strings a1, a2, ..., an. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.Given the list of strings, output the lexicographically smallest concatenation.
['sortings', 'strings']
from functools import cmp_to_key print(''.join(sorted([input() for _ in range(int(input()))],key=cmp_to_key(lambda x,y:1 if x+y>y+x else-1))))
Python
[ "strings" ]
250
142
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,152
8237ac3f3c2e79f5f70be1595630207e
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: An 'L' indicates he should move one unit left. An 'R' indicates he should move one unit right. A 'U' indicates he should move one unit up. A 'D' indicates he should move one unit down.But now Memory wants to end at the origin. To do this, he has a special trident. This trident can replace any character in s with any of 'L', 'R', 'U', or 'D'. However, because he doesn't want to wear out the trident, he wants to make the minimum number of edits possible. Please tell Memory what is the minimum number of changes he needs to make to produce a string that, when walked, will end at the origin, or if there is no such string.
['implementation', 'strings']
y=raw_input() if len(y)%2!=0: print -1 else: print (abs(y.count('R')-y.count('L'))+abs(y.count('U')-y.count('D')))/2
Python
[ "strings" ]
764
128
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,931
202396838c98654c4e40179f21a225a0
Let's denote the size of the maximum matching in a graph G as \mathit{MM}(G).You are given a bipartite graph. The vertices of the first part are numbered from 1 to n, the vertices of the second part are numbered from n+1 to 2n. Each vertex's degree is 2.For a tuple of four integers (l, r, L, R), where 1 \le l \le r \le n and n+1 \le L \le R \le 2n, let's define G'(l, r, L, R) as the graph which consists of all vertices of the given graph that are included in the segment [l, r] or in the segment [L, R], and all edges of the given graph such that each of their endpoints belongs to one of these segments. In other words, to obtain G'(l, r, L, R) from the original graph, you have to remove all vertices i such that i \notin [l, r] and i \notin [L, R], and all edges incident to these vertices.Calculate the sum of \mathit{MM}(G(l, r, L, R)) over all tuples of integers (l, r, L, R) having 1 \le l \le r \le n and n+1 \le L \le R \le 2n.
['brute force', 'combinatorics', 'constructive algorithms', 'dfs and similar', 'graph matchings', 'greedy', 'math']
class unionfind: def __init__(self,uni_num): self.uni_num=uni_num self.union_root = [-1 for i in range(self.uni_num + 1)] self.union_depth = [0] * (self.uni_num + 1) self.e_num=[0]*(self.uni_num+1) def find(self,x): # θ¦ͺはθͺ°οΌŸ if self.union_root[x] < 0: return x else: self.union_root[x] = self.find(self.union_root[x]) return self.union_root[x] def unite(self,x, y): x = self.find(x) y = self.find(y) if x == y: self.e_num[x]+=1 return if self.union_depth[x] < self.union_depth[y]: x, y = y, x if self.union_depth[x] == self.union_depth[y]: self.union_depth[x] += 1 self.union_root[x] += self.union_root[y] self.union_root[y] = x self.e_num[x]+=self.e_num[y]+1 def size(self,x): return -self.union_root[self.find(x)] def same(self,x,y): return self.find(x)==self.find(y) def edge(self,x): return self.e_num[self.find(x)] n=int(input()) root=[[] for i in range(2*n+3)] uf=unionfind(2*n+10) for i in range(2*n): u,v=map(int,input().split()) root[u].append(v) root[v].append(u) uf.unite(u,v) seen=[0]*(2*n+4) def cnt(mal,mir,maL,miR,ng1,ng2): if mal>mir or maL>miR:return 0 res1=mal*(n+1-mir) if 1<=ng1<=n: a,b=min(mal,ng1),max(mir,ng1) res1-=a*(n+1-b) if 1<=ng2<=n: a, b = min(mal, ng2), max(mir, ng2) res1 -= a * (n + 1 - b) if (1<=ng1<=n and 1<=ng2<=n): a,b=min(mal,ng1,ng2),max(mir,ng1,ng2) res1+=a*(n+1-b) maL-=n miR-=n ng1-=n ng2-=n res2=maL*(n+1-miR) if 1<=ng1<=n: a,b=min(maL,ng1),max(miR,ng1) res2-=a*(n+1-b) if 1<=ng2<=n: a, b = min(maL, ng2), max(miR, ng2) res2 -= a * (n + 1 - b) if (1<=ng1<=n and 1<=ng2<=n): a,b=min(maL,ng1,ng2),max(miR,ng1,ng2) res2+=a*(n+1-b) return res1*res2 ans=0 for x in range(1,2*n+1): if x!=uf.find(x):continue path=[x] now=x while 1: seen[now]=1 flag=0 for y in root[now]: if seen[y]:continue now=y path.append(y) flag=1 break if not flag:break m=len(path) for indl in range(m): maxl = 10 ** 10 minr = -10 ** 10 maxL = 10 ** 10 minR = -10 ** 10 indr=(indl+1)%m num=0 while 1: if indr==indl:break ans+=(num//2)*cnt(maxl,minr,maxL,minR,path[indl],path[indr]) nod=path[indr] if nod<=n: maxl=min(maxl,nod) minr=max(minr,nod) else: maxL=min(maxL,nod) minR=max(minR,nod) num+=1 indr+=1 indr%=m for ind in range(m): maxl = 10 ** 10 minr = -10 ** 10 maxL = 10 ** 10 minR = -10 ** 10 i=(ind+1)%m while 1: if i==ind:break nod = path[i] if nod <= n: maxl = min(maxl, nod) minr = max(minr, nod) else: maxL = min(maxL, nod) minR = max(minR, nod) i=(i+1)%m num=m-1 ans+=(num//2)*cnt(maxl,minr,maxL,minR,path[ind],path[ind]) maxl = 10 ** 10 minr = -10 ** 10 maxL = 10 ** 10 minR = -10 ** 10 for i in range(m): nod = path[i] if nod <= n: maxl = min(maxl, nod) minr = max(minr, nod) else: maxL = min(maxL, nod) minR = max(minR, nod) num=m ans += (num // 2) * cnt(maxl, minr, maxL, minR,10**9,10**9) print(ans)
Python
[ "math", "graphs" ]
1,066
3,790
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,188
9cf8b711a3fcf5dd5059f323f107a0bd
You have matrix a of size n Γ— n. Let's number the rows of the matrix from 1 to n from top to bottom, let's number the columns from 1 to n from left to right. Let's use aij to represent the element on the intersection of the i-th row and the j-th column. Matrix a meets the following two conditions: for any numbers i, j (1 ≀ i, j ≀ n) the following inequality holds: aij β‰₯ 0; . Matrix b is strictly positive, if for any numbers i, j (1 ≀ i, j ≀ n) the inequality bij &gt; 0 holds. You task is to determine if there is such integer k β‰₯ 1, that matrix ak is strictly positive.
['math', 'graphs']
#!py2 def solve(N, A): graph = [set() for _ in xrange(N)] rgraph = [set() for _ in xrange(N)] for u, row in enumerate(A): for v, val in enumerate(row): if val: graph[u].add(v) rgraph[v].add(u) # Try to write row 0 in terms of row i stack, seen = [0], {0} while stack: node = stack.pop() for nei in graph[node]: if nei not in seen: seen.add(nei) stack.append(nei) if len(seen) != N: return False # Try to write row i in terms of row 0 stack, seen = [0], {0} while stack: node = stack.pop() for nei in rgraph[node]: if nei not in seen: seen.add(nei) stack.append(nei) return len(seen) == N N = int(raw_input()) A = [[+(x != '0') for x in raw_input().split()] for _ in xrange(N)] print "YES" if solve(N, A) else "NO"
Python
[ "math", "graphs" ]
577
957
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
1,234
c01da186ee69936eb274dce6e1222e43
For a given sequence of distinct non-negative integers (b_1, b_2, \dots, b_k) we determine if it is good in the following way: Consider a graph on k nodes, with numbers from b_1 to b_k written on them. For every i from 1 to k: find such j (1 \le j \le k, j\neq i), for which (b_i \oplus b_j) is the smallest among all such j, where \oplus denotes the operation of bitwise XOR (https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph. We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.You can find an example below (the picture corresponding to the first test case). Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5.However, sequence (0, 1, 5, 2) is good. You are given a sequence (a_1, a_2, \dots, a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal?It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good.
['dp', 'bitmasks', 'divide and conquer', 'data structures', 'binary search', 'trees']
n = int(input()) l = list(map(int,input().split())) def fun(a): if len(a) <= 3: return len(a) maxE = max(a) if maxE == 0: return len(a) msb = 1 while 2 * msb <= maxE: msb *= 2 l1 = [] l2 = [] for x in a: if x >= msb: l1.append(x-msb) else: l2.append(x) max1 = fun(l1) max2 = fun(l2) if max1 == 0: return max2 if max2 == 0: return max1 return max(1+max1,1+max2) print(n - fun(l))
Python
[ "trees" ]
1,521
588
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
322
f097cc7057bb9a6b9fc1d2a11ee99835
Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i β€” the number of vertices j in the subtree of vertex i, such that a_j &lt; a_i. Illustration for the second example, the first integer is a_i and the integer in parentheses is c_iAfter the new year, Evlampiy could not remember what his gift was! He remembers the tree and the values of c_i, but he completely forgot which integers a_i were written on the vertices.Help him to restore initial integers!
['graphs', 'constructive algorithms', 'data structures', 'dfs and similar', 'trees']
# https://codeforces.com/contest/1287/problem/D def push(g, u, v): if u not in g: g[u] = [] g[u].append(v) def build(): S = [root] i = 0 order = {} while i < len(S): u = S[i] if u in g: for v in g[u]: S.append(v) i+=1 for u in S[::-1]: order[u] = [] flg=False if u not in g: if cnt[u]==0: order[u].append(u) flg=True else: return False, root, order else: cur = 0 for v in g[u]: for x in order[v]: if cur==cnt[u]: flg=True order[u].append(u) cur+=1 order[u].append(x) cur+=1 if flg == False: if cnt[u] > len(order[u]): return False, root, order else: order[u].append(u) return True, root, order n = int(input()) g = {} cnt = {} for i in range(1, n+1): p, c = map(int, input().split()) cnt[i] = c if p==0: root = i else: push(g, p, i) flg, root, order = build() if flg==False: print('NO') else: ans = [-1] * n for val, u in zip(list(range(n)), order[root]): ans[u-1] = val + 1 print('YES') print(' '.join([str(x) for x in ans])) #5 #0 1 #1 3 #2 1 #3 0 #2 0 #3 #2 0 #0 2 #2 0
Python
[ "graphs", "trees" ]
661
1,591
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,659
17d29a0c2ab4e4be14fe3bdeb10d1e55
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled!When building the graph, he needs four conditions to be satisfied: It must be a simple undirected graph, i.e. without multiple (parallel) edges and self-loops. The number of vertices must be exactly n β€” a number he selected. This number is not necessarily prime. The total number of edges must be prime. The degree (i.e. the number of edges connected to the vertex) of each vertex must be prime. Below is an example for n = 4. The first graph (left one) is invalid as the degree of vertex 2 (and 4) equals to 1, which is not prime. The second graph (middle one) is invalid as the total number of edges is 4, which is not a prime number. The third graph (right one) is a valid answer for n = 4. Note that the graph can be disconnected.Please help Bob to find any such graph!
['constructive algorithms', 'number theory', 'greedy', 'math']
prime = [-1]*(2001) for i in range(2,2001): if prime[i]==-1: for j in range(i,2001,i): prime[j] = i n = int(input()) e = [] for i in range(n): e.append((i,(i+1)%n)) if prime[n]==n: print (len(e)) for i in e: print (i[0]+1,i[1]+1) else: i = 1 j = n-1 while prime[n]!=n: e.append((i,j)) i += 1 j -= 1 n += 1 print (len(e)) for i in e: print (i[0]+1,i[1]+1)
Python
[ "number theory", "math" ]
1,088
381
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,033
09a0bad93090b65b5515abf0ccb96bd4
The only difference with E1 is the question of the problem.Vlad built a maze out of n rooms and n-1 bidirectional corridors. From any room u any other room v can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited k friends to play a game with them.Vlad starts the game in the room 1 and wins if he reaches a room other than 1, into which exactly one corridor leads. Friends are placed in the maze: the friend with number i is in the room x_i, and no two friends are in the same room (that is, x_i \neq x_j for all i \neq j). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time.Friends know the plan of a maze and intend to win. They don't want to waste too much energy. They ask you to determine if they can win and if they can, what minimum number of friends must remain in the maze so that they can always catch Vlad.In other words, you need to determine the size of the minimum (by the number of elements) subset of friends who can catch Vlad or say that such a subset does not exist.
['dfs and similar', 'dp', 'greedy', 'shortest paths', 'trees']
from collections import defaultdict, deque import sys input = sys.stdin.buffer.readline for _ in range(int(input())): input() n, k = map(int, input().split()) fl = input() d = defaultdict(list) for _ in range(n-1): a, b = map(int, input().split()) d[a].append(b) d[b].append(a) p = dict() c = defaultdict(list) vis = set() q = deque([(1, None)]) while q: curr, prev = q.popleft() if curr in vis: continue vis.add(curr) if prev: p[curr] = prev c[prev].append(curr) for v in d[curr]: if v not in vis: q.append((v, curr)) dist = dict() # q = deque([(x,0) for x in fl]) q = deque(map(lambda x: (int(x),0), fl.split())) while q: curr, dis = q.popleft() if curr in dist: continue dist[curr] = dis if curr != 1 and p[curr] not in dist: q.append((p[curr], dis+1)) # vis = set() q = deque([(1,0)]) ans = 0 while q: curr, dis = q.popleft() if curr not in dist: ans = -1 break elif dis == dist[curr] or dis == dist[curr]+1: ans += 1 continue elif not c[curr]: ans = -1 break else: for v in c[curr]: q.append((v,dis+1)) print(ans)
Python
[ "graphs", "trees" ]
1,330
1,172
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,150
d98ecf6c5550e7ec7639fcd1f727fb35
Calculate the value of the sum: n mod 1 + n mod 2 + n mod 3 + ... + n mod m. As the result can be very large, you should print the value modulo 109 + 7 (the remainder when divided by 109 + 7).The modulo operator a mod b stands for the remainder after dividing a by b. For example 10 mod 3 = 1.
['implementation', 'number theory', 'math']
n,m = map(int,raw_input().split(" ")) ans = 0 w = 1000000007 if m > n: ans += n*(m-n) m = n last = min(m,n-1) def su(s,e,l): return (s+e)*l/2 for i in xrange(2,900000): q = n/i if q >= last: continue ans += (n%last+n%(q+1))*(last-q)/2 last = q ans %= w for i in xrange(1,last+1): ans += n%i ans %= w print ans%w
Python
[ "number theory", "math" ]
293
326
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,291
5f4009d4065f5ad39e662095f8f5c068
You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t.Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For example, for k=2, s="az" and t="bf" the list will be ["az", "ba", "bb", "bc", "bd", "be", "bf"].Your task is to print the median (the middle element) of this list. For the example above this will be "bc".It is guaranteed that there is an odd number of strings lexicographically not less than s and not greater than t.
['number theory', 'bitmasks', 'math', 'strings']
import sys, bisect, heapq, math sys.setrecursionlimit(10**9+7) def fi(): return int(sys.stdin.readline()) def fi2(): return map(int, sys.stdin.readline().split()) def fi3(): return sys.stdin.readline().rstrip() def fo(*args): for s in args: sys.stdout.write(str(s)+' ') sys.stdout.write('\n') ## sys.stdout.flush() def puts(*args): for s in args: sys.stdout.write(str(s)) OUT = [] def bfo(*args): for s in args: OUT.append(str(s)+' ') OUT.append('\n') def bputs(*args): for s in args: OUT.append(str(s)) def flush(): sto = ''.join(OUT); fo(sto) ## alpha = 'abcdefghijklmnopqrstuvwxyz'; mod = 10**9+7; inf = 10**18+5; nax = 101010 inv = {} for i in range(26): inv[alpha[i]] = i ## class base26: def __init__(self, s): s = s[::-1] self.a = [0 for i in range(len(s)+10)] for i in range(len(s)): self.a[i] = inv[s[i]] def getstr(self): s = [] for x in self.a: s.append(alpha[x]) s.reverse() s = ''.join(s) return s def __add__(self, other): A = [0 for i in range(len(self.a))] carry = 0 for i in range(len(self.a)): S = self.a[i]+other.a[i]+carry if(S <= 25): A[i] = S carry = 0 else: A[i] = S%26 carry = 1 N = base26('') N.a = A return N def div2(self): carry = 0 n = len(self.a) for i in range(n-1, -1, -1): K = self.a[i]+carry*26 if(K%2 == 0): carry = 0 self.a[i] = K/2 else: carry = 1 self.a[i] = K/2 k = fi() s = fi3() t = fi3() a = base26(s) b = base26(t) c = a + b c.div2() res = c.getstr() res = res[-k:] bfo(res) flush()
Python
[ "math", "number theory", "strings" ]
722
1,873
0
0
0
1
1
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 1, "trees": 0 }
1,359
9b9b85f84636ebd0f7af8b410d9820f7
Alice and Bob are playing a game. There are n cells in a row. Initially each cell is either red or blue. Alice goes first.On each turn, Alice chooses two neighbouring cells which contain at least one red cell, and paints that two cells white. Then, Bob chooses two neighbouring cells which contain at least one blue cell, and paints that two cells white. The player who cannot make a move loses.Find the winner if both Alice and Bob play optimally.Note that a chosen cell can be white, as long as the other cell satisfies the constraints.
['constructive algorithms', 'dp', 'games']
nimv = [1] * 500 def mex(x): x.sort() c=0 for i in x: if i == c: c += 1 return c cnts = [4,4,4,24,4,4,4,14] nimv[:3]= [0,1,1] cp = 0 ci = 4 for i in range(3,500): nimv[i]=mex([nimv[i-2]] + [nimv[i-j-3] ^ nimv[j] for j in range(i-2)]) q = nimv[-34*3:] for i in range(5000): nimv.extend(q) for i in range(int(input())): n=int(input()) a=input() cv=0 cc = 0 for i in range(n-1): if (a[i] == 'R' and a[i+1]=='B') or (a[i]=='B' and a[i+1]=='R'): cc+=1 elif cc: cv ^= nimv[cc] cc = 0 cv ^= nimv[cc] ## print(cv) if (a.count('R') - a.count('B') + (1 if cv else 0)) >0: print("Alice") else: print("Bob")
Python
[ "games" ]
544
778
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
986
da38d1a63152e0a354b04936e9511969
Mike has a sequence A = [a1, a2, ..., an] of length n. He considers the sequence B = [b1, b2, ..., bn] beautiful if the gcd of all its elements is bigger than 1, i.e. . Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1 ≀ i &lt; n), delete numbers ai, ai + 1 and put numbers ai - ai + 1, ai + ai + 1 in their place instead, in this order. He wants perform as few operations as possible. Find the minimal number of operations to make sequence A beautiful if it's possible, or tell him that it is impossible to do so. is the biggest non-negative number d such that d divides bi for every i (1 ≀ i ≀ n).
['dp', 'number theory', 'greedy']
def main(): from math import gcd input() aa = list(map(int, input().split())) g = r = t = 0 while aa and g != 1: a = aa.pop() if t: r += 2 - (a & 1) t = 0 else: t = (a & 1) * 2 g = gcd(a, g) for a in reversed(aa): if t: r += 2 - (a & 1) t = 0 else: t = (a & 1) * 2 print("YES", (r + t) * (g < 2), sep='\n') if __name__ == '__main__': main()
Python
[ "number theory" ]
654
495
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
904
c569b47cf80dfa98a7105e246c3c1e01
The string s is given, the string length is odd number. The string consists of lowercase letters of the Latin alphabet.As long as the string length is greater than 1, the following operation can be performed on it: select any two adjacent letters in the string s and delete them from the string. For example, from the string "lemma" in one operation, you can get any of the four strings: "mma", "lma", "lea" or "lem" In particular, in one operation, the length of the string reduces by 2.Formally, let the string s have the form s=s_1s_2 \dots s_n (n&gt;1). During one operation, you choose an arbitrary index i (1 \le i &lt; n) and replace s=s_1s_2 \dots s_{i-1}s_{i+2} \dots s_n.For the given string s and the letter c, determine whether it is possible to make such a sequence of operations that in the end the equality s=c will be true? In other words, is there such a sequence of operations that the process will end with a string of length 1, which consists of the letter c?
['implementation', 'strings']
for _ in range(int(input())): s = str(input()) c = str(input()) n = len(s) index = 0 for i in range(0, n+1, 2): if s[i] == c: index = 1 break if index == 1: print("YES") else: print("NO")
Python
[ "strings" ]
1,069
297
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
3,959
591846c93bd221b732c4645e50fae617
Authors have come up with the string s consisting of n lowercase Latin letters.You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once.For all i from 1 to n-1 the following properties hold: s[p_i] \le s[p_{i + 1}] and s[q_i] \le s[q_{i + 1}]. It means that if you will write down all characters of s in order of permutation indices, the resulting string will be sorted in the non-decreasing order.Your task is to restore any such string s of length n consisting of at least k distinct lowercase Latin letters which suits the given permutations.If there are multiple answers, you can print any of them.
['greedy', 'graphs', 'dsu', 'implementation', 'data structures', 'dfs and similar', 'strings']
# adapted some python code from https://www.geeksforgeeks.org/strongly-connected-components/ from collections import defaultdict, deque #This class represents a directed graph using adjacency list representation class Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) # A function used by DFS def DFSUtil(self,v,visited): 'generate all nodes in one partition' answer = [] nodes_to_visit = deque() nodes_to_visit.append(v) while len(nodes_to_visit)>0: v = nodes_to_visit.popleft() # Mark the current node as visited and print it visited[v]= True answer.append(v) #Recur for all the vertices adjacent to this vertex for i in self.graph[v]: if visited[i]==False: nodes_to_visit.appendleft(i) return answer def fillOrder(self,v,visited, stack): # # Mark the current node as visited # visited[v]= True # #Recur for all the vertices adjacent to this vertex # for i in self.graph[v]: # if visited[i]==False: # self.fillOrder(i, visited, stack) # stack = stack.append(v) ext_stack = deque() nodes = deque() nodes.append(v) while len(nodes)>0: v = nodes.popleft() visited[v]=True for i in self.graph[v]: if visited[i] == False: nodes.appendleft(i) ext_stack.append(v) while len(ext_stack)>0: stack.append(ext_stack.pop()) # Function that returns reverse (or transpose) of this graph def getTranspose(self): g = Graph(self.V) # Recur for all the vertices adjacent to this vertex for i in self.graph: for j in self.graph[i]: g.addEdge(j,i) return g # The main function that finds and prints all strongly # connected components def printSCCs(self): 'generate all components of graph (generator of lists)' stack = [] # Mark all the vertices as not visited (For first DFS) visited =[False]*(self.V) # Fill vertices in stack according to their finishing # times for i in range(self.V): if visited[i]==False: self.fillOrder(i, visited, stack) # Create a reversed graph gr = self.getTranspose() # Mark all the vertices as not visited (For second DFS) visited =[False]*(self.V) # Now process all vertices in order defined by Stack while stack: i = stack.pop() if visited[i]==False: yield list(gr.DFSUtil(i, visited)) n,k = map(int, raw_input().split()) p = [x-1 for x in map(int, raw_input().split())] q = [x-1 for x in map(int, raw_input().split())] import sys # Create a graph given in the above diagram g = Graph(n) for i in xrange(n-1): g.addEdge(p[i], p[i+1]) g.addEdge(q[i], q[i+1]) def next_letter(letter): if letter < 'z': return chr(ord(letter)+1) else: return letter partition = sorted(map(sorted, list(g.printSCCs()))) inverse = [None] * n for i,part in enumerate(partition): for j in part: inverse[j] = i if len(partition) < k: print 'NO' else: print 'YES' answer = [None] * n # for eveyrthing in the component containing p[0], give it the letter 'a' letter = 'a' for u in xrange(n): if answer[p[u]] is None: i = inverse[p[u]] for j in partition[i]: answer[j] = letter letter = next_letter(letter) print ''.join(answer)
Python
[ "graphs", "strings" ]
849
4,039
0
0
1
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,067
7b932b2d3ab65a353b18d81cf533a54e
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.Output the probability that SmallR will win the match.
['probabilities', 'math']
a,b,c,d=list(map(int,input().split())) print((a/b)/(1-(1-(a/b))*(1-(c/d))))
Python
[ "math", "probabilities" ]
333
75
0
0
0
1
0
1
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 1, "strings": 0, "trees": 0 }
4,463
31d95251cd79d889ff9f0a624ef31394
You are given a binary matrix A of size n \times n. Let's denote an x-compression of the given matrix as a matrix B of size \frac{n}{x} \times \frac{n}{x} such that for every i \in [1, n], j \in [1, n] the condition A[i][j] = B[\lceil \frac{i}{x} \rceil][\lceil \frac{j}{x} \rceil] is met.Obviously, x-compression is possible only if x divides n, but this condition is not enough. For example, the following matrix of size 2 \times 2 does not have any 2-compression: 01 10 For the given matrix A, find maximum x such that an x-compression of this matrix is possible.Note that the input is given in compressed form. But even though it is compressed, you'd better use fast input.
['dp', 'implementation', 'number theory', 'math']
import atexit, io, sys # A stream implementation using an in-memory bytes # buffer. It inherits BufferedIOBase. buffer = io.BytesIO() sys.stdout = buffer # print via here @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) def gcd(a,b): if(a>b): temp=b b=a a=temp if(a==0): return b else: return gcd(b%a,a) n=int(raw_input()) arr=[] mindiff=10**9 ans=-1 flag=0 for i in range(n): s=raw_input() s1='' j=0 while(j<len(s)): if(65<=ord(s[j])<=70): num=10+(ord(s[j])-65) s1+=bin(num)[2:] else: num=bin(int(s[j]))[2:] num=(4-len(num))*'0'+num s1+=num j+=1 initial=s1[0] j=1 count=1 while(j<len(s1)): if(s1[j]==initial): count+=1 else: if(ans==-1): ans=count else: ans=gcd(ans,count) count=1 initial=s1[j] j+=1 if(ans==-1): ans=count else: ans=gcd(ans,count) arr.append(s1) #print(*arr) if(ans==1): print(1) exit(0) for i in range(n): initial=arr[0][i] count=1 for j in range(1,n): if(arr[j][i]==initial): count+=1 else: ans=gcd(ans,count) count=1 initial=arr[j][i] if(ans==1): print(1) exit(0) ans=gcd(ans,count) if(ans==1): print(1) exit(0) print(ans)
Python
[ "number theory", "math" ]
781
1,202
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
427
a1c3876d705ac8e8b81394ba2be12ed7
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics.Polycarp needed to write a code that could, given two words, check whether they could have been obtained from the same word as a result of typos. Polycarpus suggested that the most common typo is skipping exactly one letter as you type a word.Implement a program that can, given two distinct words S and T of the same length n determine how many words W of length n + 1 are there with such property that you can transform W into both S, and T by deleting exactly one character. Words S and T consist of lowercase English letters. Word W also should consist of lowercase English letters.
['dp', 'hashing', 'greedy', 'constructive algorithms', 'two pointers', 'strings']
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## import math import bisect mod = 998244353 # for _ in range(int(input())): from collections import Counter # sys.setrecursionlimit(10**6) # dp=[[-1 for i in range(n+5)]for j in range(cap+5)] # arr= list(map(int, input().split())) # n,l= map(int, input().split()) # arr= list(map(int, input().split())) # for _ in range(int(input())): # n=int(input()) # for _ in range(int(input())): import bisect from heapq import * from collections import defaultdict,deque def okay(x,y): if x<0 or x>=3 : return False if y<n and mat[x][y]!=".": return False if y+1<n and mat[x][y+1]!=".": return False if y+2<n and mat[x][y+2]!=".": return False return True '''for i in range(int(input())): n,m=map(int, input().split()) g=[[] for i in range(n+m)] for i in range(n): s=input() for j,x in enumerate(s): if x=="#": g[i].append(n+j) g[n+j].append(i) q=deque([0]) dis=[10**9]*(n+m) dis[0]=0 while q: node=q.popleft() for i in g[node]: if dis[i]>dis[node]+1: dis[i]=dis[node]+1 q.append(i) print(-1 if dis[n-1]==10**9 else dis[n-1])''' '''from collections import deque t = int(input()) for _ in range(t): q = deque([]) flag=False n,k = map(int, input().split()) mat = [input() for i in range(3)] vis=[[0 for i in range(105)]for j in range(3)] for i in range(3): if mat[i][0]=="s": q.append((i,0)) while q: x,y=q.popleft() if y+1>=n: flag=True break if vis[x][y]==1: continue vis[x][y]=1 if (y+1<n and mat[x][y+1]=='.' and okay(x-1,y+1)==True): q.append((x-1,y+3)) if (y+1<n and mat[x][y+1]=='.' and okay(x,y+1)==True): q.append((x,y+3)) if (y+1<n and mat[x][y+1]=='.' and okay(x+1,y+1)==True): q.append((x+1,y+3)) if flag: print("YES") else: print("NO") # ls=list(map(int, input().split())) # d=defaultdict(list)''' from collections import defaultdict #for _ in range(int(input())): n=int(input()) #n,k= map(int, input().split()) #arr=sorted([i,j for i,j in enumerate(input().split())]) s=input() t=input() n=len(s) f=0 l=0 i=0 while s[i]==t[i]: i+=1 j=n-1 while s[j]==t[j]: j-=1 print(int(s[i:j]==t[i+1:j+1])+int(s[i+1:j+1]==t[i:j]))
Python
[ "strings" ]
828
4,139
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,640
48b232b9d836b0be91d41e548a9fcefc
Insurgents accidentally got hold of the plan of a top secret research polygon created on a distant planet for the needs of the Galaxy Empire. The insurgents suppose that this polygon is developing new deadly weapon. The polygon consists of n missile silos connected by bidirectional underground passages. The passages are linked to laboratories where research is conducted. Naturally, the passages are guarded severely: the passage between silos i and j is patrolled by ci, j war droids.The insurgents studied the polygon plan and noticed its unusual structure. As it turned out, for any k-element set of silos S there is exactly one silo that is directly connected by a passage with each silo from S (we'll call this silo adjacent with S). Having considered that, the insurgents decided to act as follows: they choose a k-element set of silos S; a group of scouts lands from the air into each silo from S; each group moves along the corresponding passage to the silo, adjacent with S (as the scouts move, they check out the laboratories and watch for any signs of weapon blueprints); in the silo, adjacent with S, the groups get on the ship and fly away. The danger of the operation is the total number of droids that patrol the passages through which the scouts will go. The danger of the operation obviously only depends on the way to choose set S. The insurgents haven't yet decided on the exact silos to send the scouts to. However, they already want to start preparing the weapons for the scout groups. To do that, the insurgents need to know the mathematical average of the dangers of the operations that correspond to all possible ways to choose set S. Solve this problem to help the insurgents protect the ideals of the Republic!
['math', 'graphs']
import sys sys.setrecursionlimit(2100) range = xrange input = raw_input def getter(DP, k): n = len(DP) - 1 if 2 * k >= n: k = n - k if k < 0: return 0 return DP[k] inp = [int(x) for x in sys.stdin.read().split()]; ii = 0 n = inp[ii]; ii += 1 k = inp[ii]; ii += 1 DP = [1] DPk = [] DPkm1 = [] for N in range(1, 2002): DPk.append(getter(DP, k)) DPkm1.append(getter(DP, k-1)) DP = [getter(DP, K) + getter(DP, K - 1) for K in range(N + 1)] sm = [0]*(n+2) cnt = [0]*(n+2) for i in range(1, n): for j in range(i+1, n+1): x = inp[ii]; ii += 1 if x != -1: cnt[i] += 1 cnt[j] += 1 sm[i] += x sm[j] += x ans = 0 for i in range(1, n+1): ans += sm[i]*DPkm1[cnt[i] - 1] print ans // DPk[n]
Python
[ "math", "graphs" ]
1,742
796
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
212
84c60293d487e2c2ecee38a2fcf63b10
This is an easy version of the problem. The only difference between an easy and a hard version is the constraints on a, b, c and d.You are given 4 positive integers a, b, c, d with a &lt; c and b &lt; d. Find any pair of numbers x and y that satisfies the following conditions: a &lt; x \leq c, b &lt; y \leq d, x \cdot y is divisible by a \cdot b.Note that required x and y may not exist.
['brute force', 'math', 'number theory']
# a<c and b<d # a<x≀c and b<y≀d # xy is divisible by ab. import math def find_div(a,b,c,d): start = time() if a==b==1 or (c*d)/(a*b) == (c*d)//(a*b): return c, d if a*2<=c and b*2<=d: return 2*a, 2*b if c*d < 2*a*b: return -1,-1 else: # executes if cd > 2ab s =[] if a<b: s.append(a) s.append(b) else: s.append(b) s.append(a) if c<1000 and d<1000: for x in range(a+1, c+1): for y in range(b+1, d+1): if (x*y) % (a*b) == 0: return x, y else: if a==1 and b==1: return 2, 2 if a==1 and b<=c and b+1<=d: return b, b+1 if b==1 and a<=d and a+1<=c: return a+1, a for i in range(2, (c*d)//(a*b)+1): if time() - start > 3.9: return -1,-1 if i*a*b <= c*d: num = i*a*b if a<b: for j in range(num//d, num//b+1): if num % j == 0: if b<num//j<=d and a<j<=c: return j, num//j else: for j in range(num//c, num//a+1): if num % j == 0: if a<num//j<=c and b<j<=d: return num//j, j return -1,-1 from time import time tests = int(input()) d = tests*[4*[0]] results = [] for i in range(tests): # iterates through each test case = [int(x) for x in input().strip().split()] #st = time() if case in d: x, y = results[d.index(case)][0], results[d.index(case)][1] else: d[i]=case x, y = find_div(d[i][0],d[i][1],d[i][2],d[i][3]) results.append([x, y]) print(x, y) #print(time()-st)
Python
[ "math", "number theory" ]
503
2,032
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
2,034
055346dd6d2e0cff043b52a395e31fdf
You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n.A path from u to v is a sequence of edges such that: vertex u is the start of the first edge in the path; vertex v is the end of the last edge in the path; for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u.For each vertex v output one of four values: 0, if there are no paths from 1 to v; 1, if there is only one path from 1 to v; 2, if there is more than one path from 1 to v and the number of paths is finite; -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. Then: the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); the answer for vertex 2 is 0: there are no paths from 1 to 2; the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times).
['dfs and similar', 'dp', 'graphs', 'trees']
from collections import Counter, deque # from itertools import combinations import bisect import heapq from locale import currency import math from re import S import sys from types import GeneratorType # sys.stdin = open('grey.in', 'r') # sys.setrecursionlimit(1 * 10**9) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc result = [] LOG = 18 array = [1, 2, 3, 4, 5, 6, 7, 8] def calc(numOne, numTwo): currentSum = 0 for i in range(32): firstBit, secondBit = min(1, numOne & (1 << i)), min(1, numTwo & (1 << i)) currentSum += (firstBit ^ secondBit) return currentSum # counter = Counter() # for i in range(0, 119000): # counter[calc(i, i + 1)] += 1 # print(counter) input = sys.stdin.readline # t = int(input()) # result = [] # for _ in range(t): # a, b = map(int, input().split()) # def solve(): # state = False # count = 0 # currentMin = float('inf') # for z in range(0, b + 5): # currentB = b + z # count = 0 # for i in range(32): # firstBit, secondBit = a & (1 << i), currentB & (1 << i) # if secondBit and not firstBit: # state = True # continue # if firstBit and not secondBit: # count += (2**i) # currentMin = min(currentMin, count + 1 + z if state else count + z) # return min(currentMin, b - a) # print(solve()) # # print(result) class SegmentTree2D: def __init__(self, row, col, inMatrix): self.rows = row self.cols = col self.inMatrix = inMatrix self.matrix = [[0 for z in range(col + 1)] for i in range(row + 1)] self.genTable() def genTable(self): self.matrix[0][0] = 0 for row in range(self.rows): currentSum = 0 for col in range(self.cols): currentSum += self.inMatrix[row][col] above = self.matrix[row][col + 1] self.matrix[row + 1][col + 1] = currentSum + above def sumRegion(self, rowOne, colOne, rowTwo, colTwo): rowOne += 1 rowTwo += 1 colOne += 1 colTwo += 1 bottomRight, above = self.matrix[rowTwo][colTwo], self.matrix[rowOne - 1][colTwo] left, topLeft = self.matrix[rowTwo][colOne - 1], self.matrix[rowOne - 1][colOne - 1] return bottomRight - above - left + topLeft class LCA: def __init__(self, neighbourNodes, rootNode): self.neighbourNodes = neighbourNodes self.log = 18 self.parentNode = [[i for i in range(self.log)] for z in range(len(neighbourNodes))] self.depth = [0 for i in range(len(neighbourNodes))] self.bfs(rootNode, rootNode, 0) def bfs(self, currentNode, parentNode, currentDepth): queue = deque() queue.append((currentNode, parentNode, currentDepth)) while(queue): currentNode, parentNode, currentDepth = queue.popleft() self.parentNode[currentNode][0] = parentNode for i in range(1, self.log): self.parentNode[currentNode][i] = self.parentNode[self.parentNode[currentNode][i - 1]][i - 1] for node in self.neighbourNodes[currentNode]: if node != parentNode: queue.append((node, currentNode, currentDepth + 1)) self.depth[currentNode] = currentDepth def lca(self, nodeOne, nodeTwo): diff = abs(self.depth[nodeOne] - self.depth[nodeTwo]) if self.depth[nodeOne] < self.depth[nodeTwo]: nodeOne, nodeTwo = nodeTwo, nodeOne for i in reversed(range(self.log)): if diff & (1 << i): nodeOne = self.parentNode[nodeOne][i] if nodeOne == nodeTwo: return nodeOne for i in reversed(range(self.log)): if self.parentNode[nodeOne][i] != self.parentNode[nodeTwo][i]: nodeOne, nodeTwo = self.parentNode[nodeOne][i], self.parentNode[nodeTwo][i] return self.parentNode[nodeOne][0] def power(a, b, mod): if not b: return 1 temp = power(a, b // 2, mod) result = temp * temp if b % 2 == 0 else temp * temp * a result %= mod return result def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def genSparseTable(array, comp): sparseTable = [[float('inf') for i in range(LOG)] for x in range(len(array))] for i in range(len(array)): sparseTable[i][0] = array[i] for i in range(1, LOG): j = 0 while((j + (1 << i) - 1) < len(array)): sparseTable[j][i] = comp(sparseTable[j][i - 1], sparseTable[j + (1 << (i - 1))][i - 1]) j += 1 return sparseTable def query(l, r, sparseTable, comp): length = (r - l) + 1 idx = int(math.log(length, 2)) return comp(sparseTable[l][idx], sparseTable[r - (1 << idx) + 1][idx]) # t = int(input()) # for _ in range(t): # n, x, y = map(int, input().split()) # stringOne, stringTwo = map(int, input().split()) # def solve(): # rightMostIdx = None # cnt = 0 # for numOne, numTwo in zip(stringOne, stringTwo): # if numOne != numTwo: # cnt += 1 # if cnt % 2: # return -1 # for i in reversed(range(n)): # if stringOne[i] == stringTwo[i]: # rightMostIdx = i # break # leftMostIdx = None # currentIdx = 0 # total = 0 # while(currentIdx < n - 1): # if stringOne[currentIdx] != stringTwo[currentIdx] and stringOne[currentIdx + 1] != stringTwo[currentIdx + 1]: # if rightMostIdx is not None and rightMostIdx - 1 > currentIdx + 1: # total += min(x, 2 * y) # elif leftMostIdx is not None and leftMostIdx + 1 < currentIdx: # total += min(x, 2 * y) # else: # total += x # if leftMostIdx is None: # leftMostIdx = currentIdx # currentIdx += 2 # elif stringOne[currentIdx] != stringTwo[currentIdx]: input = sys.stdin.readline t = int(input()) for _ in range(t): input() n, m = map(int, input().split()) neighbourNodes = [[] for i in range(n)] for i in range(m): path, toPath = map(int, input().split()) path -= 1 toPath -= 1 neighbourNodes[path].append(toPath) def solve(): revNeighbourNodes = [[] for i in range(n)] for node in range(n): for neighbour in neighbourNodes[node]: revNeighbourNodes[neighbour].append(node) component = [node for node in range(n)] visited = [False for node in range(n)] stack = [] @bootstrap def dfsOne(currentNode): if visited[currentNode]: yield None visited[currentNode] = True for node in revNeighbourNodes[currentNode]: (yield dfsOne(node)) stack.append(currentNode) yield None; for node in range(n): if not visited[node]: dfsOne(node) @bootstrap def dfsTwo(currentNode, comp): if visited[currentNode]: yield None visited[currentNode] = True component[currentNode] = comp for node in neighbourNodes[currentNode]: if not visited[node]: (yield dfsTwo(node, comp)) yield None visited = [False for node in range(n)] while(stack): currentNode = stack.pop() if not visited[currentNode]: dfsTwo(currentNode, currentNode) isCycle = [False for node in range(n)] counter = Counter(component) for comp in counter: if counter[comp] > 1: isCycle[comp] = True for node in range(n): for neighbour in neighbourNodes[node]: if node == neighbour: isCycle[component[node]] = True break newEdges = [[] for node in range(n)] for node in range(n): for neighbour in neighbourNodes[node]: if component[node] != component[neighbour]: newEdges[component[node]].append(component[neighbour]) result = [0 for node in range(n)] visited = [False for node in range(n)] toBeVisited = [] @bootstrap def dfsThree(currentNode, currentAns): result[currentNode] += currentAns visited[currentNode] = True for node in newEdges[currentNode]: if visited[node]: result[node] += currentAns toBeVisited.append(node) continue newAns = currentAns if not isCycle[node] else float('inf') (yield dfsThree(node, newAns)) yield None ans = 1 if not isCycle[component[0]] else float('inf') dfsThree(component[0], ans) visited = [False for node in range(n)] @bootstrap def dfsFour(currentNode, ans): result[currentNode] += ans visited[currentNode] = True for node in newEdges[currentNode]: if not visited[node]: (yield dfsFour(node, max(ans, result[currentNode]))) yield None toBeVisited.sort(reverse = True, key = lambda x: (result[x])) for node in toBeVisited: if not visited[node]: dfsFour(node, result[node]) for node in range(n): ans = result[component[node]] if ans not in [-1, 0, 1, 2]: if ans == float('inf'): ans = -1 elif ans > 1: ans = 2 else: ans = 0 result[node] = ans result = [str(re) for re in result] for i in range(len(result)): if result[i] == "inf": result[i] = str(-1) return result print(' '.join(solve()))
Python
[ "graphs", "trees" ]
1,835
12,702
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,406
4791a795119c185b3aec91b6f8af8f03
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numbers consist of six identical digits (for example, 22-22-22), the numbers of pizza deliveries should necessarily be decreasing sequences of six different digits (for example, 98-73-21), all other numbers are the girls' numbers.You are given your friends' phone books. Calculate which friend is best to go to when you are interested in each of those things (who has maximal number of phone numbers of each type). If the phone book of one person contains some number two times, you should count it twice. That is, each number should be taken into consideration the number of times it occurs in the phone book.
['implementation', 'strings']
n=int(input()) t,p,c=[0,0,0] T='' P='' C='' for i in range(n): a,n=input().split() x,y,z=[0,0,0] for j in range(int(a)): s=input() s=s.replace('-','') if len(set(s))==1: x=x+1 else: f=1 for k in range(1,len(s)): if int(s[k])>=int(s[k-1]): f=0 break if f: y=y+1 else: z=z+1 if x==t: if T=='': T=n else: T=T+', '+n if y==p: if P=='': P=n else: P=P+', '+n if z==c: if C=='': C=n else: C=C+', '+n if x>t: t=x T=n if y>p: p=y P=n if z>c: c=z C=n print("If you want to call a taxi, you should call: "+T+'.') print("If you want to order a pizza, you should call: "+P+'.') print("If you want to go to a cafe with a wonderful girl, you should call: "+C+'.')
Python
[ "strings" ]
926
1,071
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
644
dc3848faf577c5a49273020a14b343e1
You are given a tree of n vertices numbered from 1 to n. A tree is a connected undirected graph without cycles. For each i=1,2, \ldots, n, let w_i be the weight of the i-th vertex. A vertex is called good if its weight is equal to the sum of the weights of all its neighbors.Initially, the weights of all nodes are unassigned. Assign positive integer weights to each vertex of the tree, such that the number of good vertices in the tree is maximized. If there are multiple ways to do it, you have to find one that minimizes the sum of weights of all vertices in the tree.
['constructive algorithms', 'dfs and similar', 'dp', 'implementation', 'trees']
#!/usr/bin/env python3 import sys # import getpass # not available on codechef # import math, random # import functools, itertools, collections, heapq, bisect from collections import defaultdict input = sys.stdin.readline # to read input quickly # available on Google, AtCoder Python3, not available on Codeforces # import numpy as np # import scipy MAXINT = sys.maxsize # if testing locally, print to terminal with a different color # OFFLINE_TEST = getpass.getuser() == "htong" OFFLINE_TEST = False # codechef does not allow getpass def log(*args): if OFFLINE_TEST: print('\033[36m', *args, '\033[0m', file=sys.stderr) def read_matrix(rows): return [list(map(int,input().split())) for _ in range(rows)] def minus_one_matrix(mrr): return [[x-1 for x in row] for row in mrr] # ---------------------------- template ends here ---------------------------- # https://codeforces.com/blog/entry/80158?locale=en from types import GeneratorType def bootstrap(f, stack=[]): # usage - please remember to YIELD to call and return ''' @bootstrap def recurse(n): if n <= 0: yield 0 yield (yield recurse(n-1)) + 2 res = recurse(10**5) ''' def wrappedfunc(*args): if stack: return f(*args) else: to = f(*args) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: if stack: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc if True: total_vertices = int(input()) # read line as a string # srr = input().strip() # read one line and parse each word as a string # arr = input().split() # read one line and parse each word as an integer # a,b,c = list(map(int,input().split())) # arr = list(map(int,input().split())) # arr = minus_one(arr) # read multiple rows # arr = read_strings(k) # and return as a list of str mrr = read_matrix(total_vertices-1) # and return as a list of list of int mrr = minus_one_matrix(mrr) # if total_vertices == 2: # return 2,2,[1,1] # your solution here # https://courses.grainger.illinois.edu/cs473/sp2011/lectures/09_lec.pdf g = defaultdict(set) for a,b in mrr: g[a].add(b) g[b].add(a) # log(a, b) degree = defaultdict(int) for x in range(total_vertices): degree[x] = len(g[x]) opt = [-1 for _ in range(total_vertices)] opt1_store = [-1 for _ in range(total_vertices)] opt2_store = [-1 for _ in range(total_vertices)] start = allstart = 0 assignment = [0 for _ in range(total_vertices)] def dfs(start, g, entry_operation, exit_operation): entered = set([start]) exiting = set() stack = [start] prev = {} null_pointer = "NULL" prev[start] = null_pointer while stack: cur = stack[-1] if cur not in exiting: for nex in g[cur]: if nex in entered: continue entry_operation(prev[cur], cur, nex) entered.add(nex) stack.append(nex) prev[nex] = cur exiting.add(cur) else: stack.pop() exit_operation(prev[cur], cur) def entry_operation(prev, cur, nex): pass def exit_operation(prev, cur): opt1 = 1_000_000 - degree[cur] + 1 opt2 = 0 for nex in g[cur]: if nex == prev: continue opt2 += opt[nex] for nex_nex in g[nex]: if nex_nex == cur: continue opt1 += opt[nex_nex] opt1_store[cur] = opt1 opt2_store[cur] = opt2 opt[cur] = max(opt1, opt2) dfs(0, g, entry_operation, exit_operation) color = {} color[0] = 1 - int(opt[0] == opt2_store[0]) def entry_operation(prev, cur, nex): if color[cur] == 1 or opt[nex] == opt2_store[nex]: color[nex] = 0 else: color[nex] = 1 def exit_operation(prev, cur): pass dfs(0, g, entry_operation, exit_operation) # assert -1 not in assignment # assert -1 not in opt # assert -1 not in opt1_store # assert -1 not in opt2_store log(opt) # log(assignment) assignment = [degree[i] if color[i] else 1 for i in range(total_vertices)] a = sum(degree[i] == x for i,x in enumerate(assignment)) b = sum(assignment) print(a,b) print(" ".join(str(x) for x in assignment))
Python
[ "graphs", "trees" ]
607
4,844
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
1,096
f4d6c39a8224fb1fdb1cda63636f7f8e
Vova again tries to play some computer card game.The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number ai is written on the i-th card in the deck.After receiving the deck and the magic number, Vova removes x (possibly x = 0) cards from the top of the deck, y (possibly y = 0) cards from the bottom of the deck, and the rest of the deck is his new deck (Vova has to leave at least one card in the deck after removing cards). So Vova's new deck actually contains cards x + 1, x + 2, ... n - y - 1, n - y from the original deck.Vova's new deck is considered valid iff the product of all numbers written on the cards in his new deck is divisible by k. So Vova received a deck (possibly not a valid one) and a number k, and now he wonders, how many ways are there to choose x and y so the deck he will get after removing x cards from the top and y cards from the bottom is valid?
['data structures', 'two pointers', 'binary search', 'number theory']
import math def fact(nn): p=2 df={} while nn%2==0: if 2 not in df: df[2]=0 df[2]+=1 nn/=2 p=3 s=math.sqrt(nn)+1 while p<s: while nn%p==0: if p not in df: df[p]=0 df[p]+=1 nn/=p s=math.sqrt(nn)+1 p+=2 if nn>1: df[nn]=1 return df n,k =[int(i) for i in raw_input().split(" ")] a=[int(i) for i in raw_input().split(" ")] fk=fact(k) nbf=len(fk) afacts=[0]*n sfacts=[0]*n sfacts[-1]=[0]*nbf fs=fk.keys() gg=[fk[i] for i in fs] for i in range(n): afacts[i]=[0]*nbf sfacts[i]=[0]*nbf ni=a[i] for j in range(nbf): nbfj=0 while nbfj<fk[fs[j]] and ni%fs[j]==0: ni/=fs[j] nbfj+=1 afacts[i][j]=nbfj sfacts[i][j]=sfacts[i-1][j]+nbfj #OK now we want all the sfacts[n-y]-sfacts[x]>gg x=0 y=n-1 vires=[0]*nbf res=0 while x<n: virend=sfacts[n-y-1] OK=True for i in range(nbf): if virend[i]-vires[i]<gg[i]: OK=False break while not OK and y>0: y-=1 OK=True virend=sfacts[n-y-1] for i in range(nbf): if virend[i]-vires[i]<gg[i]: OK=False break # print x,y,OK,y+1 vires=sfacts[x] if not OK: break #print y+1 res+=y+1 x+=1 y=min(y,n-x-1) print res
Python
[ "number theory" ]
1,026
1,426
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,986
f6cd855ceda6029fc7d14daf2c9bb7dc
There is an infinite sequence consisting of all positive integers in the increasing order: p = {1, 2, 3, ...}. We performed n swap operations with this sequence. A swap(a, b) is an operation of swapping the elements of the sequence on positions a and b. Your task is to find the number of inversions in the resulting sequence, i.e. the number of such index pairs (i, j), that i &lt; j and pi &gt; pj.
['implementation', 'sortings', 'data structures', 'binary search', 'trees']
from sys import stdin from itertools import repeat def main(): n = int(stdin.readline()) data = map(int, stdin.read().split(), repeat(10, 2 * n)) d = {} for i in xrange(n): a, b = data[i*2], data[i*2+1] d[a], d[b] = d.get(b, b), d.get(a, a) s = d.keys() s.sort() idx = {} for i, x in enumerate(s, 1): idx[x] = i ans = 0 b = [0] * (2 * n + 1) ans = 0 for i, x in enumerate(s): y = d[x] z = idx[y] r = 0 while z > 0: r += b[z] z = z & (z - 1) ans += i - r if y > x: ans += y - x - idx[y] + idx[x] elif y < x: ans += x - y - idx[x] + idx[y] z = idx[y] while z <= 2 * n: b[z] += 1 z += z - (z & (z - 1)) print ans main()
Python
[ "trees" ]
400
837
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
2,477
07cbcf6e1f1e7f1a6ec45241cf9ac2a9
Little John aspires to become a plumber! Today he has drawn a grid consisting of n rows and m columns, consisting of n Γ— m square cells.In each cell he will draw a pipe segment. He can only draw four types of segments numbered from 1 to 4, illustrated as follows: Each pipe segment has two ends, illustrated by the arrows in the picture above. For example, segment 1 has ends at top and left side of it.Little John considers the piping system to be leaking if there is at least one pipe segment inside the grid whose end is not connected to another pipe's end or to the border of the grid. The image below shows an example of leaking and non-leaking systems of size 1 Γ— 2. Now, you will be given the grid that has been partially filled by Little John. Each cell will either contain one of the four segments above, or be empty. Find the number of possible different non-leaking final systems after Little John finishes filling all of the empty cells with pipe segments. Print this number modulo 1000003 (106 + 3).Note that rotations or flipping of the grid are not allowed and so two configurations that are identical only when one of them has been rotated or flipped either horizontally or vertically are considered two different configurations.
['math']
n,m = map(int, raw_input().split()) mp = [] def checkrow(row): ret = 0 beg = False ok = True for j in range(m): if(mp[row][j] != '.'): if not beg and (mp[row][j] != '1' and mp[row][j] != '2'): ok = False if beg and (mp[row][j] != '3' and mp[row][j] != '4'): ok = False beg = not beg if ok: ret += 1 beg = True ok = True for j in range(m): if(mp[row][j] != '.'): if not beg and (mp[row][j] != '1' and mp[row][j] != '2'): ok = False if beg and (mp[row][j] != '3' and mp[row][j] != '4'): ok = False beg = not beg if ok: ret += 1 return ret def checkcol(col): ret = 0 beg = False ok = True for i in range(n): if(mp[i][col] != '.'): if not beg and (mp[i][col] != '1' and mp[i][col] != '4'): ok = False if beg and (mp[i][col] != '2' and mp[i][col] != '3'): ok = False beg = not beg if ok: ret += 1 beg = True ok = True for i in range(n): if(mp[i][col] != '.'): if not beg and (mp[i][col] != '1' and mp[i][col] != '4'): ok = False if beg and (mp[i][col] != '2' and mp[i][col] != '3'): ok = False beg = not beg if ok: ret += 1 return ret for i in range(n): mp.append(raw_input()) ans = 1 MOD = 1000003 for i in range(n): ans *= checkrow(i) ans %= MOD for i in range(m): ans *= checkcol(i) ans %= MOD print ans
Python
[ "math" ]
1,247
1,638
0
0
0
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,694
c01c7a6f289e6c4a7a1e2fb2492a069e
The country has n cities and n - 1 bidirectional roads, it is possible to get from every city to any other one if you move only along the roads. The cities are numbered with integers from 1 to n inclusive.All the roads are initially bad, but the government wants to improve the state of some roads. We will assume that the citizens are happy about road improvement if the path from the capital located in city x to any other city contains at most one bad road.Your task is β€” for every possible x determine the number of ways of improving the quality of some roads in order to meet the citizens' condition. As those values can be rather large, you need to print each value modulo 1 000 000 007 (109 + 7).
['dp', 'trees']
import sys MOD = 1000000007 n = int (sys.stdin.readline ()) a = [[] for i in range (n)] p = map (int, sys.stdin.readline ().split ()) for i in range (1, n): a[p[i - 1] - 1] += [i] f = [1] * n for v in range (n)[::-1]: for u in a[v]: f[v] = (f[v] * (f[u] + 1)) % MOD g = [1] * n for v in range (n): lo = [1] for u in a[v]: lo += [lo[-1] * (f[u] + 1) % MOD] hi = [1] for u in a[v][::-1]: hi += [hi[-1] * (f[u] + 1) % MOD] for i, u in enumerate (a[v]): g[u] = (g[u] * (g[v] * lo[i] * hi[len (a[v]) - 1 - i] + 1)) % MOD sys.stdout.write (' '.join (map (str, [(f[i] * g[i]) % MOD for i in range (n)])))
Python
[ "trees" ]
703
621
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,121
47129977694cb371c7647cfd0db63d29
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. There are n cities and n-1 two-way roads connecting pairs of cities in the kingdom. From any city, you can reach any other city by walking through some roads. The cities are numbered from 1 to n, and the city 1 is the capital of the kingdom. So, the kingdom has a tree structure.As the queen, Linova plans to choose exactly k cities developing industry, while the other cities will develop tourism. The capital also can be either industrial or tourism city.A meeting is held in the capital once a year. To attend the meeting, each industry city sends an envoy. All envoys will follow the shortest path from the departure city to the capital (which is unique).Traveling in tourism cities is pleasant. For each envoy, his happiness is equal to the number of tourism cities on his path.In order to be a queen loved by people, Linova wants to choose k cities which can maximize the sum of happinesses of all envoys. Can you calculate the maximum sum for her?
['dp', 'greedy', 'sortings', 'dfs and similar', 'trees']
def main(): from sys import stdin from sys import stdout input = stdin.readline print = stdout.write def dfs(town_ix, deep=0, parent=0): deeps[town_ix] = deep if len(kingdom_structure[town_ix]) == 1 and kingdom_structure[town_ix][0] == parent: return 1 for road_to in kingdom_structure[town_ix]: if road_to != parent: quantity_child[town_ix] += dfs(road_to, deep + 1, town_ix) return quantity_child[town_ix] + 1 n, k = list(map(int, input().split())) kingdom_structure = [[] for _ in range(n)] memo = [list(map(int, input().split())) for _ in range(n - 1)] deeps = [0] * n quantity_child = [0] * n for i in range(n - 1): v = memo[i][0] - 1 u = memo[i][1] - 1 kingdom_structure[v].append(u) kingdom_structure[u].append(v) dfs(0) towns_profit = sorted([deeps[i] - quantity_child[i] for i in range(n)], reverse=True) print(f'{sum(towns_profit[:k])}\n') if __name__ == '__main__': from sys import setrecursionlimit import threading setrecursionlimit(2097152) threading.stack_size(134217728) main_thread = threading.Thread(target=main) main_thread.start() main_thread.join()
Python
[ "graphs", "trees" ]
1,229
1,261
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,980
37447ade3cad88e06c1f407576e4a041
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).Your task is to count the number of segments where Horace can "see an elephant".
['string suffix structures', 'strings']
#!/usr/bin/env python2 from __future__ import print_function import os from io import BytesIO range = xrange input = BytesIO(os.read(0, os.fstat(0).st_size)).readline print = lambda x: os.write(1, str(x)) def pi(s): p = [0] * len(s) for i in range(1, len(s) - 1): g = p[i - 1] while g and (s[i + 1] - s[i] != s[g + 1] - s[g]): g = p[g - 1] p[i] = g + int(s[i + 1] - s[i] == s[g + 1] - s[g]) return p def match(s, pat): res = 0 p = pi(pat + [float('inf')] + s) for i in range(len(p) - len(s), len(p)): if p[i] == len(pat) - 1: res += 1 return res def main(): n, w = map(float, input().split()) a = [float(i) for i in input().split()] b = [float(i) for i in input().split()] print(match(a, b)) if __name__ == '__main__': main()
Python
[ "strings" ]
1,093
845
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
674
d02e8f3499c4eca03e0ae9c23f80dc95
Vasya is pressing the keys on the keyboard reluctantly, squeezing out his ideas on the classical epos depicted in Homer's Odysseus... How can he explain to his literature teacher that he isn't going to become a writer? In fact, he is going to become a programmer. So, he would take great pleasure in writing a program, but none β€” in writing a composition.As Vasya was fishing for a sentence in the dark pond of his imagination, he suddenly wondered: what is the least number of times he should push a key to shift the cursor from one position to another one?Let's describe his question more formally: to type a text, Vasya is using the text editor. He has already written n lines, the i-th line contains ai characters (including spaces). If some line contains k characters, then this line overall contains (k + 1) positions where the cursor can stand: before some character or after all characters (at the end of the line). Thus, the cursor's position is determined by a pair of integers (r, c), where r is the number of the line and c is the cursor's position in the line (the positions are indexed starting from one from the beginning of the line).Vasya doesn't use the mouse to move the cursor. He uses keys "Up", "Down", "Right" and "Left". When he pushes each of these keys, the cursor shifts in the needed direction. Let's assume that before the corresponding key is pressed, the cursor was located in the position (r, c), then Vasya pushed key: "Up": if the cursor was located in the first line (r = 1), then it does not move. Otherwise, it moves to the previous line (with number r - 1), to the same position. At that, if the previous line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r - 1; "Down": if the cursor was located in the last line (r = n), then it does not move. Otherwise, it moves to the next line (with number r + 1), to the same position. At that, if the next line was short, that is, the cursor couldn't occupy position c there, the cursor moves to the last position of the line with number r + 1; "Right": if the cursor can move to the right in this line (c &lt; ar + 1), then it moves to the right (to position c + 1). Otherwise, it is located at the end of the line and doesn't move anywhere when Vasya presses the "Right" key; "Left": if the cursor can move to the left in this line (c &gt; 1), then it moves to the left (to position c - 1). Otherwise, it is located at the beginning of the line and doesn't move anywhere when Vasya presses the "Left" key.You've got the number of lines in the text file and the number of characters, written in each line of this file. Find the least number of times Vasya should push the keys, described above, to shift the cursor from position (r1, c1) to position (r2, c2).
['greedy', 'graphs', 'shortest paths', 'data structures', 'dfs and similar']
from collections import deque def read(line): return [int(c) for c in line.split()] def solve(n, lines, r1, c1, r2, c2): queue = deque([(r1, c1, 0)]) visited = {} while queue: r, c, cost = queue.pop() if (r, c) not in visited: visited[(r, c)] = cost else: if cost < visited[(r, c)]: visited[(r, c)] = cost else: continue # left or right to the target column if c2 <= lines[r - 1] + 1: queue.appendleft((r, c2, cost + abs(c - c2))) # right to last column last_pos = lines[r - 1] + 1 if c < last_pos: queue.appendleft((r, last_pos, cost + abs(c - last_pos))) # up if r - 1 >= 1: last_pos_prev = lines[r - 2] + 1 if last_pos_prev >= c: queue.appendleft((r - 1, c, cost + 1)) else: queue.appendleft((r - 1, last_pos_prev, cost + 1)) # down if r + 1 <= n: last_pos_next = lines[r] + 1 if last_pos_next >= c: queue.appendleft((r + 1, c, cost + 1)) else: queue.appendleft((r + 1, last_pos_next, cost + 1)) return visited[(r2, c2)] def main(): with open('input.txt') as f: test = f.readlines() n, = read(test[0]) lines = read(test[1]) r1, c1, r2, c2 = read(test[2]) ans = solve(n, lines, r1, c1, r2, c2) with open('output.txt', 'w') as f: f.write(str(ans)) if __name__ == "__main__": main()
Python
[ "graphs" ]
2,820
1,586
0
0
1
0
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
2,946
1f6be4f0f7d3f9858b498aae1357c2c3
Aleksey has n friends. He is also on a vacation right now, so he has m days to play this new viral cooperative game! But since it's cooperative, Aleksey will need one teammate in each of these m days.On each of these days some friends will be available for playing, and all others will not. On each day Aleksey must choose one of his available friends to offer him playing the game (and they, of course, always agree). However, if any of them happens to be chosen strictly more than \left\lceil\dfrac{m}{2}\right\rceil times, then all other friends are offended. Of course, Aleksey doesn't want to offend anyone.Help him to choose teammates so that nobody is chosen strictly more than \left\lceil\dfrac{m}{2}\right\rceil times.
['combinatorics', 'flows', 'greedy', 'implementation']
import sys input = sys.stdin.readline tests = int(input()) for tt in range(tests): n, m = list(map(int, input().split())) cnt = [0] * (n+1) ans = [0] * (m) friend = [[] for i in range(m)] for i in range(m): friend[i] = list(map(int, input().split())) for i in range(m): if len(friend[i]) == 2: take = friend[i][1] cnt[take] += 1 ans[i] = take for i in range(m): if ans[i] == 0: dmin, take = 200003, -1 for j in friend[i][1::]: if cnt[j] < dmin: dmin, take = cnt[j], j cnt[take] += 1 ans[i] = take good = True for x in ans: if cnt[x] > (m+1)//2: good = False break if good: print("YES") print(" ".join(map(str, ans))) else: print("NO")
Python
[ "math", "graphs" ]
757
932
0
0
1
1
0
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,835
b4cd60296083ee2ae8a560209433dcaf
This problem differs from the previous one only in the absence of the constraint on the equal length of all numbers a_1, a_2, \dots, a_n.A team of SIS students is going to make a trip on a submarine. Their target is an ancient treasure in a sunken ship lying on the bottom of the Great Rybinsk sea. Unfortunately, the students don't know the coordinates of the ship, so they asked Meshanya (who is a hereditary mage) to help them. He agreed to help them, but only if they solve his problem.Let's denote a function that alternates digits of two numbers f(a_1 a_2 \dots a_{p - 1} a_p, b_1 b_2 \dots b_{q - 1} b_q), where a_1 \dots a_p and b_1 \dots b_q are digits of two integers written in the decimal notation without leading zeros.In other words, the function f(x, y) alternately shuffles the digits of the numbers x and y by writing them from the lowest digits to the older ones, starting with the number y. The result of the function is also built from right to left (that is, from the lower digits to the older ones). If the digits of one of the arguments have ended, then the remaining digits of the other argument are written out. Familiarize with examples and formal definitions of the function below.For example: f(1111, 2222) = 12121212 f(7777, 888) = 7787878 f(33, 44444) = 4443434 f(555, 6) = 5556 f(111, 2222) = 2121212Formally, if p \ge q then f(a_1 \dots a_p, b_1 \dots b_q) = a_1 a_2 \dots a_{p - q + 1} b_1 a_{p - q + 2} b_2 \dots a_{p - 1} b_{q - 1} a_p b_q; if p &lt; q then f(a_1 \dots a_p, b_1 \dots b_q) = b_1 b_2 \dots b_{q - p} a_1 b_{q - p + 1} a_2 \dots a_{p - 1} b_{q - 1} a_p b_q. Mishanya gives you an array consisting of n integers a_i, your task is to help students to calculate \sum_{i = 1}^{n}\sum_{j = 1}^{n} f(a_i, a_j) modulo 998\,244\,353.
['combinatorics', 'number theory', 'math']
import sys from collections import deque IS_LOCAL = False def read_one(dtype=int): return dtype(input()) def read_multiple(f, dtype=int): return f(map(dtype, input().split())) def swap(x, y): return y, x def main(): n = 3 a = [12, 3, 45] if not IS_LOCAL: n = read_one() a = read_multiple(list) d = 998_244_353 s, k = 0, 1 tot = n z = 0 while tot > 0: zeroed = 0 for i in range(n): if a[i] == 0: continue t = a[i] % 10 a[i] //= 10 if a[i] == 0: zeroed += 1 s = (s + t * z * k * 2) % d s = (s + t * tot * k * k * 11) % d k *= 10 z += k * zeroed tot -= zeroed print(s) if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == 'True': IS_LOCAL = True main()
Python
[ "math", "number theory" ]
1,933
905
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,939
d11b56fe172110d5dfafddf880e48f18
You are given an angle \text{ang}. The Jury asks You to find such regular n-gon (regular polygon with n vertices) that it has three vertices a, b and c (they can be non-consecutive) with \angle{abc} = \text{ang} or report that there is no such n-gon. If there are several answers, print the minimal one. It is guarantied that if answer exists then it doesn't exceed 998244353.
['geometry', 'brute force']
L = [-1] * 181 for i in range(3, 400): for j in range(1, i-1): if L[180*j/i] == -1 and 180*j%i==0: L[180*j/i] = i T = input() for i in range(T): ang = input() print L[ang]
Python
[ "geometry" ]
431
204
0
1
0
0
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
778
554115bec46bb436a0a1ddf8c05a2d08
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.Gildong loves this concept so much, so he wants to play with it. He has n distinct strings of equal length m. He wants to discard some of the strings (possibly none or all) and reorder the remaining strings so that the concatenation becomes a palindrome. He also wants the palindrome to be as long as possible. Please help him find one.
['greedy', 'constructive algorithms', 'implementation', 'brute force', 'strings']
x,y=map(int,input().split()) a=set() l=[] for i in range(x): l.append(input()) a.add(l[-1]) s=set() m='' for i in a: r=i[::-1] if i!=r and r in a and r not in s: s.add(i) elif r==i and len(i)>len(m): m=i s=''.join(list(s)) o=s+m+s[::-1] print(len(o)) print(o)
Python
[ "strings" ]
656
268
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,286
2fad8bea91cf6db14b34271e88ab093c
You are given a connected weighted undirected graph, consisting of n vertices and m edges.You are asked k queries about it. Each query consists of a single integer x. For each query, you select a spanning tree in the graph. Let the weights of its edges be w_1, w_2, \dots, w_{n-1}. The cost of a spanning tree is \sum \limits_{i=1}^{n-1} |w_i - x| (the sum of absolute differences between the weights and x). The answer to a query is the lowest cost of a spanning tree.The queries are given in a compressed format. The first p (1 \le p \le k) queries q_1, q_2, \dots, q_p are provided explicitly. For queries from p+1 to k, q_j = (q_{j-1} \cdot a + b) \mod c.Print the xor of answers to all queries.
['binary search', 'data structures', 'dfs and similar', 'dsu', 'graphs', 'greedy', 'math', 'sortings', 'trees']
from bisect import bisect_left from collections import defaultdict I = lambda: [int(x) for x in input().split()] class DSU: def __init__(self, N): self.p = list(range(N)) def find(self, x): if self.p[x] != x: self.p[x] = self.find(self.p[x]) return self.p[x] def union(self, x, y): self.p[self.find(x)] = self.find(y) edges = [] n, m = I() for _ in range(m): x, y, w = I() edges += [(x - 1, y - 1, w)] p, k, a, b, c = I() Q = I() for _ in range(k - p): Q += [(Q[-1] * a + b) % c] def kruskal(x): dsu, ans, W, sgn = DSU(n), [], 0, 0 E = sorted(edges, key=lambda q: abs(x - q[2])) for u, v, w in E: if dsu.find(u) == dsu.find(v): continue s = -1 + 2 * int(x <= w) dsu.union(u, v) ans += [w] W += w * s sgn += s return sorted(ans), W, sgn points = defaultdict(tuple) at, maxval = 0, 10**8 while at <= maxval: cur_weights = kruskal(at)[0] lo, hi = at, maxval while lo < hi: mid = (lo + hi + 1) // 2 if kruskal(mid)[0] == cur_weights: lo = mid else: hi = mid - 1 points[lo] = kruskal(lo) at = lo + 1 for _, _, w in edges: points[w] = kruskal(w) w, out = sorted(points), 0 for x in Q: idx = bisect_left(w, x) if idx >= len(w): idx -= 1 out ^= (points[w[idx]][1] - x*points[w[idx]][2]) print(out)
Python
[ "graphs", "math", "trees" ]
777
1,485
0
0
1
1
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
4,061
27baf9b1241c0f8e3a2037b18f39fe34
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashtag as a string consisting of lowercase English letters and exactly one symbol '#' located at the beginning of the string. The length of the hashtag is defined as the number of symbols in it without the symbol '#'.The head administrator of the page told Vasya that hashtags should go in lexicographical order (take a look at the notes section for the definition).Vasya is lazy so he doesn't want to actually change the order of hashtags in already published news. Instead, he decided to delete some suffixes (consecutive characters at the end of the string) of some of the hashtags. He is allowed to delete any number of characters, even the whole string except for the symbol '#'. Vasya wants to pick such a way to delete suffixes that the total number of deleted symbols is minimum possible. If there are several optimal solutions, he is fine with any of them.
['binary search', 'implementation', 'greedy', 'strings']
def cut_to_lexicographic(word_bigger, word_smaller): if len(word_bigger) > len(word_smaller): return word_bigger[:len(word_smaller)] for l in range(len(word_bigger)): if word_bigger[l] != word_smaller[l]: return word_smaller[:l] return word_bigger n = int(input()) array = [str(input()) for c in range(n)] b = n - 2 while b > -1: if array[b + 1] >= array[b]: b = b - 1 else: array[b] = cut_to_lexicographic(array[b], array[b+1]) print("\n".join(array))
Python
[ "strings" ]
1,180
519
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
615
43fbb05dc01b5302f19d923e45e325e7
Ostap already settled down in Rio de Janiero suburb and started to grow a tree in his garden. Recall that a tree is a connected undirected acyclic graph. Ostap's tree now has n vertices. He wants to paint some vertices of the tree black such that from any vertex u there is at least one black vertex v at distance no more than k. Distance between two vertices of the tree is the minimum possible number of edges of the path between them.As this number of ways to paint the tree can be large, Ostap wants you to compute it modulo 109 + 7. Two ways to paint the tree are considered different if there exists a vertex that is painted black in one way and is not painted in the other one.
['dp', 'trees']
import sys #sys.stdin=open("data.txt") #sys.stdout=open("data.txt","w") input=sys.stdin.readline n,k=map(int,input().split()) g=[[] for _ in range(n+1)] vis=[0]*(n+1) for _ in range(n-1): u,v=map(int,input().split()) g[u].append(v) g[v].append(u) def getans(u,k): vis[u]=1 # first k -> need k # then cover exact # last k -> covers k above totalv=[0]*(2*k+1) totalv[k-1]=1 carry=1 # total when this node is black for v in g[u]: if vis[v]: continue getv=getans(v,k) carry=(carry*sum(getv))%1000000007 out2=[0]*(2*k+1) #print("before",totalv) for i in range(1,2*k+1): for j in range(2*k+1): if j+i>=2*k: out2[max(i-1,j)]+=getv[i]*totalv[j] else: out2[min(i-1,j)]+=getv[i]*totalv[j] for i in range(2*k+1): totalv[i]=out2[i]%1000000007 #print("after ",totalv,carry) totalv[2*k]+=carry #print(u,totalv) return totalv if k==0: print(1) else: temp=getans(1,k) print(sum(temp[k:])%1000000007)
Python
[ "trees" ]
684
1,124
0
0
0
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,764
5c33d1f970bcc2ffaea61d5407b877b2
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings.String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way that they form a. For example, string "for" is contained as a substring in strings "codeforces", "for" and "therefore", but is not contained as a substring in strings "four", "fofo" and "rof".
['sortings', 'strings']
n = input() ll = [] for i in xrange(n): ll.append(raw_input()) ll.sort(key=lambda x: len(x)) check = False for i in xrange(n): for j in xrange(i+1, n): if ll[i] not in ll[j]: check = True break if not check: print "YES" print "\n".join(ll) else: print "NO"
Python
[ "strings" ]
541
312
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
972
f4c743af8e8a1f90b74a27ca9bbc8b7b
Let's assume that v(n) is the largest prime number, that does not exceed n; u(n) is the smallest prime number strictly greater than n. Find .
['number theory', 'math']
T = int( input() ) #for every prime x #(b-a)/ab #1/a-1/b MAX = 33000 bePrime = [0] * MAX; primNum = [] for j in range(2, MAX): if bePrime[j] == 0: primNum.append( j ) i = j while i < MAX: bePrime[i] = 1 i = i + j def isPrime( a ): for j in primNum: if j >= a: return True if a % j == 0: return False return True def gcd( a, b ): if b == 0: return a return gcd( b, a % b ); while T > 0: num = 0; n = int( input() ) m = n while isPrime(m) == False: m -= 1 while isPrime(n + 1) == False: n += 1 num += 1 a = n - 1 b = 2 * ( n+1 ) a = a * (n+1) * m - num * b b = b * (n+1) * m g = gcd( a, b) a //= g b //= g print( '{0}/{1}'.format( a, b ) ) T -= 1;
Python
[ "math", "number theory" ]
143
857
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
3,438
a365055f2d1c836fd50aed9090db1072
You are given a connected undirected graph with n vertices and m edges. Vertices of the graph are numbered by integers from 1 to n and edges of the graph are numbered by integers from 1 to m.Your task is to answer q queries, each consisting of two integers l and r. The answer to each query is the smallest non-negative integer k such that the following condition holds: For all pairs of integers (a, b) such that l\le a\le b\le r, vertices a and b are reachable from one another using only the first k edges (that is, edges 1, 2, \ldots, k).
['binary search', 'data structures', 'dfs and similar', 'divide and conquer', 'dsu', 'greedy', 'trees']
import os import sys from io import BytesIO, IOBase import sys import threading threading.stack_size(250 * 1024 * 1024) sys.setrecursionlimit(5000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") class DisjointSetWithWeights: def __init__(self, size): self.U = [[i, 1] for i in range(size)] self.W = [10**9 for i in range(size)] def root(self, e): u = self.U[e] if u[0] != e: # r = self.U[e] = self.root(u[0]) return self.root(u[0]) return u def union(self, first, second, weight): uFirst, uSecond = self.root(first), self.root(second) if uFirst == uSecond: return False if uFirst[1] < uSecond[1]: uFirst, uSecond = uSecond, uFirst first, second = second, first if uSecond[0] != uFirst[0]: self.W[uSecond[0]] = weight uSecond[0] = uFirst[0] uFirst[1] += uSecond[1] return True def maxWeight(self, s, e): w = 0 while s != e: if self.W[s] < self.W[e]: s, w = self.U[s][0], self.W[s] else: e, w = self.U[e][0], self.W[e] return w class SparseTable: def __init__(self, A, F): self.A = A self.F = F self.buildLG() self.buildST() def buildLG(self): self.LG = [] lg, V = 0, 1 for e in range(len(self.A) + 1): if V * 2 <= e: V *= 2 lg += 1 self.LG.append(lg) def buildST(self): n = len(self.A) self.ST = [] length = 1 while length <= n: if length == 1: self.ST.append(self.A) else: self.ST.append([self.F(self.ST[-1][s], self.ST[-1][s + length//2]) for s in range(n - length + 1)]) length <<= 1 def query(self, l, r): if l == r: return self.ST[0][l] if l > r: l, r = r, l e = self.LG[r - l + 1] return self.F(self.ST[e][l], self.ST[e][r - 2**e + 1]) T = int(input()) for _ in range(T): n, m, q = map(int, input().split()) dsu = DisjointSetWithWeights(n + 1) for i in range(m): s, e = map(int, input().split()) dsu.union(s, e, i) W = [dsu.maxWeight(i, i + 1) for i in range(1, n)] ST = SparseTable(W, max) R = [] for i in range(q): a, b = map(int, input().split()) if a == b: R.append(0) else: R.append(ST.query(a - 1, b - 2) + 1) print(" ".join(str(r) for r in R))
Python
[ "graphs", "trees" ]
641
4,480
0
0
1
0
0
0
0
1
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
3,929
819aebac427c2c0f96e58bca60b81e33
The store sells n beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them.A necklace is a set of beads connected in a circle.For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemble the following necklaces (these are not all possible options): And the following necklaces cannot be assembled from beads sold in the store: The first necklace cannot be assembled because it has three beads "a" (of the two available). The second necklace cannot be assembled because it contains a bead "d", which is not sold in the store. We call a necklace k-beautiful if, when it is turned clockwise by k beads, the necklace remains unchanged. For example, here is a sequence of three turns of a necklace. As you can see, this necklace is, for example, 3-beautiful, 6-beautiful, 9-beautiful, and so on, but it is not 1-beautiful or 2-beautiful.In particular, a necklace of length 1 is k-beautiful for any integer k. A necklace that consists of beads of the same color is also beautiful for any k.You are given the integers n and k, and also the string s containing n lowercase letters of the English alphabet β€” each letter defines a bead in the store. You can buy any subset of beads and connect them in any order. Find the maximum length of a k-beautiful necklace you can assemble.
['dp', 'greedy', 'graphs', 'number theory', 'dfs and similar', 'brute force']
import math import collections t = int(input()) for _ in range(t): n,k = map(int, input().split()) s = input() ctr = collections.Counter(s) ans = 0 for i in range(1,n+1): g = math.gcd(i, k) l = i // g cnt = sum([(v//l)*l for v in ctr.values()]) if cnt >= i: ans = i print(ans)
Python
[ "graphs", "number theory" ]
1,509
348
0
0
1
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 1, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,610
046900001c7326fc8d890a22fa7267c9
Alica and Bob are playing a game.Initially they have a binary string s consisting of only characters 0 and 1.Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent characters of string s and delete them. For example, if s = 1011001 then the following moves are possible: delete s_1 and s_2: \textbf{10}11001 \rightarrow 11001; delete s_2 and s_3: 1\textbf{01}1001 \rightarrow 11001; delete s_4 and s_5: 101\textbf{10}01 \rightarrow 10101; delete s_6 and s_7: 10110\textbf{01} \rightarrow 10110. If a player can't make any move, they lose. Both players play optimally. You have to determine if Alice can win.
['games']
for _ in range(int(input())): s = input() s=list(s) if min(s.count('0'),s.count('1'))%2==0: print("NET") else: print("DA")
Python
[ "games" ]
850
155
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,464
0f7ceecdffe11f45d0c1d618ef3c6469
You are given one integer number n. Find three distinct integers a, b, c such that 2 \le a, b, c and a \cdot b \cdot c = n or say that it is impossible to do it.If there are several answers, you can print any.You have to answer t independent test cases.
['number theory', 'greedy', 'math']
def factors(n): factor = [] for i in range(2, int(n**0.5)+1): if n % i == 0: factor.append(i) return factor t = int(input()) for l in range(t): n = int(input()) x = 0 factor = factors(n) lenfactor = len(factor) for i in range(lenfactor): for j in range(i+1, lenfactor): k = n/(factor[i]*factor[j]) if k%1 == 0 and k != factor[i] and k != factor[j]: print('YES') print(str(factor[i]) + ' ' + str(factor[j]) + ' ' + str(int(k)) ) x = 1 break if x == 1: break if x == 0: print('NO')
Python
[ "math", "number theory" ]
283
663
0
0
0
1
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
857
cc23f07b6539abbded7e120793bef6a7
Furlo and Rublo play a game. The table has n piles of coins lying on it, the i-th pile has ai coins. Furlo and Rublo move in turns, Furlo moves first. In one move you are allowed to: choose some pile, let's denote the current number of coins in it as x; choose some integer y (0 ≀ y &lt; x; x1 / 4 ≀ y ≀ x1 / 2) and decrease the number of coins in this pile to y. In other words, after the described move the pile will have y coins left. The player who can't make a move, loses. Your task is to find out, who wins in the given game if both Furlo and Rublo play optimally well.
['games']
from bisect import * input() r = [3, 15, 81, 6723, 15 ** 4, 15 ** 8] v = [0, 1, 2, 0, 3, 1, 2] print ['Rublo', 'Furlo'][reduce(lambda x, y : x ^ y, map(lambda x : v[bisect_left(r, x)], map(int, raw_input().split()))) > 0]
Python
[ "games" ]
578
221
1
0
0
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,084
aba6e64e040952b88e7dcb95e4472e56
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers.For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbitrary integer greater than 1, such that it divides at least one element in each pair. WCD may not exist for some lists.For example, if the list looks like [(12, 15), (25, 18), (10, 24)], then their WCD can be equal to 2, 3, 5 or 6 (each of these numbers is strictly greater than 1 and divides at least one number in each pair).You're currently pursuing your PhD degree under Ildar's mentorship, and that's why this problem was delegated to you. Your task is to calculate WCD efficiently.
['number theory', 'greedy', 'brute force']
def gcd(a,b): if b==0:return a return gcd(b,a%b) n=int(raw_input()) d = 0 prime_lim = 0 nums = [] for i in xrange(n): a,b=map(int,raw_input().split()) nums.append((a,b)) d = gcd(d, a*b) prime_lim=max(prime_lim,a,b) k = int(prime_lim**0.5)+5 k=min(k,d-1) for i in xrange(2,k+1): if d%i==0: d = i break if d > prime_lim: for a,b in nums: if a*b == d: d = a break if d==1:d=-1 print d
Python
[ "number theory" ]
864
463
0
0
0
0
1
0
0
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 1, "probabilities": 0, "strings": 0, "trees": 0 }
4,581
7cf9bb97385ee3a5b5e28f66eab163d0
You are given two strings s and t both of length n and both consisting of lowercase Latin letters.In one move, you can choose any length len from 1 to n and perform the following operation: Choose any contiguous substring of the string s of length len and reverse it; at the same time choose any contiguous substring of the string t of length len and reverse it as well. Note that during one move you reverse exactly one substring of the string s and exactly one substring of the string t.Also note that borders of substrings you reverse in s and in t can be different, the only restriction is that you reverse the substrings of equal length. For example, if len=3 and n=5, you can reverse s[1 \dots 3] and t[3 \dots 5], s[2 \dots 4] and t[2 \dots 4], but not s[1 \dots 3] and t[1 \dots 2].Your task is to say if it is possible to make strings s and t equal after some (possibly, empty) sequence of moves.You have to answer q independent test cases.
['constructive algorithms', 'sortings', 'strings']
for _ in range(int(input())): n = int(input()) s1, s2 = input(), input() a1, a2 = [0]*26, [0]*26 for v in map(ord, s1): a1[v-97] += 1 for v in map(ord, s2): a2[v-97] += 1 if a1 != a2: print('NO') continue if max(a1) > 1: print('YES') continue inv1 = sum(c1 > c2 for i, c1 in enumerate(s1) for c2 in s1[i+1:]) inv2 = sum(c1 > c2 for i, c1 in enumerate(s2) for c2 in s2[i+1:]) print('YES' if inv1 % 2 == inv2 % 2 else 'NO')
Python
[ "strings" ]
1,102
515
0
0
0
0
0
0
1
0
{ "games": 0, "geometry": 0, "graphs": 0, "math": 0, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
4,676