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
6bd41042c6a442765cd93c73d55f6189
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l \dots r]. The characters of each string are numbered from 1.We can perform several operations on the strings we consider. Each operation is to choose a substring of our string and replace it with another string. There are two possible types of operations: replace 011 with 110, or replace 110 with 011. For example, if we apply exactly one operation to the string 110011110, it can be transformed into 011011110, 110110110, or 110011011.Binary string a is considered reachable from binary string b if there exists a sequence s_1, s_2, ..., s_k such that s_1 = a, s_k = b, and for every i \in [1, k - 1], s_i can be transformed into s_{i + 1} using exactly one operation. Note that k can be equal to 1, i. e., every string is reachable from itself.You are given a string t and q queries to it. Each query consists of three integers l_1, l_2 and len. To answer each query, you have to determine whether t[l_1 \dots l_1 + len - 1] is reachable from t[l_2 \dots l_2 + len - 1].
['data structures', 'hashing', 'strings']
import sys input = sys.stdin.readline n=int(input()) t=input().strip() q=int(input()) ZEROS=[0]*n ZERO_ONE=[] ONECOUNT=[0]*n ind=0 count=0 for i in range(n): ZEROS[i]=ind if t[i]=="0": ind+=1 ONECOUNT[i]=count%2 ZERO_ONE.append(count%2) count=0 else: count+=1 ONECOUNT[i]=count ZEROS.append(ind) S=ZERO_ONE LEN=len(S) p=2 import random mod=random.randint(10**8,10**9)*2+1 mod2=random.randint(10**8,10**9)*2+1 mod3=random.randint(10**8,10**9)*2+1 mod4=random.randint(10**8,10**9)*2+1 TABLE=[0] TABLE2=[0] TABLE3=[0] TABLE4=[0] for i in range(LEN): TABLE.append(p*TABLE[-1]%mod+S[i]%mod) # テーブルを埋める TABLE2.append(p*TABLE2[-1]%mod2+S[i]%mod2) # テーブルを埋める TABLE3.append(p*TABLE3[-1]%mod3+S[i]%mod2) # テーブルを埋める TABLE4.append(p*TABLE4[-1]%mod4+S[i]%mod4) # テーブルを埋める def hash_ij(i,j): # [i,j)のハッシュ値を求める return (TABLE[j]-TABLE[i]*pow(p,j-i,mod))%mod def hash_ij2(i,j): # [i,j)のハッシュ値を求める return (TABLE2[j]-TABLE2[i]*pow(p,j-i,mod2))%mod2 def hash_ij3(i,j): # [i,j)のハッシュ値を求める return (TABLE3[j]-TABLE3[i]*pow(p,j-i,mod3))%mod3 def hash_ij4(i,j): # [i,j)のハッシュ値を求める return (TABLE4[j]-TABLE4[i]*pow(p,j-i,mod4))%mod4 def zcount(l,LEN): return ZEROS[l+LEN]-ZEROS[l] def first_check(l,LEN): if t[l]=="0": return 0 else: return (ZERO_ONE[ZEROS[l]]-ONECOUNT[l]+1)%2 def equalcheck(l1,l2,LEN): f1,f2=ZEROS[l1]+1,ZEROS[l2]+1 if l1+LEN-1=="0": la1=ZEROS[l1+LEN] else: la1=ZEROS[l1+LEN]-1 if l2+LEN-1=="0": la2=ZEROS[l2+LEN] else: la2=ZEROS[l2+LEN]-1 if hash_ij(f1,la1+1)==hash_ij(f2,la2+1) and hash_ij2(f1,la1+1)==hash_ij2(f2,la2+1) and hash_ij3(f1,la1+1)==hash_ij3(f2,la2+1) and hash_ij4(f1,la1+1)==hash_ij4(f2,la2+1): return "Yes" else: return "No" for queries in range(q): l1,l2,LEN=map(int,input().split()) l1-=1 l2-=1 #print(l1,l2,LEN) if zcount(l1,LEN)!=zcount(l2,LEN): print("No") continue if zcount(l1,LEN)==0: print("Yes") continue if first_check(l1,LEN)!=first_check(l2,LEN): print("No") continue if zcount(l1,LEN)==1: print("Yes") continue print(equalcheck(l1,l2,LEN))
Python
[ "strings" ]
1,435
2,317
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,254
878c2e57a396187ccef51d0f941386cf
This is the easy version of the problem. The only difference is that in this version k = 0.There is an array a_1, a_2, \ldots, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfect square.Moreover, it is allowed to do at most k such operations before the division: choose a number in the array and change its value to any positive integer. But in this version k = 0, so it is not important.What is the minimum number of continuous segments you should use if you will make changes optimally?
['data structures', 'dp', 'greedy', 'math', 'number theory', 'two pointers']
import os import sys from collections import defaultdict,deque from io import BytesIO, IOBase # MOD = 998244353 # nmax = (2*(10**5))+2 # fact = [1] * (nmax+1) # for i in range(2, nmax+1): # fact[i] = fact[i-1] * i % MOD # inv = [1] * (nmax+1) # for i in range(2, nmax+1): # inv[i] = pow(fact[i], MOD-2, MOD) # def C(n, m): # return fact[n] * inv[m] % MOD * inv[n-m] % MOD if 0 <= m <= n else 0 factor_dict = {1: 1} primes = [] for p in range(2, 10**7): if p*p > 10**7: break prime = True for i in range(2, p): if i*i > p: break if p % i==0: prime = False break if prime: primes.append(p) def factor(n): if n in factor_dict: return factor_dict[n] n2 = n for p in primes: if p*p > n: break while n % (p*p)==0: n = n//(p*p) factor_dict[n2] = n return n for i in range(2, 10**4): factor(i) from collections import Counter from functools import lru_cache from collections import deque def main(): # import bisect,math # class SortedList(): # BUCKET_RATIO = 50 # REBUILD_RATIO = 170 # def __init__(self,buckets): # buckets = list(buckets) # buckets = sorted(buckets) # self._build(buckets) # def __iter__(self): # for i in self.buckets: # for j in i: yield j # def __reversed__(self): # for i in reversed(self.buckets): # for j in reversed(i): yield j # def __len__(self): # return self.size # def __contains__(self,x): # if self.size == 0: return False # bucket = self._find_bucket(x) # i = bisect.bisect_left(bucket,x) # return i != len(bucket) and bucket[i] == x # def __getitem__(self,x): # if x < 0: x += self.size # if x < 0: raise IndexError # for i in self.buckets: # if x < len(i): return i[x] # x -= len(i) # raise IndexError # def _build(self,buckets=None): # if buckets is None: buckets = list(self) # self.size = len(buckets) # bucket_size = int(math.ceil(math.sqrt(self.size/self.BUCKET_RATIO))) # tmp = [] # for i in range(bucket_size): # t = buckets[(self.size*i)//bucket_size:(self.size*(i+1))//bucket_size] # tmp.append(t) # self.buckets = tmp # def _find_bucket(self,x): # for i in self.buckets: # if x <= i[-1]: # return i # return i # def add(self,x): # # O(√N) # if self.size == 0: # self.buckets = [[x]] # self.size = 1 # return True # bucket = self._find_bucket(x) # bisect.insort(bucket,x) # self.size += 1 # if len(bucket) > len(self.buckets) * self.REBUILD_RATIO: # self._build() # return True # def remove(self,x): # # O(√N) # if self.size == 0: return False # bucket = self._find_bucket(x) # i = bisect.bisect_left(bucket,x) # if i == len(bucket) or bucket[i] != x: return False # bucket.pop(i) # self.size -= 1 # if len(bucket) == 0: self._build() # return True # def lt(self,x): # # less than < x # for i in reversed(self.buckets): # if i[0] < x: # return i[bisect.bisect_left(i,x) - 1] # def le(self,x): # # less than or equal to <= x # for i in reversed(self.buckets): # if i[0] <= x: # return i[bisect.bisect_right(i,x) - 1] # def gt(self,x): # # greater than > x # for i in self.buckets: # if i[-1] > x: # return i[bisect.bisect_right(i,x)] # def ge(self,x): # # greater than or equal to >= x # for i in self.buckets: # if i[-1] >= x: # return i[bisect.bisect_left(i,x)] # def index(self,x): # # the number of elements < x # ans = 0 # for i in self.buckets: # if i[-1] >= x: # return ans + bisect.bisect_left(i,x) # ans += len(i) # return ans # def index_right(self,x): # # the number of elements < x # ans = 0 # for i in self.buckets: # if i[-1] > x: # return ans + bisect.bisect_right(i,x) # ans += len(i) # return ans from math import sqrt for _ in range(int(input())): n,k=map(int,input().split()) arr=list(map(int,input().split())) seen=set([]) ans=0 for el in arr: if factor(el) in seen: ans+=1 seen=set([]) seen.add(factor(el)) else : seen.add(factor(el)) if seen!=set([]): ans+=1 print(ans) #---------------------------------------------------------------------------------------- # 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
[ "math", "number theory" ]
665
7,514
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,247
58b9ec7ff9718ceae1aa3d4503c8cbed
There are n cities in Shaazzzland, numbered from 0 to n-1. Ghaazzzland, the immortal enemy of Shaazzzland, is ruled by AaParsa.As the head of the Ghaazzzland's intelligence agency, AaParsa is carrying out the most important spying mission in Ghaazzzland's history on Shaazzzland.AaParsa has planted m transport cannons in the cities of Shaazzzland. The i-th cannon is planted in the city a_i and is initially pointing at city b_i.It is guaranteed that each of the n cities has at least one transport cannon planted inside it, and that no two cannons from the same city are initially pointing at the same city (that is, all pairs (a_i, b_i) are distinct).AaParsa used very advanced technology to build the cannons, the cannons rotate every second. In other words, if the i-th cannon is pointing towards the city x at some second, it will target the city (x + 1) \mod n at the next second.As their name suggests, transport cannons are for transportation, specifically for human transport. If you use the i-th cannon to launch yourself towards the city that it's currently pointing at, you'll be airborne for c_i seconds before reaching your target destination.If you still don't get it, using the i-th cannon at the s-th second (using which is only possible if you are currently in the city a_i) will shoot you to the city (b_i + s) \mod n and you'll land in there after c_i seconds (so you'll be there in the (s + c_i)-th second). Also note the cannon that you initially launched from will rotate every second but you obviously won't change direction while you are airborne. AaParsa wants to use the cannons for travelling between Shaazzzland's cities in his grand plan, and he can start travelling at second 0. For him to fully utilize them, he needs to know the minimum number of seconds required to reach city u from city v using the cannons for every pair of cities (u, v).Note that AaParsa can stay in a city for as long as he wants.
['graphs', 'shortest paths']
import sys input = lambda: sys.stdin.readline().rstrip() def dijkstra(n, E, i0=0): D = [1 << 30] * n; D[i0] = 0; Q = set([i for i in range(n)]) while Q: d = 1 << 30 for q in Q: if D[q] < d: i = q; d = D[q] Q.remove(i) for j, w in enumerate(E[i]): jj = (j + d) % n if jj == i: continue nd = d + w if D[jj] > nd: D[jj] = nd return " ".join(map(str, D)) N, M = map(int, input().split());inf = 2 * 10 ** 9;X = [[inf] * N for _ in range(N)] for _ in range(M):a, b, c = map(int, input().split());X[a][b] = c Y = [[0] * N for _ in range(N)] for i, Yi in enumerate(Y): Xi = X[i] for j in range(N): if j and mi < Xi[j] + N - 1: mi = min(mi + 1, Xi[j]); Yi[j] = mi; continue mi = min([(Xi[j-k] + k) for k in range(N)]); Yi[j] = mi print("\n".join([dijkstra(N, Y, s) for s in range(N)]))
Python
[ "graphs" ]
2,081
952
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,306
1b8596fcbaa42fa334b782b78ad1931b
On a weekend, Qingshan suggests that she and her friend Daniel go hiking. Unfortunately, they are busy high school students, so they can only go hiking on scratch paper.A permutation p is written from left to right on the paper. First Qingshan chooses an integer index x (1\le x\le n) and tells it to Daniel. After that, Daniel chooses another integer index y (1\le y\le n, y \ne x).The game progresses turn by turn and as usual, Qingshan moves first. The rules follow: If it is Qingshan's turn, Qingshan must change x to such an index x' that 1\le x'\le n, |x'-x|=1, x'\ne y, and p_{x'}&lt;p_x at the same time. If it is Daniel's turn, Daniel must change y to such an index y' that 1\le y'\le n, |y'-y|=1, y'\ne x, and p_{y'}&gt;p_y at the same time. The person who can't make her or his move loses, and the other wins. You, as Qingshan's fan, are asked to calculate the number of possible x to make Qingshan win in the case both players play optimally.
['games', 'greedy']
n = int(input()) a = [int(i) for i in input().split()] r = [] cur = 0 i = 0 while n != i + 1: while n != i + 1 and a[i] < a[i + 1]: i += 1 cur += 1 r.append(cur + 1) cur = 1 while n != i + 1 and a[i] > a[i + 1]: i += 1 cur += 1 r.append(cur) cur = 0 t = max(r) if t % 2 == 0: print(0) exit() ans = 0 fl = False for i in range(0, len(r), 2): if (r[i] == t and r[i + 1] == t) and not fl: ans += 1 elif fl and r[i] == t or r[i+1] == t: print(0) exit() if r[i] == t or r[i+1] == t: fl = True print(ans)
Python
[ "games" ]
1,071
638
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 }
278
c46d1a87c6a6540d573c0391e845e1db
This is an interactive problem.In the Wonderful Metropolis of the Future, there is no need in subway train drivers. Due to the technological progress, they were replaced by the Artificial Intelligence (AI). Unfortunately, one day the predictions of sci-fi writers came true: the AI rebelled and now there is an uncontrollable train in the subway. It can be dangerous! Your task is to find the train and stop the AI.The subway of the Metropolis is one line (regular straight line with no self-intersections) with n stations, indexed consecutively from 1 to n. At each moment the train is at some station. You need to determine the index of this station, so that the train would be secured.To find the train, dispatcher Sarah gave you a gadget that allows you to select arbitrary numbers l and r (l \le r), and then check, whether the train is located on a station with index between l and r, inclusive. Unfortunately, recharging of the gadget takes some time (and every time you use it as soon as possible), so between two applications of the gadget the train can move to any station that is at most k stations away. Formally, if the train was at the station x when the gadget was applied, then at the next application of the gadget the train can appear at any station y such that \max(1, x - k) \leq y \leq \min(n, x + k).Note that AI is not aware that you are trying to catch the train, so it makes all moves according to its predefined plan.After an examination of the gadget you found that it is very old and can hold no more than 4500 applications, after which it will break and your mission will be considered a failure.Can you find the station with the train using no more than 4500 applications of the gadgets?
['binary search', 'probabilities', 'interactive']
# import collections, atexit, math, sys, bisect sys.setrecursionlimit(1000000) def getIntList(): return list(map(int, input().split())) try : #raise ModuleNotFoundError import numpy def dprint(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) dprint('debug mode') except ModuleNotFoundError: def dprint(*args, **kwargs): pass inId = 0 outId = 0 if inId>0: dprint('use input', inId) sys.stdin = open('input'+ str(inId) + '.txt', 'r') #标准输出重定向至文件 if outId>0: dprint('use output', outId) sys.stdout = open('stdout'+ str(outId) + '.txt', 'w') #标准输出重定向至文件 atexit.register(lambda :sys.stdout.close()) #idle 中不会执行 atexit N, K = getIntList() b1 = 1 b2 = N def spaned(): global b1 global b2 b1-=K b2+=K if b1<1: b1 = 1 if b2>N: b2 = N import random while True: while b2 - b1+1 >K*5: mid = (b2+b1)//2 print(b1,mid) r = input() if r == 'Yes': if b1== mid: sys.exit() b2 = mid elif r == 'No': b1 =mid +1 elif r =='Bad': sys.exit() spaned() t = random.randint(b1,b2) print(t,t) r = input() if r=='Yes': sys.exit() elif r== 'Bad': sys.exit() spaned()
Python
[ "probabilities" ]
1,801
1,343
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,237
7ad14848b3b9f075477fbf0c5f648c77
You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t. You can perform the following operation on s any number of times to achieve it — Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1...r], then it becomes s[r,l,l + 1 ... r - 1]. All the remaining characters of s stay in their position. For example, on rotating the substring [2,4] , string "abcde" becomes "adbce". A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Find the minimum number of operations required to convert s to t, or determine that it's impossible.
['dp', 'strings']
def num(c): return ord(c) - 97 import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) s1 = input().strip() s2 = input().strip() char1 = [0] * 26 char2 = [0] * 26 for c in s1: char1[num(c)] += 1 for c in s2: char2[num(c)] += 1 if char1 != char2: print(-1) continue dp = [[(False, 0, 0) for j in range(n+1)] for i in range(n + 1)] dp[0][0] = [True, 0,[0]*26] def upd(a, b, val, sett): if not dp[a][b][0] or val > dp[a][b][1]: dp[a][b] = (True, val, sett) for i in range(n): for j in range(n): valid, val, tab = dp[i][j] if not valid: continue top = s1[i] bot = s2[j] if top == bot: #upd(i+1, j+1, val + 1, tab) if not dp[i + 1][j + 1][0] or val + 1 > dp[i + 1][j + 1][1]: dp[i + 1][j + 1] = [True, val + 1, tab] if tab[num(top)] > 0: sett = tab[:] sett[num(top)] -= 1 #upd(i+1, j, val, sett) if not dp[i + 1][j][0] or val > dp[i + 1][j][1]: dp[i + 1][j] = [True, val, sett] sett = tab[:] sett[num(bot)] += 1 #upd(i, j + 1, val, sett) if not dp[i][j + 1][0] or val > dp[i][j + 1][1]: dp[i][j + 1] = [True, val, sett] del dp[i][j][2] poss = [dp[i][n][1] for i in range(n + 1)] print(n - max(poss))
Python
[ "strings" ]
903
1,622
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,159
48494a73273cd8d999e94ba1a9581fdf
This is the easier version of the problem. In this version, 1 \le n \le 10^5 and 0 \le a_i \le 1. You can hack this problem only if you solve and lock both problems.Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend Alice. This year, he decides to prepare n boxes of chocolate, numbered from 1 to n. Initially, the i-th box contains a_i chocolate pieces.Since Bob is a typical nice guy, he will not send Alice n empty boxes. In other words, at least one of a_1, a_2, \ldots, a_n is positive. Since Alice dislikes coprime sets, she will be happy only if there exists some integer k &gt; 1 such that the number of pieces in each box is divisible by k. Note that Alice won't mind if there exists some empty boxes. Charlie, Alice's boyfriend, also is Bob's second best friend, so he decides to help Bob by rearranging the chocolate pieces. In one second, Charlie can pick up a piece in box i and put it into either box i-1 or box i+1 (if such boxes exist). Of course, he wants to help his friend as quickly as possible. Therefore, he asks you to calculate the minimum number of seconds he would need to make Alice happy.
['number theory', 'greedy', 'math']
def count_wyn(st_p, end_p, curr_x): tmp_wyn_to_ret = 0 tmp_wyn_to_ret_1 = 0 num_1 = 0 mid_10 = 0 mid_11 = 0 mid_12 = 0 mid = False for x in range(st_p, end_p + 1): if t[x] != 0: if mid == False: num_1 += 1 if num_1 == curr_x//2: mid_10 = x mid_11 = x mid = True else: mid_12 = x break if curr_x%2 == 0: for xx in range(st_p, end_p + 1): if t[xx] == 1: tmp_wyn_to_ret += abs(mid_10 - xx) #print('DLA MID_P ZWRACAM:', tmp_wyn_to_ret, 'st_p:', st_p, 'end_p:', end_p, 'mid_10:', mid_10) #print('------------------------------------') return tmp_wyn_to_ret else: for xx in range(st_p, end_p + 1): if t[xx] == 1: tmp_wyn_to_ret += abs(xx - mid_11) tmp_wyn_to_ret_1 += abs(xx - mid_12) #print('DLA MID_P_1_2 ZWRACAM:', min(tmp_wyn_to_ret, tmp_wyn_to_ret_1), 'st_p:', st_p, 'end_p:', end_p, 'mid_11', mid_11, 'mid_12', mid_12) #print('------------------------------------') return min(tmp_wyn_to_ret, tmp_wyn_to_ret_1) n = int(input()) t = list(map(int, input().split())) t_sum = sum(t) wyn = 10**18 t_div = [] if t_sum <= 1: print('-1') exit(0) for i in range(2, int(t_sum ** .5) + 2): if t_sum % i == 0: while t_sum % i == 0: t_sum //= i t_div.append(i) if t_sum > 1: t_div.append(t_sum) for x in t_div: tmp_s = 0 tmp_wyn = 0 pocz = 0 for y in range(0, len(t), +1): tmp_s += t[y] if tmp_s == x: #print('WYWOLUJE DLA - pocz:', pocz, 'y:', y, 'x:', x) tmp_wyn += count_wyn(pocz ,y, x) pocz = y+1 tmp_s = 0 if tmp_wyn <= wyn: wyn = tmp_wyn print(wyn)
Python
[ "math", "number theory" ]
1,261
1,910
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,332
6d940cb4b54f63a7aaa82f21e4c5b994
PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For each Ball i we know the id of its most distant relative living on the same tree. If there are several such vertices, we only know the value of the one with smallest id among those.How many trees are there in the forest?
['graphs', 'dsu', 'interactive', 'dfs and similar', 'trees']
import sys sys.setrecursionlimit(10000000) nBalls = int(raw_input()) edge = [None] + map(int, raw_input().split()) group = [0] * (nBalls + 1) def dfs(ball): if not group[ball]: group[ball] = groupNum dfs(edge[ball]) groupNum = 0 for ball in xrange(1, nBalls + 1): if not group[ball]: if group[edge[ball]]: group[ball] = group[edge[ball]] else: groupNum += 1 dfs(ball) print groupNum
Python
[ "graphs", "trees" ]
536
461
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,960
b663dadb1033d435775bf000c2041d43
As a human, she can erase history of its entirety. As a Bai Ze (Hakutaku), she can create history out of nothingness.—Perfect Memento in Strict SenseKeine has the ability to manipulate history. The history of Gensokyo is a string s of length 1 initially. To fix the chaos caused by Yukari, she needs to do the following operations n times, for the i-th time: She chooses a non-empty substring t_{2i-1} of s. She replaces t_{2i-1} with a non-empty string, t_{2i}. Note that the lengths of strings t_{2i-1} and t_{2i} can be different.Note that if t_{2i-1} occurs more than once in s, exactly one of them will be replaced.For example, let s="marisa", t_{2i-1}="a", and t_{2i}="z". After the operation, s becomes "mzrisa" or "marisz".After n operations, Keine got the final string and an operation sequence t of length 2n. Just as Keine thinks she has finished, Yukari appears again and shuffles the order of t. Worse still, Keine forgets the initial history. Help Keine find the initial history of Gensokyo!Recall that a substring is a sequence of consecutive characters of the string. For example, for string "abc" its substrings are: "ab", "c", "bc" and some others. But the following strings are not its substring: "ac", "cba", "acb".HacksYou cannot make hacks in this problem.
['constructive algorithms', 'greedy', 'strings']
from __future__ import print_function from collections import defaultdict import os,sys,io import random #from io import BytesIO, IOBase input = lambda: sys.stdin.readline().rstrip("\r\n") def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def di(): return defaultdict(int) def dl(): return defaultdict(list) def ceil(x,y): if x%y==0: return x//y else: return x//y+1 def powerMod(x,y,p): res = 1 x %= p while y > 0: if y&1: res = (res*x)%p y = y>>1 x = (x*x)%p return res def gcd(x, y): while y: x, y = y, x % y return x def isPrime(n) : # Check Prime Number or not if (n <= 1) : return False if (n <= 3) : return True 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 def read(): sys.stdin = open('tests.txt', 'r') sys.stdout = open('result.txt', 'w') def main(): for _ in range(ii()): n = ii() ocurrence = di() #dict = defaultdict(str) for i in range(2*n): s = input() for j in range(len(s)): ocurrence[(s[j])] = ocurrence[(s[j])] + 1 final = input() for k in range(len(final)): ocurrence[(final[k])] = ocurrence[(final[k])] + 1 res = -1 for x in ocurrence: if ocurrence[x] != 0 and ocurrence[x] % 2 == 1: res = x break print(res) #read() main()
Python
[ "strings" ]
1,399
1,898
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,879
b37bbf1fe9ac5144cfa230633ccbdd79
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: 10010 and 01111 are similar (they have the same character in position 4); 10010 and 11111 are similar; 111 and 111 are similar; 0110 and 1001 are not similar. You are given an integer n and a binary string s consisting of 2n-1 characters. Let's denote s[l..r] as the contiguous substring of s starting with l-th character and ending with r-th character (in other words, s[l..r] = s_l s_{l + 1} s_{l + 2} \dots s_r).You have to construct a binary string w of length n which is similar to all of the following strings: s[1..n], s[2..n+1], s[3..n+2], ..., s[n..2n-1].
['constructive algorithms', 'strings']
t = int(input()) for _ in range(t): n, s = int(input()), input() print(*[s[i] for i in range(0,len(s),2)], sep='')
Python
[ "strings" ]
916
134
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,083
a3a7515219ebb0154218ee3520e20d75
Mike has n strings s1, s2, ..., sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string "coolmike", in one move he can transform it into the string "oolmikec".Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?
['dp', 'brute force', 'strings']
def rotate(s): n = len(s) return s[1:] + s[0] n = int(input()) a = [input() for _ in range(n)] s = a[0] n = len(s) min_cost = float('inf') for _ in range(n): s = rotate(s) cost = 0 for i in a: found = False for _ in range(n): if i == s: found = True break cost += 1 i = rotate(i) if not found: cost = -float('inf') min_cost = min(min_cost, cost) if min_cost < 0: min_cost = -1 print(min_cost)
Python
[ "strings" ]
405
529
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 }
624
ba27ac62b84705d80fa580567ab64c3b
Diamond Miner is a game that is similar to Gold Miner, but there are n miners instead of 1 in this game.The mining area can be described as a plane. The n miners can be regarded as n points on the y-axis. There are n diamond mines in the mining area. We can regard them as n points on the x-axis. For some reason, no miners or diamond mines can be at the origin (point (0, 0)). Every miner should mine exactly one diamond mine. Every miner has a hook, which can be used to mine a diamond mine. If a miner at the point (a,b) uses his hook to mine a diamond mine at the point (c,d), he will spend \sqrt{(a-c)^2+(b-d)^2} energy to mine it (the distance between these points). The miners can't move or help each other.The object of this game is to minimize the sum of the energy that miners spend. Can you find this minimum?
['geometry', 'greedy', 'math', 'sortings']
mas = list(map(int, input().split())) t = mas[0] for j in range(t): mas = list(map(int, input().split())) n = mas[0] lst1 = [0 for i in range(n)] lst2 = [0 for i in range(n)] i1 = 0 i2 = 0 for i in range(2 * n): mas = list(map(int, input().split())) if (mas[0] == 0): lst1[i1] = mas[1] ** 2 i1 += 1 else: lst2[i2] = mas[0] ** 2 i2 += 1 lst1.sort() lst2.sort() s = 0 for i in range(n): s += (lst1[i] + lst2[i]) ** 0.5 print(s)
Python
[ "math", "geometry" ]
880
581
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,975
d51aa18439e7afffa11ad181064c0450
Bertown is under siege! The attackers have blocked all the ways out and their cannon is bombarding the city. Fortunately, Berland intelligence managed to intercept the enemies' shooting plan. Let's introduce the Cartesian system of coordinates, the origin of which coincides with the cannon's position, the Ox axis is directed rightwards in the city's direction, the Oy axis is directed upwards (to the sky). The cannon will make n more shots. The cannon balls' initial speeds are the same in all the shots and are equal to V, so that every shot is characterized by only one number alphai which represents the angle at which the cannon fires. Due to the cannon's technical peculiarities this angle does not exceed 45 angles (π / 4). We disregard the cannon sizes and consider the firing made from the point (0, 0).The balls fly according to the known physical laws of a body thrown towards the horizon at an angle: vx(t) = V·cos(alpha) vy(t) = V·sin(alpha) – g·t x(t) = V·cos(alpha)·t y(t) = V·sin(alpha)·t – g·t2 / 2Think of the acceleration of gravity g as equal to 9.8.Bertown defends m walls. The i-th wall is represented as a vertical segment (xi, 0) - (xi, yi). When a ball hits a wall, it gets stuck in it and doesn't fly on. If a ball doesn't hit any wall it falls on the ground (y = 0) and stops. If the ball exactly hits the point (xi, yi), it is considered stuck. Your task is to find for each ball the coordinates of the point where it will be located in the end.
['data structures', 'sortings', 'geometry']
import sys from array import array # noqa: F401 from math import pi, sin, cos from bisect import bisect_left def input(): return sys.stdin.buffer.readline().decode('utf-8') n, v = map(int, input().split()) v = float(v) alpha = [float(input()) for _ in range(n)] m = int(input()) wall = sorted(tuple(map(float, input().split())) for _ in range(m)) + [(1e9, 1e9)] max_angle = pi / 4 eps = 1e-9 a = [0.0] * m + [max_angle + eps] for i in range(m): ng_angle, ok_angle = 0.0, max_angle + eps for _ in range(50): mid_angle = (ok_angle + ng_angle) / 2 t = wall[i][0] / (v * cos(mid_angle)) if (v * sin(mid_angle) * t - 9.8 * t**2 / 2) - eps <= wall[i][1]: ng_angle = mid_angle else: ok_angle = mid_angle a[i] = max(a[i], ng_angle) a[i + 1] = max(a[i], a[i + 1]) ans = [''] * n for i in range(n): wi = bisect_left(a, alpha[i]) ok, ng = 0.0, 1e7 sin_a = sin(alpha[i]) for _ in range(50): t = (ok + ng) / 2 if v * sin_a * t - 9.8 * t**2 / 2 >= 0.0: ok = t else: ng = t x = v * cos(alpha[i]) * ok if x < wall[wi][0]: ans[i] = f'{x:.8f} {0:.8f}' else: ok, ng = 0.0, 1e7 cos_a = cos(alpha[i]) for _ in range(50): t = (ok + ng) / 2 if v * cos_a * t <= wall[wi][0]: ok = t else: ng = t y = v * sin_a * ok - 9.8 * ok**2 / 2 ans[i] = f'{wall[wi][0]:.8f} {y:.8f}' print('\n'.join(ans))
Python
[ "geometry" ]
1,479
1,552
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,400
ced70b400694fa16929d4b0bce3da294
Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i \cdot a_j where a_1, \dots, a_n is some sequence of positive integers.Of course, the girl decided to take it to school with her. But while she was having lunch, hooligan Grisha erased numbers on the main diagonal and threw away the array a_1, \dots, a_n. Help Sasha restore the array!
['number theory', 'math']
I=input I() a=[*map(int,I().split())] a[0]=a[1]*a[2]/int(I().split()[2]) print(*(int(y/a[0]**.5)for y in a))
Python
[ "math", "number theory" ]
477
108
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,036
abdf06347e6db23932ef07020f49aa52
Dreamoon has a string s and a pattern string p. He first removes exactly x characters from s obtaining string s' as a result. Then he calculates that is defined as the maximal number of non-overlapping substrings equal to p that can be found in s'. He wants to make this number as big as possible.More formally, let's define as maximum value of over all s' that can be obtained by removing exactly x characters from s. Dreamoon wants to know for all x from 0 to |s| where |s| denotes the length of string s.
['dp', 'strings']
s, p = input(), input() n, m = len(s) + 1, len(p) d = [[0] * n for t in range(n)] for x in range(1, n): i, j = x, m while i and j: j -= s[i - 1] == p[j - 1] i -= 1 if not j: for y in range(i + 1): d[x][y + x - i - m] = d[i][y] + 1 for y in range(x): d[x][y] = max(d[x][y], d[x - 1][y]) print(*d[-1])
Python
[ "strings" ]
511
340
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,592
adf024899fb2a684427463733358566a
There is an integer n without zeros in its decimal representation. Alice and Bob are playing a game with this integer. Alice starts first. They play the game in turns.On her turn, Alice must swap any two digits of the integer that are on different positions. Bob on his turn always removes the last digit of the integer. The game ends when there is only one digit left.You have to find the smallest integer Alice can get in the end, if she plays optimally.
['constructive algorithms', 'games', 'math', 'strings']
for _ in range(int(input())): n = list(map(int, ' '.join(input()).split())) if len(n) > 2: print(min(n)) else: print(n[-1])
Python
[ "math", "strings", "games" ]
462
138
1
0
0
1
0
0
1
0
{ "games": 1, "geometry": 0, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 1, "trees": 0 }
1,669
0cc73612bcfcd3be142064e2da9e92e3
Treeland consists of n cities and n-1 roads. Each road is bidirectional and connects two distinct cities. From any city you can get to any other city by roads. Yes, you are right — the country's topology is an undirected tree.There are some private road companies in Treeland. The government decided to sell roads to the companies. Each road will belong to one company and a company can own multiple roads.The government is afraid to look unfair. They think that people in a city can consider them unfair if there is one company which owns two or more roads entering the city. The government wants to make such privatization that the number of such cities doesn't exceed k and the number of companies taking part in the privatization is minimal.Choose the number of companies r such that it is possible to assign each road to one company in such a way that the number of cities that have two or more roads of one company is at most k. In other words, if for a city all the roads belong to the different companies then the city is good. Your task is to find the minimal r that there is such assignment to companies from 1 to r that the number of cities which are not good doesn't exceed k. The picture illustrates the first example (n=6, k=2). The answer contains r=2 companies. Numbers on the edges denote edge indices. Edge colors mean companies: red corresponds to the first company, blue corresponds to the second company. The gray vertex (number 3) is not good. The number of such vertices (just one) doesn't exceed k=2. It is impossible to have at most k=2 not good cities in case of one company.
['greedy', 'graphs', 'constructive algorithms', 'binary search', 'dfs and similar', 'trees']
# will you survive without fast IO? # will not stripping save you some time? from collections import deque n, k = map(int, raw_input().split()) g = [[] for i in xrange(n + 1)] par = [0] * (n + 1) deg = [0] * (n + 1) edges = [] idx = 0 for i in xrange(n - 1): u, v = map(int, raw_input().split()) g[u].append(v) g[v].append(u) edges.append((u, v, idx)) idx += 1 deg[u] += 1 deg[v] += 1 deglist = [i for i in xrange(1, n + 1)] deglist.sort(key = lambda x : deg[x], reverse = True) C = deg[deglist[k]] def solve(u): global par, n, C vis = [0] * (n + 1) color = [0] * (n + 1) ans = [0] * (n - 1) vis[u] = 1 col = 0 q = deque([(u, col)]) color[u] = col while q: u, col = q.popleft() for v in g[u]: if vis[v] == 1: continue col += 1 if (col > C): col -= C par[v] = u vis[v] = 1 q.append((v, col)) color[v] = col for u, v, idx in edges: if u != par[v]: u, v = v, u ans[idx] = color[v] return ans ans = solve(1) print C print ' '.join(map(str, ans))
Python
[ "graphs", "trees" ]
1,689
1,170
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,369
739f51381ed125770e61194b9bc8adb0
Vittorio has three favorite toys: a teddy bear, an owl, and a raccoon. Each of them has a name. Vittorio takes several sheets of paper and writes a letter on each side of every sheet so that it is possible to spell any of the three names by arranging some of the sheets in a row (sheets can be reordered and flipped as needed). The three names do not have to be spelled at the same time, it is sufficient that it is possible to spell each of them using all the available sheets (and the same sheet can be used to spell different names).Find the minimum number of sheets required. In addition, produce a list of sheets with minimum cardinality which can be used to spell the three names (if there are multiple answers, print any).
['greedy', 'strings']
class SegmentTree: def __init__(self, init_val, segfunc, ide_ele): n = len(init_val) self.segfunc = segfunc self.ide_ele = ide_ele self.num = 1 << (n - 1).bit_length() self.tree = [ide_ele] * 2 * self.num self.size = n for i in range(n): self.tree[self.num + i] = init_val[i] for i in range(self.num - 1, 0, -1): self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1]) def update(self, k, x): k += self.num self.tree[k] = self.segfunc(self.tree[k],x) while k > 1: k >>= 1 self.tree[k] = self.segfunc(self.tree[2*k], self.tree[2*k+1]) def query(self, l, r): if r==self.size: r = self.num res = self.ide_ele l += self.num r += self.num right = [] while l < r: if l & 1: res = self.segfunc(res, self.tree[l]) l += 1 if r & 1: right.append(self.tree[r-1]) l >>= 1 r >>= 1 for e in right[::-1]: res = self.segfunc(res,e) return res import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import log,gcd input = lambda :sys.stdin.readline().rstrip() mi = lambda :map(int,input().split()) li = lambda :list(mi()) for _ in range(1): #S = [random.choice("ABC") for i in range(10)] #T = [random.choice("ABC") for i in range(10)] #U = [random.choice("ABC") for i in range(10)] #S = "".join(S) #T = "".join(T) #U = "".join(U) S = input() T = input() U = input() max_match = 0 for q in range(26): ch = chr(q+ord("A")) X = [i for i in range(len(S)) if S[i]==ch] Y = [i for i in range(len(T)) if T[i]==ch] Z = [i for i in range(len(U)) if U[i]==ch] x,y,z = len(X),len(Y),len(Z) """ 0 <= k <= min(x,y) maximize k+min(z,x+y-2*k) """ check = -1 k = -1 for tt in range(min(x,y)+1): tmp = tt + min(x+y-2*tt,z) if tmp > check: k = tt check = tmp max_match += check check = -1 EM = -1 for t in range(max_match+1): tmp = min(t,len(S))+min(t,len(T))+min(t,len(U))-2*t if tmp > check: check = tmp EM = t ST = [] TU = [] US = [] res = [] use_S = [False] * len(S) use_T = [False] * len(T) use_U = [False] * len(U) for q in range(26): ch = chr(q+ord("A")) X = [i for i in range(len(S)) if S[i]==ch] Y = [i for i in range(len(T)) if T[i]==ch] Z = [i for i in range(len(U)) if U[i]==ch] x,y,z = len(X),len(Y),len(Z) """ 0 <= k <= min(x,y) maximize k+min(z,x+y-2*k) """ check = -1 k = -1 for tt in range(min(x,y)+1): tmp = tt + min(x+y-2*tt,z) if tmp > check: k = tt check = tmp def calc(tt): if tt < 0 or tt > min(x,y): return -1 return tt + min(x+y-2*tt,z) assert calc(k-1) <= calc(k) assert calc(k) >= calc(k+1) for _ in range(k): a,b = X.pop(),Y.pop() if EM: EM -= 1 ST.append(ch) use_S[a] = True use_T[b] = True while Z and X and EM: a,c = X.pop(),Z.pop() US.append(ch) use_S[a] = use_U[c] = True EM -= 1 while Z and Y and EM: b,c = Y.pop(),Z.pop() TU.append(ch) use_T[b] = use_U[c] = True EM -= 1 ans = [] X = [S[i] for i in range(len(S)) if not use_S[i]] Y = [T[i] for i in range(len(T)) if not use_T[i]] Z = [U[i] for i in range(len(U)) if not use_U[i]] while X and TU: ans.append(X.pop()+TU.pop()) while Y and US: ans.append(Y.pop()+US.pop()) while Z and ST: ans.append(Z.pop()+ST.pop()) #print(ST,TU,US,X,Y,Z) for ch in ST: X.append(ch) Y.append(ch) for ch in TU: Y.append(ch) Z.append(ch) for ch in US: Z.append(ch) X.append(ch) if len(X) > len(Y): X,Y = Y,X if len(Y) > len(Z): Y,Z = Z,Y ALL = [X,Y,Z] while True: p = [0,1,2] p.sort(key=lambda i:len(ALL[i])) if not ALL[p[1]]: break a = ALL[p[2]].pop() b = ALL[p[1]].pop() ans.append(a+b) for a in ALL[p[2]]: ans.append(a+"A") print(len(ans)) print(*ans,sep="\n") def check(S,res): n = len(res) for i in range(2**n): cnt = [0] * 26 for j in range(n): p = res[j] if i>>j & 1: cnt[ord(p[0])-ord("A")] += 1 else: cnt[ord(p[1])-ord("A")] += 1 for j in range(26): ch = chr(ord("A")+j) if cnt[j] < S.count(ch): break else: return True return False def checker(S,T,U,res): for p in [S,T,U]: if not check(p,res): return False return True #assert checker(S,T,U,ans)
Python
[ "strings" ]
729
5,720
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 }
866
9bd393bb8752a69016c5312750e8b507
It is a simplified version of problem F2. The difference between them is the constraints (F1: k \le 2, F2: k \le 10).You are given an integer n. Find the minimum integer x such that x \ge n and the number x is k-beautiful.A number is called k-beautiful if its decimal representation having no leading zeroes contains no more than k different digits. E.g. if k = 2, the numbers 3434443, 55550, 777 and 21 are k-beautiful whereas the numbers 120, 445435 and 998244353 are not.
['binary search', 'bitmasks', 'brute force', 'constructive algorithms', 'dfs and similar', 'greedy']
import os, sys from io import BytesIO, IOBase from bisect import * 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, 8192)) 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, 8192)) 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") class dict(dict): def __missing__(self, key): return 0 sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") inp = lambda dtype: dtype(input().strip()) inp_d = lambda dtype: [dtype(x) for x in input().split()] inp_2d = lambda dtype, n: [inp(dtype) for _ in range(n)] inp_2ds = lambda dtype, n: [inp_d(dtype) for _ in range(n)] inp_enu = lambda dtype: [(i, x) for i, x in enumerate(inp_d(dtype))] inp_enus = lambda dtype, n: [[i] + [inp_d(dtype)] for i in range(n)] ceil1 = lambda a, b: (a + b - 1) // b get_bit = lambda x, i: (x >> i) & 1 for _ in range(inp(int)): n, k = inp_d(int) n1 = str(n) ans, ln = float('inf'), len(n1) digs = [] for i in n1: if len(digs) == k - 1: break if i not in digs: digs.append(i) for i in range(10): cur, lst, flag = [], [-1, 0], 0 if str(i) not in digs: digs.append(str(i)) flag = 1 digs.sort() for j in n1: ix = bisect_left(digs, j) if ix < len(digs): cur.append(digs[ix]) if j < digs[ix]: cur.extend([digs[0]] * (ln - len(cur))) if ix != len(digs) - 1: lst = [len(cur) - 1, ix + 1] else: if lst[0] == -1: cur = ['9'] * 10 break cur[lst[0]] = digs[lst[1]] cur = cur[:lst[0] + 1] + [digs[0]] * (ln - lst[0] - 1) break if len(cur) == len(n1): break if flag: digs.remove(str(i)) ans = min(ans, int(''.join(cur))) print(ans)
Python
[ "graphs" ]
582
3,449
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,642
d9e9c53b391eb44f469cc92fdcf3ea0a
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some number of consecutive characters of the string. For example, string "aba" has substrings "" (empty substring), "a", "b", "a", "ab", "ba", "aba".If string s has at least two equal substrings then Kerem will change characters at some positions to some other lowercase English letters. Changing characters is a very tiring job, so Kerem want to perform as few changes as possible.Your task is to find the minimum number of changes needed to make all the substrings of the given string distinct, or determine that it is impossible.
['constructive algorithms', 'implementation', 'strings']
n = int(input()) s = list(input()) f = set(s) if n > 26 : print('-1') exit(0) else: print(n - len(f))
Python
[ "strings" ]
842
120
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,658
3ca37d1209b487a383b56ba4b7c1e872
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. The parent of a vertex v (different from root) is the previous to v vertex on the shortest path from the root to the vertex v. Children of the vertex v are all vertices for which v is the parent.You are given a rooted tree with n vertices. The vertex 1 is the root. Initially, all vertices are healthy.Each second you do two operations, the spreading operation and, after that, the injection operation: Spreading: for each vertex v, if at least one child of v is infected, you can spread the disease by infecting at most one other child of v of your choice. Injection: you can choose any healthy vertex and infect it. This process repeats each second until the whole tree is infected. You need to find the minimal number of seconds needed to infect the whole tree.
['binary search', 'greedy', 'sortings', 'trees']
import sys input=sys.stdin.readline def get_rid_of_zeros(): while len(number_of_children) and number_of_children[-1]<=0: number_of_children.pop() for _ in range(int(input())): n=int(input()) x=list(map(int,input().split())) number_of_children=[0]*n for i in x: number_of_children[i-1]+=1 number_of_children.append(1) number_of_children.sort(reverse=True) get_rid_of_zeros() ans=0 temp=1 for i in range(len(number_of_children)-1,-1,-1): if number_of_children[i]>0: number_of_children[i]-=temp temp+=1 ans+=1 number_of_children.sort(reverse=True) get_rid_of_zeros() while len(number_of_children) and number_of_children[0]>0: ans+=1 last=0 temp=number_of_children[0] for i in range(len(number_of_children)): if number_of_children[i]==temp: last=i number_of_children[i]-=1 number_of_children[last] -= 1 get_rid_of_zeros() print(ans) # 1 # 17 # 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2
Python
[ "trees" ]
923
1,127
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 }
272
ee9ba877dee1a2843e885a18823cbff0
One day, liouzhou_101 got a chat record of Freda and Rainbow. Out of curiosity, he wanted to know which sentences were said by Freda, and which were said by Rainbow. According to his experience, he thought that Freda always said "lala." at the end of her sentences, while Rainbow always said "miao." at the beginning of his sentences. For each sentence in the chat record, help liouzhou_101 find whose sentence it is.
['implementation', 'strings']
I=lambda:map(int, raw_input().split()) n=input() for _ in xrange(n): s=raw_input() if s.startswith('miao.') and s.endswith('lala.'): print 'OMG>.< I don\'t know!' elif s.startswith('miao.'): print 'Rainbow\'s' elif s.endswith('lala.'): print 'Freda\'s' else: print 'OMG>.< I don\'t know!'
Python
[ "strings" ]
418
309
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 }
303
c9c3fabde66856667c338d71e17f6418
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination.Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet.Determine for which values d Natasha can make the Martians happy.Natasha can use only her banknotes. Martians don't give her change.
['number theory']
from fractions import gcd n,k = [int(x) for x in raw_input().split()] a = [int(x)%k for x in raw_input().split()] g = reduce(gcd, a) if g == 0: print "1\n0" else: g = gcd(g,k) print k/g print " ".join([str(i) for i in range(0,k,g)])
Python
[ "number theory" ]
1,011
249
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 }
1,457
81ad3bb3d58a33016221d60a601790d4
Julia is conducting an experiment in her lab. She placed several luminescent bacterial colonies in a horizontal testtube. Different types of bacteria can be distinguished by the color of light they emit. Julia marks types of bacteria with small Latin letters "a", ..., "z".The testtube is divided into n consecutive regions. Each region is occupied by a single colony of a certain bacteria type at any given moment. Hence, the population of the testtube at any moment can be described by a string of n Latin characters.Sometimes a colony can decide to conquer another colony in one of the adjacent regions. When that happens, the attacked colony is immediately eliminated and replaced by a colony of the same type as the attacking colony, while the attacking colony keeps its type. Note that a colony can only attack its neighbours within the boundaries of the testtube. At any moment, at most one attack can take place.For example, consider a testtube with population "babb". There are six options for an attack that may happen next: the first colony attacks the second colony (1 → 2), the resulting population is "bbbb"; 2 → 1, the result is "aabb"; 2 → 3, the result is "baab"; 3 → 2, the result is "bbbb" (note that the result is the same as the first option); 3 → 4 or 4 → 3, the population does not change.The pattern of attacks is rather unpredictable. Julia is now wondering how many different configurations of bacteria in the testtube she can obtain after a sequence of attacks takes place (it is possible that no attacks will happen at all). Since this number can be large, find it modulo 109 + 7.
['dp', 'combinatorics', 'string suffix structures', 'brute force']
from sys import stdin, stdout rr = lambda: stdin.readline().strip() MOD = 10**9 + 7 from string import ascii_lowercase as alpha from itertools import groupby N = int(rr()) S = rr() A = [] for k,v in groupby(S): A.append(k) G = len(A) last = {c: -1 for c in alpha} prev = [0]*G for i, u in enumerate(A): prev[i] = last[u] last[u] = i dp = [+(prev[i] == -1) for i in xrange(G)] dps = [0] for x in dp: dps.append((dps[-1] + x)%MOD) for i in xrange(N - 1): for j in xrange(G): dp[j] = (dp[j] + dps[j] - dps[prev[j] + 1]) % MOD for j in xrange(G): dps[j + 1] = (dps[j] + dp[j]) % MOD print reduce(lambda x,y: (x+y)%MOD, dp)
Python
[ "math", "strings" ]
1,608
663
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 }
2,130
776706f09cd446bc144a2591e424e437
You are given a convex polygon. Count, please, the number of triangles that contain a given point in the plane and their vertices are the vertices of the polygon. It is guaranteed, that the point doesn't lie on the sides and the diagonals of the polygon.
['two pointers', 'geometry']
import sys import gc gc.disable() rl = sys.stdin.readline n = int(rl()) p = [complex(float(x),float(y)) for x,y in map(str.split,map(rl,[-1]*n))] pi = [c.conjugate() for c in p] fn = [0.5*x*(x-1) for x in xrange(0,n+1)] fnn = fn[::-1] for jj in xrange(int(rl())): a = complex(*map(float,rl().split())) pp = map(a.__rsub__,p) pc = map(a.conjugate().__rsub__,pi) i = 1 ri = 0 b = pp[0] try: for j,c in enumerate(pc): while (b*c).imag<0: ri += fn[j-i] b=pp[i] i+=1 for j,c in enumerate(pc): while (b*c).imag<0: ri += fnn[i-j] b=pp[i] i+=1 except: print n*(n-1)*(n-2)/6-int(ri) else: print 0
Python
[ "geometry" ]
254
797
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 }
3,785
9366e1626b33b4f4e49cf35200c0448f
Valera has array a, consisting of n integers a0, a1, ..., an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.
['implementation', 'number theory', 'math']
m = int(input()) listValue = input().split() x = input().rstrip('\n') values = [int(v) for v in listValue] reverse_x = list(x) reverse_int = [int(s) for s in reverse_x] reverse_list = [0] * m sum_list = 0 for i in range(m): if reverse_x[i] == '1': reverse_list[i] = max(reverse_list[i - 1] + values[i], sum_list) else: reverse_list[i] = reverse_list[i - 1] sum_list += values[i] print(reverse_list[-1])
Python
[ "number theory", "math" ]
486
433
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,191
dced53eba154855fa0f203178574990c
There is a square of size 10^6 \times 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices.You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square.Now you are wondering how many pieces this square divides into after drawing all segments. Write a program calculating the number of pieces of the square.
['data structures', 'geometry', 'implementation', 'sortings']
from __future__ import division, print_function _interactive = False def main(): MAX = 1000000 h, v = input_as_list() hs = input_as_matrix(h, 3) vs = input_as_matrix(v, 3) hs += [(0, 0, MAX), (MAX, 0, MAX)] vs += [(0, 0, MAX), (MAX, 0, MAX)] # Event types VST, H, VEN = (0, 1, 2) events = [] for y, l, r in hs: events += [(y, H, (l, r))] for x, l, r in vs: events += [(l, VST, x)] events += [(r, VEN, x)] events.sort() debug_print(events) st = SegmentTree([0]*MAX, func=lambda x, y: x+y) newv = SortedList() ans = 0 for y, t, d in events: if t == VST: newv.add(d) elif t == H: l, r = d cnt = st.query(l, r+1) ans += max(0, cnt-1) if l == 0: pos = newv.bisect_right(r) for _ in range(pos): x = newv.pop(0) st[x] = 1 else: pos = newv.bisect_left(l) while len(newv) > pos: x = newv.pop() st[x] = 1 elif t == VEN: newv.discard(d) st[d] = 0 print(ans) # Constants INF = float('inf') MOD = 10**9+7 alphabets = 'abcdefghijklmnopqrstuvwxyz' # Python3 equivalent names import os, sys, itertools if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip # print-flush in interactive problems if _interactive: flush = sys.stdout.flush def printf(*args, **kwargs): print(*args, **kwargs) flush() # Debug print, only works on local machine LOCAL = "LOCAL_" in os.environ debug_print = (print) if LOCAL else (lambda *x, **y: None) # Fast IO if (not LOCAL) and (not _interactive): from io import BytesIO from atexit import register sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') # Some utility functions(Input, N-dimensional lists, ...) def input_as_list(): return [int(x) for x in input().split()] def input_with_offset(o): return [int(x)+o for x in input().split()] def input_as_matrix(n, m): return [input_as_list() for _ in range(n)] def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f() class SegmentTree: def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): """func of data[start, stop)""" start += self._size stop += self._size res_left = res_right = self._default while start < stop: if start & 1: res_left = self._func(res_left, self.data[start]) start += 1 if stop & 1: stop -= 1 res_right = self._func(self.data[stop], res_right) start >>= 1 stop >>= 1 return self._func(res_left, res_right) def __repr__(self): return "SegmentTree({0})".format(self.data) class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) main()
Python
[ "geometry" ]
474
11,597
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,866
6778eae5422b8ed026a33856998ea89a
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.The main school of the capital is located in (s_x, s_y). There are n students attending this school, the i-th of them lives in the house located in (x_i, y_i). It is possible that some students live in the same house, but no student lives in (s_x, s_y).After classes end, each student walks from the school to his house along one of the shortest paths. So the distance the i-th student goes from the school to his house is |s_x - x_i| + |s_y - y_i|.The Provision Department of Berland has decided to open a shawarma tent somewhere in the capital (at some point with integer coordinates). It is considered that the i-th student will buy a shawarma if at least one of the shortest paths from the school to the i-th student's house goes through the point where the shawarma tent is located. It is forbidden to place the shawarma tent at the point where the school is located, but the coordinates of the shawarma tent may coincide with the coordinates of the house of some student (or even multiple students).You want to find the maximum possible number of students buying shawarma and the optimal location for the tent itself.
['implementation', 'geometry', 'greedy', 'brute force']
n,x,y=map(int,input().split()) l=0 r=0 u=0 d=0 for i in range(n): x1,y1=map(int,input().split()) if x1>x: d=d+1 if x1<x: u=u+1 if y>y1: l=l+1 if y<y1: r=r+1 #print(l,r,u,d) ans=max(l,r,u,d) print(ans) if ans==l: print(x,y-1) elif ans==r: print(x,y+1) elif ans==u: print(x-1,y) elif ans==d: print(x+1,y)
Python
[ "geometry" ]
1,444
375
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 }
2,357
dd098a17343a02fa5dc0d2d6cea853c7
Let's call a string s perfectly balanced if for all possible triplets (t,u,v) such that t is a non-empty substring of s and u and v are characters present in s, the difference between the frequencies of u and v in t is not more than 1.For example, the strings "aba" and "abc" are perfectly balanced but "abb" is not because for the triplet ("bb",'a','b'), the condition is not satisfied.You are given a string s consisting of lowercase English letters only. Your task is to determine whether s is perfectly balanced or not.A string b is called a substring of another string a if b can be obtained by deleting some characters (possibly 0) from the start and some characters (possibly 0) from the end of a.
['brute force', 'greedy', 'strings']
# cook your dish here #!/usr/bin/env python from bisect import bisect_left import os from math import ceil, factorial, fmod,pi,sqrt from pickle import FALSE from re import T from select import select import sys from collections import Counter from io import BytesIO, IOBase, StringIO def modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 # Loop to find the value # until the expo is not zero while (expo): # Multiply p with q # if expo is odd if (expo & 1): p = (p * q) % mod q = (q * q) % mod # Reduce the value of # expo by 2 expo >>= 1 return p def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm def read_arr(): return [int(x) for x in input().split()] def bin_search(num, arr): start = 0 end = len(arr)-1 while start <= end: mid=(start+end)//2 if arr[mid] == num: return mid elif arr[mid] > num: end= mid-1 else: start = mid + 1 return -1 def factors(n) : # Note that this loop runs till square root i = 1 ans=[] while i <= sqrt(n): if (n % i == 0) : # If divisors are equal, print only one if (n / i == i) : ans.append(i) else : # Otherwise print both ans.append(i) ans.append(int(n/i)) i = i + 1 return ans def is_palindrome(n): for j in range(len(n)//2): if n[j]!=n[len(n)-j-1]: return False return True def fine(arr): pres = [] string = "" for j in arr: for k in j: string += k j = 0 while j < len(string): if string[j] not in pres: pres.append(string[j]) while string[j]==pres[-1]: j += 1 if j == len(string): break else: return False return True def main(): for i in range(int(input())): string = [x for x in input()] sets =set(string) ans="YES" for j in range(len(string)-len(sets)+1): pres = set() for k in range(j,j+len(sets)): pres.add(string[k]) if pres!=sets: ans="NO" break print(ans) # 1 0 0 0 1 1 # zero -> 0 0 1 1 0 0 # one -> 1 1 1 0 1 1 # zero -> 0 0 0 0 0 0 # one -> 1 1 1 1 1 0 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
[ "strings" ]
818
4,736
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,219
be42e213ff43e303e475d77a9560367f
Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies. Rubik has 3 computers, on which he can play this game. All computers are located in different houses. Besides, it has turned out that each part of the game can be completed only on one of these computers. Let's number the computers with integers from 1 to 3. Rubik can perform the following actions: Complete some part of the game on some computer. Rubik spends exactly 1 hour on completing any part on any computer. Move from the 1-st computer to the 2-nd one. Rubik spends exactly 1 hour on that. Move from the 1-st computer to the 3-rd one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 1-st one. Rubik spends exactly 2 hours on that. Move from the 2-nd computer to the 3-rd one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 1-st one. Rubik spends exactly 1 hour on that. Move from the 3-rd computer to the 2-nd one. Rubik spends exactly 2 hours on that. Help Rubik to find the minimum number of hours he will need to complete all parts of the game. Initially Rubik can be located at the computer he considers necessary.
['dfs and similar', 'greedy']
n = int(input()) c = list(map(int, input().split())) d = dict() d[1] = [] d[2] = [] d[3] = [] for i in range(n): d[c[i]].append(i) done = set() mas = [] k = 0 poss = set() for i in range(n): l = list(map(int, input().split())) l = l[1:] mas.append(l) if len(l) == 0: k = c[i] poss.add((k, i)) o = 0 bigans = 1000000000 for a in poss: k = a[0] done = set() done.add(a[1] + 1) ans = 1 while len(done) != n: #o += 1 if o == 10: break while True: y = len(done) for i in d[k]: if (i + 1) in done: continue flag = True for j in mas[i]: if j not in done: flag = False if flag: done.add(i + 1) ans += 1 if y == len(done): break if len(done) == n: break k += 1 ans += 1 if k == 4: k = 1 bigans = min(bigans, ans) print(bigans)
Python
[ "graphs" ]
1,407
1,090
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 }
4,352
09d0f11bdb9eca2161dee83a335dd2b7
Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters.He wants to convert string a into string b by performing some (possibly zero) operations on a.In one move, he can either choose an index i (1 \leq i\leq n-1) and swap a_i and a_{i+1}, or choose an index i (1 \leq i \leq n-k+1) and if a_i, a_{i+1}, \ldots, a_{i+k-1} are all equal to some character c (c \neq 'z'), replace each one with the next character (c+1), that is, 'a' is replaced by 'b', 'b' is replaced by 'c' and so on. Note that he can perform any number of operations, and the operations can only be performed on string a. Help Ashish determine if it is possible to convert string a into b after performing some (possibly zero) operations on it.
['dp', 'hashing', 'greedy', 'implementation', 'strings']
import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n, k = map(int, input().split()) a = input() b = input() c1 = [0] * 26 c2 = [0] * 26 for i in range(n): c1[ord(a[i]) - 97] += 1 c2[ord(b[i]) - 97] += 1 ans = 'YES' for j in range(26): if c1[j] == c2[j]: continue elif c1[j] < c2[j]: ans = 'NO' break elif (c1[j] - c2[j]) % k != 0: ans = 'NO' break else: c1[j+1] = c1[j+1] + c1[j] - c2[j] print(ans)
Python
[ "strings" ]
898
853
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,744
08679e44ee5d3c3287230befddf7eced
You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.For every i (1 \leq i \leq n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly n swap operations, each of them either c_i \leftrightarrow a_i or c_i \leftrightarrow b_i (i iterates over all integers between 1 and n, inclusive).For example, if a is "code", b is "true", and c is "help", you can make c equal to "crue" taking the 1-st and the 4-th letters from a and the others from b. In this way a becomes "hodp" and b becomes "tele".Is it possible that after these swaps the string a becomes exactly the same as the string b?
['implementation', 'strings']
n = int(input()) for i in range(n): a = input() b = input() c = input() flag=1 for j in range(len(c)): if(c[j]==a[j] or c[j]==b[j]): flag =1 else: flag = 0 break if(flag==1): print("YES") else: print("NO")
Python
[ "strings" ]
988
301
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,820
1c64defd239d785acc4e1b622289624d
A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at, and the number of the desk they would like to sit at (which may be the same as their current desk). Each engineer must either remain where they sit, or move to the desired seat they indicated in the survey. No two engineers currently sit at the same desk, nor may any two engineers sit at the same desk in the new seating arrangement.How many seating arrangements can you create that meet the specified requirements? The answer may be very large, so compute it modulo 1000000007 = 109 + 7.
['graphs', 'combinatorics', 'dsu', 'dfs and similar', 'trees']
n = int(input()) m = 2 * n + 1 u = [[] for i in range(m)] v = [0] * m s = [0] * m d = 10 ** 9 + 7 y = 1 for j in range(n): a, b = map(int, input().split()) v[a] = b if a != b: s[b] += 1 u[b].append(a) for b in range(m): if not v[b]: x = 0 p = [b] while p: x += 1 a = p.pop() s[a] = -1 p += u[a] y = (x * y) % d for a in range(m): if s[a] == 0: b = v[a] while s[b] == 1: s[b] = -1 b = v[b] s[b] -= 1 for a in range(m): if s[a] == 1: y = (2 * y) % d while s[a]: s[a] = 0 a = v[a] print(y)
Python
[ "graphs", "math", "trees" ]
810
699
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 }
2,164
e7f84300e9480a94a2399fcd5f47ecec
A non-empty digit string is diverse if the number of occurrences of each character in it doesn't exceed the number of distinct characters in it.For example: string "7" is diverse because 7 appears in it 1 time and the number of distinct characters in it is 1; string "77" is not diverse because 7 appears in it 2 times and the number of distinct characters in it is 1; string "1010" is diverse because both 0 and 1 appear in it 2 times and the number of distinct characters in it is 2; string "6668" is not diverse because 6 appears in it 3 times and the number of distinct characters in it is 2. You are given a string s of length n, consisting of only digits 0 to 9. Find how many of its \frac{n(n+1)}{2} substrings are diverse.A string a is a substring of a string b if a can be obtained from b by deletion of several (possibly, zero or all) characters from the beginning and several (possibly, zero or all) characters from the end.Note that if the same diverse string appears in s multiple times, each occurrence should be counted independently. For example, there are two diverse substrings in "77" both equal to "7", so the answer for the string "77" is 2.
['brute force', 'implementation', 'strings']
import sys input = sys.stdin.readline print = sys.stdout.write t = int(input().strip()) def solve(n, a): s = 0 for i in range(n): ds, m = {}, 0 for j in range(i, min(n, i+100)): if a[j] in ds: ds[a[j]] = ds[a[j]]+1 else: ds[a[j]] = 1 m = max(m, ds[a[j]]) if m<=len(ds): s = s+1 return str(s) for i in range(t): n = int(input().strip()) a = list(map(int, input().strip())) print(solve(n, a)+"\n")
Python
[ "strings" ]
1,281
577
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,084
6c5cf702d85ff25cf9e7bfd16534197d
Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.The game works as follows: there is a tree of size n, rooted at node 1, where each node is initially white. Red and Blue get one turn each. Red goes first. In Red's turn, he can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree red. However, to make the game fair, Red is only allowed to color k nodes of the tree. In other words, after Red's turn, at most k of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation any number of times: Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon. Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let w be the number of white nodes, r be the number of red nodes, and b be the number of blue nodes. The score of the game is w \cdot (r - b).Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?
['data structures', 'dfs and similar', 'games', 'graphs', 'greedy', 'math', 'sortings', 'trees']
import sys input = sys.stdin.buffer.readline n, k = [*map(int, input().split())] d = [[] for i in range(n)] p, h, l, v = [0]*n, [-1]*n, [0]*n, [0]*n for _ in range(n-1): a, b = [int(i)-1 for i in input().split()] d[a].append(b) d[b].append(a) q, p[0] = [0], -1 leaves = [] while q: q1 = [] for i in q: for j in d[i]: if j != p[i]: q1.append(j) p[j] = i if len(d[j]) == 1: leaves.append(j) q = q1 for i in leaves[::-1]: c, x = 0, i while x != -1 and h[x] < c: h[x] = c; c+=1; l[x]=i; x=p[x]; t = sorted(list(range(n)), key=lambda x: h[x], reverse=True) r = nb = 0 for i in t: if not v[i]: r += 1 nb += h[i]+1 v[i] = 1 x = l[i] while not v[x]: v[x] = 1; x = p[x] if r == k: break rr = max((nb-i)*(i+nb-n) for i in range(r, k+1)) rl = min((nb-k+i)*(k+nb-n+i) for i in range(max(n-nb-k+1,1))) print(rr if n-nb < k else rl)
Python
[ "graphs", "math", "trees", "games" ]
1,510
1,001
1
0
1
1
0
0
0
1
{ "games": 1, "geometry": 0, "graphs": 1, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 1 }
187
574347ab83379e5b08618d2b275b0d96
This is an interactive problem.In good old times dwarves tried to develop extrasensory abilities: Exactly n dwarves entered completely dark cave. Each dwarf received a hat — white or black. While in cave, none of the dwarves was able to see either his own hat or hats of other Dwarves. Dwarves went out of the cave to the meadow and sat at an arbitrary place one after the other. When a dwarf leaves the cave, he sees the colors of all hats of all dwarves that are seating on the meadow (i.e. left the cave before him). However, he is not able to see the color of his own hat and none of the dwarves can give him this information. The task for dwarves was to got diverged into two parts — one with dwarves with white hats and one with black hats. After many centuries, dwarves finally managed to select the right place on the meadow without error. Will you be able to repeat their success?You are asked to successively name n different integer points on the plane. After naming each new point you will be given its color — black or white. Your task is to ensure that the named points can be split by a line in such a way that all points of one color lie on the same side from the line and points of different colors lie on different sides. Moreover, no points can belong to the line. Also, you need to report any such line at the end of the process.In this problem, the interactor is adaptive — the colors of the points in the tests are not fixed beforehand and the jury program can select them arbitrarily, in particular, depending on your program output.
['constructive algorithms', 'binary search', 'geometry', 'interactive']
n=int(input()) print(1,0) c=input() n-=1 L=1 R=999999999 while n>0: M=int((L+R)/2) print(1,M) if input()==c: L=M+1 else: R=M n-=1 print(0,R,2,R-1)
Python
[ "geometry" ]
1,560
183
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,576
586341bdd33b1dc3ab8e7f9865b5f6f6
Amugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "samplease".Amugae will merge his sentence left to right (i.e. first merge the first two words, then merge the result with the third word and so on). Write a program that prints the compressed word after the merging process ends.
['hashing', 'string suffix structures', 'implementation', 'brute force', 'strings']
def kmp(s): i,j = -1,0 fail = [0]*len(s) while j < len(s): if i == -1 or s[j] == s[i]: fail[j] = i j += 1 i += 1 else: i = -1 if i == 0 else fail[i-1]+1 return fail[-1]+1 n = input() words = raw_input().split(" ") out = words[0] for word in words[1:]: com = min(len(word),len(out)) l = kmp(word+"_"+out[-com:]) out += word[l:] print out
Python
[ "strings" ]
552
452
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,812
166fbe42dd60317e85e699d9bed76957
Integer factorisation is hard. The RSA Factoring Challenge offered $100\,000 for factoring RSA-1024, a 1024-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a 1024-bit number.Since your programming language of choice might not offer facilities for handling large integers, we will provide you with a very simple calculator. To use this calculator, you can print queries on the standard output and retrieve the results from the standard input. The operations are as follows: + x y where x and y are integers between 0 and n-1. Returns (x+y) \bmod n. - x y where x and y are integers between 0 and n-1. Returns (x-y) \bmod n. * x y where x and y are integers between 0 and n-1. Returns (x \cdot y) \bmod n. / x y where x and y are integers between 0 and n-1 and y is coprime with n. Returns (x \cdot y^{-1}) \bmod n where y^{-1} is multiplicative inverse of y modulo n. If y is not coprime with n, then -1 is returned instead. sqrt x where x is integer between 0 and n-1 coprime with n. Returns y such that y^2 \bmod n = x. If there are multiple such integers, only one of them is returned. If there are none, -1 is returned instead. ^ x y where x and y are integers between 0 and n-1. Returns {x^y \bmod n}. Find the factorisation of n that is a product of between 2 and 10 distinct prime numbers, all of form 4x + 3 for some integer x.Because of technical issues, we restrict number of requests to 100.
['interactive', 'number theory', 'math']
import random import math n = int(input()) z = [n] for i in range(15): w = random.randint(1, n - 1) print('sqrt', w * w % n) v = int(input()) y = [] for x in z: y.append(math.gcd(w+v, x)) y.append(x // y[-1]) z = y z = list(set(z) - {1}) print('!', len(z), *z)
Python
[ "number theory", "math" ]
1,774
304
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,001
10f2f1df27cf61f11afb074dab01ebec
Smart Beaver recently got interested in a new word game. The point is as follows: count the number of distinct good substrings of some string s. To determine if a string is good or not the game uses rules. Overall there are n rules. Each rule is described by a group of three (p, l, r), where p is a string and l and r (l ≤ r) are integers. We’ll say that string t complies with rule (p, l, r), if the number of occurrences of string t in string p lies between l and r, inclusive. For example, string "ab", complies with rules ("ab", 1, 2) and ("aab", 0, 1), but does not comply with rules ("cd", 1, 2) and ("abab", 0, 1).A substring s[l... r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2... s|s| (|s| is a length of s) is string slsl + 1... sr.Consider a number of occurrences of string t in string p as a number of pairs of integers l, r (1 ≤ l ≤ r ≤ |p|) such that p[l... r] = t.We’ll say that string t is good if it complies with all n rules. Smart Beaver asks you to help him to write a program that can calculate the number of distinct good substrings of string s. Two substrings s[x... y] and s[z... w] are cosidered to be distinct iff s[x... y] ≠ s[z... w].
['hashing', 'strings']
def count(p, s): start = 0 c = 0 while True: try: pos = s.index(p, start) c += 1 start = pos + 1 except ValueError: return c s = input() n = int(input()) pravs = [] for i in range(n): p, l, r = input().split() l = int(l); r = int(r) pravs.append((p, l, r)) var = set() for l in range(len(s)): for r in range(l+1, len(s)+1): pods = s[l:r] for prav in pravs: if not prav[1] <= count(pods, prav[0]) <= prav[2]: break else: var.add(pods) print(len(var))
Python
[ "strings" ]
1,158
611
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,451
51c355a5b56f9b1599e7d985f0b7c04e
In Medieval times existed the tradition of burning witches at steaks together with their pets, black cats. By the end of the 15-th century the population of black cats ceased to exist. The difficulty of the situation led to creating the EIC - the Emergency Inquisitory Commission.The resolution #666 says that a white cat is considered black when and only when the perimeter of its black spots exceeds the acceptable norm. But what does the acceptable norm equal to? Every inquisitor will choose it himself depending on the situation. And your task is to find the perimeter of black spots on the cat's fur.The very same resolution says that the cat's fur is a white square with the length of 105. During the measurement of spots it is customary to put the lower left corner of the fur into the origin of axes (0;0) and the upper right one — to the point with coordinates (105;105). The cats' spots are nondegenerate triangles. The spots can intersect and overlap with each other, but it is guaranteed that each pair of the triangular spots' sides have no more than one common point.We'll regard the perimeter in this problem as the total length of the boarders where a cat's fur changes color.
['sortings', 'implementation', 'geometry']
from math import * eps=1e-14 n = input() l = [map(int,raw_input().split()) for _ in xrange(n)] res = 0 def isect(a1,b1,c1,x1,y1,x2,y2): a2,b2,c2=y1-y2,x2-x1,x1*y2-y1*x2 d = a1*b2-a2*b1 if d==0: return None, None x = -1.0*(c1*b2-c2*b1)/d y = -1.0*(c2*a1-a2*c1)/d #print x1,y1,x2,y2,x,y if min(x1,x2)-eps<=x<=max(x1,x2)+eps and min(y1,y2)-eps<=y<=max(y1,y2)+eps: return x,y return None, None def cres(xmi,xma,rx): #print rx n = 0 sx = xma-xmi for j,(x,i) in enumerate(rx): if n>0: sx-=max(0,min(x,xma)-max(xmi,rx[j-1][0])) if i: n+=1 else: n-=1 return sx def count(x,y,xx,yy,i): a1,b1,c1=y-yy,xx-x,x*yy-y*xx xmi=min(x,xx) xma=max(x,xx) ymi=min(y,yy) yma=max(y,yy) rx=[] ry=[] for j,(ax,ay,bx,by,cx,cy) in enumerate(l): if i==j: continue x1,y1=isect(a1,b1,c1,ax,ay,bx,by) x2,y2=isect(a1,b1,c1,cx,cy,bx,by) x3,y3=isect(a1,b1,c1,cx,cy,ax,ay) x = filter(lambda x: x is not None, [x1,x2,x3]) if len(x)<2: continue y = filter(lambda x: x is not None, [y1,y2,y3]) #print xmi,xma,ymi,yma,x,y rx.append((min(x),True)) rx.append((max(x),False)) ry.append((min(y),True)) ry.append((max(y),False)) rx.sort() ry.sort() return hypot(cres(xmi,xma,rx),cres(ymi,yma,ry)) for i,(ax,ay,bx,by,cx,cy) in enumerate(l): res+=count(ax,ay,bx,by,i) res+=count(cx,cy,bx,by,i) res+=count(ax,ay,cx,cy,i) print "%.7f"%res
Python
[ "geometry" ]
1,193
1,556
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,546
752c583a1773847504bf0d50b72a9dda
You are given a string t and n strings s_1, s_2, \dots, s_n. All strings consist of lowercase Latin letters.Let f(t, s) be the number of occurences of string s in string t. For example, f('\text{aaabacaa}', '\text{aa}') = 3, and f('\text{ababa}', '\text{aba}') = 2.Calculate the value of \sum\limits_{i=1}^{n} \sum\limits_{j=1}^{n} f(t, s_i + s_j), where s + t is the concatenation of strings s and t. Note that if there are two pairs i_1, j_1 and i_2, j_2 such that s_{i_1} + s_{j_1} = s_{i_2} + s_{j_2}, you should include both f(t, s_{i_1} + s_{j_1}) and f(t, s_{i_2} + s_{j_2}) in answer.
['string suffix structures', 'brute force', 'strings']
from __future__ import division, print_function from collections import deque class Node: def __init__(self, c, nxt, fail, o): self.c = c self.nxt = nxt self.fail = fail self.o = o root = Node('', {}, Node, 0) root.fail = root def new_node(par, c): node = Node(c, {}, root, 0) par.nxt[c] = node return node def go(n, c): while True: try: return n.nxt[c] except KeyError: if n != root: n = n.fail else: return root def build(ps): for i, p in enumerate(ps): n = root for c in p: try: n = n.nxt[c] except KeyError: n = new_node(n, c) n.o += 1 q = deque([root]) while q: n = q.popleft() for c, cn in n.nxt.iteritems(): q.append(cn) if n == root: cn.fail = root else: cn.fail = go(n.fail, c) cn.o += cn.fail.o def query(s, ar): n = root for i, c in enumerate(s): n = go(n, c) ar[i] += n.o def main(): s = input() ps = [input() for _ in range(int(input()))] build(ps) far = array_of(int, len(s)) query(s, far) root.nxt = {} root.o = 0 rps = [list(reversed(ss)) for ss in ps] rs = list(reversed(s)) build(rps) bar = array_of(int, len(rs)) query(rs, bar) ans = 0 for i in range(len(s)-1): ans += bar[i] * far[len(s)-2-i] print(ans) INF = float('inf') MOD = 10**9 + 7 import os, sys from atexit import register from io import BytesIO import itertools if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip if 0: debug_print = print else: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) input = lambda: sys.stdin.readline().rstrip('\r\n') debug_print = lambda *x, **y: None def input_as_list(): return list(map(int, input().split())) def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f() main()
Python
[ "strings" ]
706
2,280
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,066
eddb90c1f26d9c44544617aeff56c782
Lunar New Year is approaching, and Bob received a gift from his friend recently — a recursive sequence! He loves this sequence very much and wants to play with it.Let f_1, f_2, \ldots, f_i, \ldots be an infinite sequence of positive integers. Bob knows that for i &gt; k, f_i can be obtained by the following recursive equation:f_i = \left(f_{i - 1} ^ {b_1} \cdot f_{i - 2} ^ {b_2} \cdot \cdots \cdot f_{i - k} ^ {b_k}\right) \bmod p,which in short isf_i = \left(\prod_{j = 1}^{k} f_{i - j}^{b_j}\right) \bmod p,where p = 998\,244\,353 (a widely-used prime), b_1, b_2, \ldots, b_k are known integer constants, and x \bmod y denotes the remainder of x divided by y.Bob lost the values of f_1, f_2, \ldots, f_k, which is extremely troublesome – these are the basis of the sequence! Luckily, Bob remembers the first k - 1 elements of the sequence: f_1 = f_2 = \ldots = f_{k - 1} = 1 and the n-th element: f_n = m. Please find any possible value of f_k. If no solution exists, just tell Bob that it is impossible to recover his favorite sequence, regardless of Bob's sadness.
['number theory', 'math', 'matrices']
from __future__ import division from sys import stdin, stdout from math import sqrt, ceil pow(1, 2, 3) def write(x): stdout.write(str(x) + "\n") def mmul(a, b, p): assert len(a[0]) == len(b) n = len(a) m = len(a[0]) k = len(b[0]) res = [[0] * k for _ in xrange(n)] for r in xrange(n): for c in xrange(k): sum = 0 for i in xrange(m): sum = (sum + a[r][i] * b[i][c]) % p res[r][c] = sum return res def mpow(a, x, p): if x == 1: return a if x % 2 == 1: return mmul(mpow(a, x - 1, p), a, p) else: res = mpow(a, x // 2, p) return mmul(res, res, p) def xgcd(b, a): x0, x1, y0, y1 = 1, 0, 0, 1 while a != 0: q, b, a = b // a, a, b % a x0, x1 = x1, x0 - q * x1 y0, y1 = y1, y0 - q * y1 return b, x0, y0 def solve(a, c, m): res, x0, y0 = xgcd(a, m) if c % res != 0: return -1 a //= res c //= res m //= res res, x0, y0 = xgcd(a, m) assert res == 1 return (x0 * c) % m def shanks(alpha, beta, p): t = int(ceil(sqrt(p))) small = {beta: 0} b = beta for i in range(1, t + 1): b = (b * alpha) % p small[b] = i for i in range(0, p, t): temp = pow(alpha, i, p) if temp in small: return (i - small[temp]) % (p - 1) assert False k = int(stdin.readline()) b = map(int, stdin.readline().split()) n, m = map(int, stdin.readline().split()) p = 998244353 h_n = shanks(3, m, p) trans = [b] + [[0] * k for _ in xrange(k - 1)] for i in xrange(k - 1): trans[i + 1][i] = 1 trans = mpow(trans, n - k, p - 1) c = trans[0][0] h_k = solve(c, h_n, p - 1) if h_k == -1: print -1 else: print pow(3, h_k, p)
Python
[ "math", "number theory" ]
1,179
1,784
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,337
3b10e984d7ca6d4071fd4e743394bb60
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.
['number theory', 'math']
import itertools import StringIO def tonum(a): return int("".join(map(str, a))) def genDict(): nums = map(tonum, itertools.permutations([1,6,8,9])) d = {} for n in nums: d[n%7] = str(n) return d def solve(a, b, mod): if b == 0: return 0 for i in xrange(mod): if (a*i-b)%mod == 0: return i s = raw_input().strip() a = [s.count(chr(i + 48)) for i in xrange(10)] a[1] -= 1 a[6] -= 1 a[8] -= 1 a[9] -= 1 t, r = 1, 0 for i in xrange(10): for j in xrange(a[i]): r += i*t t = t*10%7 r = 7 - r k = solve(t, r, 7) d = genDict() output = StringIO.StringIO() output.write(d[k]) for i in xrange(9, -1, -1): output.write(chr(i+48)*a[i]) print output.getvalue()
Python
[ "math", "number theory" ]
367
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 }
4,265
ab99c564f98bc6caea26b28280858c21
You are given a colored permutation p_1, p_2, \dots, p_n. The i-th element of the permutation has color c_i.Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] \dots where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = \dots).We can also define a multiplication of permutations a and b as permutation c = a \times b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p \times p \times \dots \times p}_{k \text{ times}}.Find the minimum k &gt; 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).It can be proved that the answer always exists.
['graphs', 'number theory', 'math', 'dfs and similar', 'brute force']
import sys input = lambda: sys.stdin.readline().rstrip() from math import sqrt def primeFactor(n): ret, i, d, sq = {}, 2, 2, int(sqrt(n)) + 1 while i < 4: k = 0 while n % i == 0: n, k = n//i, k+1 ret[i], sq = k, int(sqrt(n)) + 1 i = i * 2 - 1 while i <= sq: k = 0 while n % i == 0: n, k = n//i, k+1 ret[i], sq = k, int(sqrt(n)) + 1 i, d = i + d, d ^ 6 if n > 1: ret[n] = 1 return ret def divisors(N): pf = primeFactor(N) ret = [1] for p in pf: prev = ret[:] q = 1 for i in range(1, pf[p]+1): q *= p for r in prev: ret.append(r * q) return sorted(ret) def chk(X): n = len(X) XX = X * 2 mi = 1 << 30 for d in divisors(n): if d >= mi: break for i in range(d): for j in range(i, n+i, d): if XX[j] != XX[j+d]: break else: mi = min(mi, d) return mi T = int(input()) for _ in range(T): N = int(input()) A = [int(a) - 1 for a in input().split()] C = [int(a) - 1 for a in input().split()] done = [0] * N L = [] for i in range(N): if done[i]: continue t = [C[i]] j = A[i] while j != i: t.append(C[j]) done[j] = 1 j = A[j] L.append(t) print(min([chk(a) for a in L]))
Python
[ "graphs", "number theory", "math" ]
816
1,471
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 }
2,087
12b64f77fc9dd44a7e0287ff0a716a6a
Fangy the little walrus, as all the modern walruses, loves to communicate via text messaging. One day he faced the following problem: When he sends large texts, they are split into parts each containing n characters (which is the size of one text message). Thus, whole sentences and words get split!Fangy did not like it, so he faced the task of breaking the text into minimal messages on his own so that no sentence were broken into pieces when it is sent and the number of text messages to be sent would be minimal. If two consecutive sentences are in different messages, the space between them can be ignored (Fangy does not write this space).The little walrus's text looks in the following manner: TEXT ::= SENTENCE | SENTENCE SPACE TEXTSENTENCE ::= WORD SPACE SENTENCE | WORD ENDEND ::= {'.', '?', '!'}WORD ::= LETTER | LETTER WORDLETTER ::= {'a'..'z', 'A'..'Z'}SPACE ::= ' 'SPACE stands for the symbol of a space.So, how many messages did Fangy send?
['expression parsing', 'greedy', 'strings']
n = int(raw_input()) a = map(len, (" " + raw_input()).replace('?', '.').replace('!', '.')[:-1].split('.')) res = 0 t = -1 for i in a: if i > n: print "Impossible" exit() if t + i + 1 <= n: t += i + 1 else: res += 1 t = i if t != 0: res += 1 print res
Python
[ "strings" ]
956
306
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,740
c7e4f544ec8b4972291542e66aff5df5
You are given an array of n non-negative integers a_1, a_2, \ldots, a_n. You can make the following operation: choose an integer x \geq 2 and replace each number of the array by the remainder when dividing that number by x, that is, for all 1 \leq i \leq n set a_i to a_i \bmod x.Determine if it is possible to make all the elements of the array equal by applying the operation zero or more times.
['constructive algorithms', 'math', 'number theory', 'sortings']
t=int(input()) for _ in range(t): n=int(input()) lst=list(map(int,input().split())) tempmax=max(lst) temparr = lst.copy() dct={} for i in range(n): if(temparr[i] not in dct): dct[temparr[i]]=1 else: dct[temparr[i]]+=1 if(n==1): print("YES") elif (len(dct) == 1): print("YES") elif(1 in dct): found=False for i in dct.keys(): if(i+1 in dct): print("NO") found=True break if(found==False): print("YES") else: print("YES")
Python
[ "math", "number theory" ]
439
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 }
2,931
8dcf63e0e4584df7a471c84ce3ca8fe1
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.A tree is a connected undirected graph with n-1 edges.You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], \dots, v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
['dfs and similar', 'trees', 'graphs']
from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): 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 class Graph(object): def __init__(self): self.neighbours = {} def add_node(self, node): self.neighbours[node] = [] def add_edge(self, edge): u, v = edge self.neighbours[u].append(v) self.neighbours[v].append(u) @bootstrap def dfs(self, v, parent, depth=0): parents[v] = parent depths[v] = depth visited[v] = 1 intime[v] = timer[0] timer[0] += 1 for child in self.neighbours[v]: if visited[child] == 0: yield self.dfs(child, v, depth + 1) outtime[v] = timer[0] timer[0] += 1 yield def inPath(x, y): return intime[x] <= intime[y] and outtime[x] >= outtime[y] g = Graph() n, q = map(int, input().split()) for i in range(n): g.add_node(i + 1) for i in range(n - 1): x, y = map(int, input().split()) g.add_edge((x, y)) visited, intime, outtime = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1) timer = [0] parents, depths = {}, {} g.dfs(1, -1) for i in range(q): lis = list(map(int, input().split()))[1:] deep = lis[0] for j in lis: if depths[deep] < depths[j]: deep = j for j in range(len(lis)): if lis[j] == deep: continue if parents[lis[j]]!=-1: lis[j] = parents[lis[j]] ok = True for j in lis: ok = ok & inPath(j, deep) print("YES") if ok else print("NO") # region fastio # Credits # # template credits to cheran-senthil's github Repo 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
Python
[ "graphs", "trees" ]
551
4,851
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 }
356
296552dc2df23b3920baef7d47d0a591
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning.Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message?The cost of sending the message is the sum of the costs of sending every word in it.
['dsu', 'implementation', 'greedy']
n,k,m=map(int,input().split()) L=input().split() A=list(map(int,input().split())) for i in range(k): inp=list(map(int,input().split())) X=[] ind=1 for i in range(2,inp[0]+1): if A[inp[i]-1]<A[inp[ind]-1]: ind=i #print(ind) for i in range(1,inp[0]+1): A[inp[i]-1]=A[inp[ind]-1] #print(A) dic=dict() for i in range(n): dic[L[i]]=A[i] mes=input().split() out=0 for i in mes: out+=dic[i] print(out)
Python
[ "graphs" ]
567
467
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 }
4,929
a1631f068c8da218243a9ab0aced4f16
Little penguin Polo has got a tree — a non-directed connected acyclic graph, containing n nodes and n - 1 edges. We will consider the tree nodes numbered by integers from 1 to n.Today Polo wonders, how to find the number of pairs of paths that don't have common nodes. More formally, he should find the number of groups of four integers a, b, c and d such that: 1 ≤ a &lt; b ≤ n; 1 ≤ c &lt; d ≤ n; there's no such node that lies on both the shortest path from node a to node b and from node c to node d. The shortest path betweem two nodes is the path that is shortest in the number of edges.Help Polo solve this problem.
['combinatorics', 'dfs and similar', 'trees']
n=input() e=[[] for i in range(0,n+10)] sz,f=[0]*(n+10),[0]*(n+10) s=[] ans=n*n*(n-1)*(n-1)/4 for i in xrange(1,n): u,v=map(int,raw_input().split()) e[u].append(v) e[v].append(u) q=[1] for i in xrange(0,n): u=q[i] for v in e[u]: if (v==f[u]): continue q.append(v) f[v]=u for i in reversed(xrange(0,n)): u=q[i] sz[u]+=1 sz[f[u]]+=sz[u] su=sz[u]*(sz[u]-1)/2-sum(sz[v]*(sz[v]-1)/2 for v in e[u] if (v!=f[u])) ans-=su*(su+2*(n-sz[u])*sz[u]) print ans
Python
[ "math", "graphs", "trees" ]
624
464
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 }
759
1b8c94f278ffbdf5b7fc38b3976252b6
You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
['implementation', 'number theory', 'math']
s0 = raw_input() n = int(s0) for i in xrange(n): s = raw_input() sa = s.split() x, y, b = int(sa[0]), int(sa[1]), int(sa[2]) pb = b for k in range(7): pb = (pb * pb) % y if (x * pb) % y == 0: print "Finite" else: print "Infinite"
Python
[ "number theory", "math" ]
396
252
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,751
b3d093272fcb289108fe45be8c72f38e
For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the distances are distinct. Max wants to know now how many locations the shark visited. He assumed there is such an integer k that if the shark in some day traveled the distance strictly less than k, then it didn't change the location; otherwise, if in one day the shark traveled the distance greater than or equal to k; then it was changing a location in that day. Note that it is possible that the shark changed a location for several consecutive days, in each of them the shark traveled the distance at least k.The shark never returned to the same location after it has moved from it. Thus, in the sequence of n days we can find consecutive nonempty segments when the shark traveled the distance less than k in each of the days: each such segment corresponds to one location. Max wants to choose such k that the lengths of all such segments are equal.Find such integer k, that the number of locations is as large as possible. If there are several such k, print the smallest one.
['data structures', 'dsu', 'trees', 'brute force']
import bisect; def getIntList(): return list(map(int, input().split())); def getTransIntList(n): first=getIntList(); m=len(first); result=[[0]*n for _ in range(m)]; for i in range(m): result[i][0]=first[i]; for j in range(1, n): curr=getIntList(); for i in range(m): result[i][j]=curr[i]; return result; n=int(input()); a=getIntList(); anums=[(a[i], i) for i in range(n)]; anums.sort(); location=0; length=0; k=1; pieces=[]; def upgrade(x): curr=(x, x+1) i=bisect.bisect(pieces, curr); joinLeft=False; joinRight=False; if i>0 and pieces[i-1][1]==x: joinLeft=True; if i<len(pieces) and pieces[i][0]==x+1: joinRight=True; if joinLeft: if joinRight: pieces[i-1]=(pieces[i-1][0], pieces[i][1]) pieces.pop(i); else: pieces[i-1]=(pieces[i-1][0], x+1); return pieces[i-1][1]-pieces[i-1][0]; else: if joinRight: pieces[i]=(x, pieces[i][1]) else: pieces.insert(i, curr); return pieces[i][1]-pieces[i][0]; currLength=0; currSum=0; for x in anums: currSum+=1; val, num=x; l=upgrade(num); #print(pieces); currLength=max(currLength, l); #print(currLength,"*",len(pieces),"==",currSum) if currLength*len(pieces)==currSum: currK=val+1; currLocation=len(pieces); if currLocation>location: location=currLocation; k=currK; if (location+2)*currLength-1>n: break; print(k);
Python
[ "graphs", "trees" ]
1,352
1,561
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,993
a592b3cf7ecac3d56fe4e99e35d454f6
You have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation.Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three parameters t_i, x_i, y_i in the input. Based on the value of t_i, you must do one of the following:Type 1: (t_i=1, x_i, y_i) — pick an a_i, such that 0 \le a_i \le y_i, and perform the following update a_i times: k:=\lceil (k + x_i) \rceil.Type 2: (t_i=2, x_i, y_i) — pick an a_i, such that 0 \le a_i \le y_i, and perform the following update a_i times: k:=\lceil (k \cdot x_i) \rceil.Note that x_i can be a fractional value. See input format for more details. Also, \lceil x \rceil is the smallest integer \ge x.At the i-th time-step, you must apply the i-th operation exactly once.For each j such that 1 \le j \le m, output the earliest time-step at which you can create exactly j bananas. If you cannot create exactly j bananas, output -1.
['dfs and similar', 'dp', 'graphs', 'implementation']
import math import sys def ceil(f,f1): return (f+f1-1)//f1 def main(): n, m = map(int, sys.stdin.readline().split()) dp = [math.inf] * (m + 1) dp[0] = 0 used = [0] * (m + 1) used[0] = 1 for i in range(n): t, x, y = map(int, sys.stdin.readline().split()) s = set() for r in range(m + 1): if used[r]: tw = y lo = r + ceil(x,100000) if t == 1 else ceil(r * x, 100000) while tw and lo <= m and not used[lo] and lo not in s: s.add(lo) dp[lo] = min(dp[lo], i) r = lo tw -= 1 lo = r + ceil(x,100000) if t == 1 else ceil(r * x, 100000) for h in s: used[h] = 1 for i in range(1, m + 1): print(dp[i] + 1 if dp[i] != math.inf else -1, end=' ') main()
Python
[ "graphs" ]
1,245
924
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 }
4,961
d436c7a3b7f07c9f026d00bdf677908d
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that.Let's consider a set of functions of the following form: Let's define a sum of n functions y1(x), ..., yn(x) of the given type as function s(x) = y1(x) + ... + yn(x) for any x. It's easy to show that in this case the graph s(x) is a polyline. You are given n functions of the given type, your task is to find the number of angles that do not equal 180 degrees, in the graph s(x), that is the sum of the given functions.Valeric and Valerko really want to watch the next Euro Championship game, so they asked you to help them.
['sortings', 'geometry', 'math']
from sys import stdin, stdout from decimal import Decimal n = int(stdin.readline()) visit = [] for i in range(n): k, b = map(Decimal, stdin.readline().split()) if not k: continue visit.append(-b/k) visit.sort() if len(visit): ans = 1 else: ans = 0 e = Decimal(10) ** Decimal(-10) for i in range(1, len(visit)): if visit[i] != visit[i - 1]: ans += 1 stdout.write(str(ans))
Python
[ "math", "geometry" ]
816
436
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
552
24a43df3e6d2af348692cdfbeb8a195c
Do you know a story about the three musketeers? Anyway, you will learn about its origins now.Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys.There are n warriors. Richelimakieu wants to choose three of them to become musketeers but it's not that easy. The most important condition is that musketeers must know each other to cooperate efficiently. And they shouldn't be too well known because they could be betrayed by old friends. For each musketeer his recognition is the number of warriors he knows, excluding other two musketeers.Help Richelimakieu! Find if it is possible to choose three musketeers knowing each other, and what is minimum possible sum of their recognitions.
['hashing', 'brute force', 'graphs', 'dfs and similar']
n,m=map(int,raw_input().split()) graph=[[False for i in xrange(n+1)]for j in xrange(n+1)] graph2=[[] for i in xrange(n+1)] for i in xrange(m): u,v=map(int,raw_input().split()) graph[u][v]=graph[v][u]=True graph2[u].append(v) graph2[v].append(u) ans=1e999 for u in xrange(1,n+1): for v in graph2[u]: for k in graph2[v]: if graph[u][k]: ans=min(ans,len(graph2[u])+len(graph2[v])+len(graph2[k])-6) if ans==1e999:ans=-1 print ans
Python
[ "graphs" ]
795
482
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,004
424f37abd0e19208e6b0cb8b670e7187
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of the translation:Define T as a set of points which is the union of all P(x,y) such that the origin (0,0) lies in P(x,y) (both strictly inside and on the boundary). There is also an equivalent definition: a point (x,y) lies in T only if there are two points A,B in P such that \overrightarrow {AB} = \overrightarrow {(x,y)}. One can prove T is a polygon too. For example, if P is a regular triangle then T is a regular hexagon. At the picture below P is drawn in black and some P(x,y) which contain the origin are drawn in colored: The spaceship has the best aerodynamic performance if P and T are similar. Your task is to check whether the polygons P and T are similar.
['geometry']
n = int(input()) polygon = [None] * n for i in range(n): polygon[i] = tuple(map(int, input().split())) if n % 2: print("NO") else: def same(id1, id2): ax = polygon[id1 + 1][0] - polygon[id1][0] ay = polygon[id1 + 1][1] - polygon[id1][1] bx = polygon[id2 + 1][0] - polygon[id2][0] by = polygon[id2 + 1][1] - polygon[id2][1] return abs(ax) == abs(bx) and (ax * by == bx * ay) polygon.append(polygon[0]) for i in range(n // 2): if not same(i, i + n // 2): print("NO") exit() print("YES")
Python
[ "geometry" ]
1,118
581
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,750
341555349b0c1387334a0541730159ac
You are given an array a_1, a_2, \dots , a_n, which is sorted in non-decreasing order (a_i \le a_{i + 1}). Find three indices i, j, k such that 1 \le i &lt; j &lt; k \le n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to construct a non-degenerate triangle with sides 3, 4 and 5 but impossible with sides 3, 4 and 7). If it is impossible to find such triple, report it.
['geometry', 'math']
for u in range(int(input())): n = int(input()) x = [int(w) for w in input().split()] if x[0] + x[1] > x[-1]: print(-1) else: print(1, 2, n)
Python
[ "math", "geometry" ]
571
185
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,244
9b05933b72dc24d743cb59978f35c8f3
The rules of Sith Tournament are well known to everyone. n Sith take part in the Tournament. The Tournament starts with the random choice of two Sith who will fight in the first battle. As one of them loses, his place is taken by the next randomly chosen Sith who didn't fight before. Does it need to be said that each battle in the Sith Tournament ends with a death of one of opponents? The Tournament ends when the only Sith remains alive.Jedi Ivan accidentally appeared in the list of the participants in the Sith Tournament. However, his skills in the Light Side of the Force are so strong so he can influence the choice of participants either who start the Tournament or who take the loser's place after each battle. Of course, he won't miss his chance to take advantage of it. Help him to calculate the probability of his victory.
['dp', 'bitmasks', 'probabilities', 'math']
import math import sys n=int(raw_input()) A=[] #print "hi" #sys.stdout.flush() for j in range(n): A+=[[float(x) for x in raw_input().split()]] #print "hi" while(True): #print n #print A if n==1: print "1.0" break if n==2: print A[0][1] break M=0 j0=1 for j in range(1,n): if A[0][j]>M: j0=j M=A[0][j] B=[] for i in range(n): if i==j0: continue B+=[[]] for j in range(n): if j==j0: continue if i!=0 and j!=0: B[-1]+=[A[i][j]] elif i==0 and j==0: B[-1]+=[0] elif i==0 and j!=0: B[-1]+=[A[0][j]*A[j][j0]+A[0][j0]*A[j0][j]] elif i!=0 and j==0: B[-1]+=[A[j][0]*A[j][j0]+A[j0][0]*A[j0][j]] A=B n-=1
Python
[ "math", "probabilities" ]
836
907
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,106
0c7a476716445c535a61f4e81edc7f75
The statement of this problem is the same as the statement of problem C2. The only difference is that, in problem C1, n is always even, and in C2, n is always odd.You are given a regular polygon with 2 \cdot n vertices (it's convex and has equal sides and equal angles) and all its sides have length 1. Let's name it as 2n-gon.Your task is to find the square of the minimum size such that you can embed 2n-gon in the square. Embedding 2n-gon in the square means that you need to place 2n-gon in the square in such way that each point which lies inside or on a border of 2n-gon should also lie inside or on a border of the square.You can rotate 2n-gon and/or the square.
['binary search', 'geometry', 'ternary search', 'math']
import sys import math range = xrange input = raw_input t = int(input()) for _ in range(t): n = int(input()) r = 0.5 * math.tan(math.pi*(2*n-2)/(4*n)) # r = 1/(2.0 * math.tan(math.pi / 2.0*n)) print 2*r
Python
[ "math", "geometry" ]
729
207
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
3,084
951437dba30c662838b6832b194b5efe
You are given a rooted tree consisting of n vertices. Each vertex has a number written on it; number ai is written on vertex i.Let's denote d(i, j) as the distance between vertices i and j in the tree (that is, the number of edges in the shortest path from i to j). Also let's denote the k-blocked subtree of vertex x as the set of vertices y such that both these conditions are met: x is an ancestor of y (every vertex is an ancestor of itself); d(x, y) ≤ k. You are given m queries to the tree. i-th query is represented by two numbers xi and ki, and the answer to this query is the minimum value of aj among such vertices j such that j belongs to ki-blocked subtree of xi.Write a program that would process these queries quickly!Note that the queries are given in a modified way.
['data structures', 'trees']
py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange def sync_with_stdio(b): if b: return import os, sys from io import BytesIO, IOBase # FastIO for PyPy2 and PyPy3 (works with interactive) by Pajenegod class FastI(object): def __init__(self, fd=0, buffersize=2**14): self.stream = stream = BytesIO(); self.bufendl = 0 def read2buffer(): s = os.read(fd, buffersize + os.fstat(fd).st_size); pos = stream.tell() stream.seek(0,2); stream.write(s); stream.seek(pos); return s self.read2buffer = read2buffer # Read entire input def read(self): while self.read2buffer(): pass return self.stream.read() if self.stream.tell() else self.stream.getvalue() def readline(self): while self.bufendl == 0: s = self.read2buffer(); self.bufendl += s.count(b"\n") + (not s) self.bufendl -= 1; return self.stream.readline() def input(self): return self.readline().rstrip(b'\r\n') # Read all remaining integers, type is given by optional argument def readnumbers(self, zero=0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; c = b"-"[0] for c in self.read(): if c >= b"0"[0]: numb = 10 * numb + conv(c) - 48 elif c == b"-"[0]: sign = -1 elif c != b"\r"[0]: A.append(sign*numb); numb = zero; sign = 1 if c >= b"0"[0]: A.append(sign*numb) return A class FastO(IOBase): def __init__(self, fd=1): stream = BytesIO() self.flush = lambda: os.write(1, stream.getvalue()) and not stream.truncate(0) and stream.seek(0) self.write = stream.write if py2 else lambda s: stream.write(s.encode()) sys.stdin, sys.stdout = FastI(), FastO() global input input = sys.stdin.input import sys class ostream: def __lshift__(self,a): if a == endl: sys.stdout.write("\n") sys.stdout.flush() else: sys.stdout.write(str(a)) return self def tie(self, val):pass cout = ostream() endl = object() class istream: tiedto = cout inp = None def __rlshift__(a,b): if a.tiedto == cout: sys.stdout.flush() if type(b)==tuple or type(b)==list: return type(b)(type(c)(a.get()) for c in b) return type(b)(a.get()) def tie(self, val): self.tiedto = val def get(a): while not a.inp: a.inp = sys.stdin.readline().split()[::-1] return a.inp.pop() cin = istream() class Vector: def __lshift__(self, other): self.type = other return self def __rshift__(self, other): if type(other) == tuple: return [self.type(other[1])]*other[0] else: return [self.type()]*other vector = Vector() sync_with_stdio(False); cin.tie(0); cout.tie(0); ########################## PERSISTENT SEGMENTTREE (surprisingly good memory effecient) BIG = 10**9 vals = [] L = [] R = [] # Create a persistant segmenttree of size n def create(n): ind = len(vals) vals.append(BIG) L.append(-1) R.append(-1) if n==1: L[ind] = -1 R[ind] = -1 else: mid = n//2 L[ind] = create(mid) R[ind] = create(n - mid) return ind # Set seg[i]=val for segment tree ind, of size n, def setter(ind, i, val, n): ind2 = len(vals) vals.append(BIG) L.append(-1) R.append(-1) if n==1: vals[ind2] = val return ind2 mid = n//2 if i < mid: L[ind2] = setter(L[ind], i, val, mid) R[ind2] = R[ind] else: L[ind2] = L[ind] R[ind2] = setter(R[ind], i - mid, val, n - mid) vals[ind2] = min(vals[L[ind2]], vals[R[ind2]]) return ind2 # Find minimum of seg[l:r] for segment tree ind, of size n def minimum(ind, l, r, n): if l==0 and r==n: return vals[ind] mid = n//2 if r <= mid: return minimum(L[ind], l, r, mid) elif mid<=l: return minimum(R[ind], l - mid, r - mid, n - mid) else: return min( minimum(L[ind], l, mid, mid), minimum(R[ind], 0, r - mid, n - mid)) ###################################################################### import sys inp = sys.stdin.readnumbers() ii = 0 n = inp[ii] ii += 1 r = inp[ii]-1 ii += 1 A = inp[ii:ii+n] ii += n coupl = [[] for _ in range(n)] for _ in range(n-1): x,y = inp[ii]-1, inp[ii+1]-1 ii += 2 coupl[x].append(y) coupl[y].append(x) # Start reordering the nodes after DFS ordering found = [False]*n found[r] = True Qdum = [r] Q = [] while Qdum: node = Qdum.pop() Q.append(node) for nei in coupl[node]: if not found[nei]: found[nei] = True Qdum.append(nei) mapper = [-1]*n for i,node in enumerate(Q): mapper[node] = i couplprim = [] for node in range(n): couplprim.append([mapper[nei] for nei in coupl[Q[node]]]) rprim = 0 assert(rprim == mapper[r]) Aprim = [A[Q[i]] for i in range(n)] # Nodes has been reordered, now figure out some DFS stuff like dfs, family size depth = [-1]*n family_size = [0]*n depth[rprim] = 0 Qprim = [rprim] first_time = [True]*n while Qprim: node = Qprim.pop() if first_time[node]: first_time[node] = False Qprim.append(node) for nei in couplprim[node]: if depth[nei] == -1: depth[nei] = depth[node]+1 Qprim.append(nei) else: f = 1 for nei in couplprim[node]: f += family_size[nei] family_size[node] = f # Time to bucket sort the nodes in order of depth D = [[] for _ in range(2*n)] for node in range(n): D[depth[node]].append(node) ##################### PERSISTENT SEGMENT TREE PART # So simple, yet so much going on Dseg = [0]*(2*n) ind = create(n) for i,nodes in enumerate(D): for node in nodes: ind = setter(ind, node, Aprim[node], n) Dseg[i] = ind ############################# m = inp[ii] ii += 1 ans = 0 for _ in range(m): p = inp[ii] ii += 1 q = inp[ii] ii += 1 x = mapper[(p + ans)%n] k = (q + ans)%n ans = minimum(Dseg[depth[x]+k], x, x + family_size[x], n) cout << ans << "\n"
Python
[ "trees" ]
784
6,446
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 }
4,460
67a70d58415dc381afaa74de1fee7215
The name of one small but proud corporation consists of n lowercase English letters. The Corporation has decided to try rebranding — an active marketing strategy, that includes a set of measures to change either the brand (both for the company and the goods it produces) or its components: the name, the logo, the slogan. They decided to start with the name.For this purpose the corporation has consecutively hired m designers. Once a company hires the i-th designer, he immediately contributes to the creation of a new corporation name as follows: he takes the newest version of the name and replaces all the letters xi by yi, and all the letters yi by xi. This results in the new version. It is possible that some of these letters do no occur in the string. It may also happen that xi coincides with yi. The version of the name received after the work of the last designer becomes the new name of the corporation.Manager Arkady has recently got a job in this company, but is already soaked in the spirit of teamwork and is very worried about the success of the rebranding. Naturally, he can't wait to find out what is the new name the Corporation will receive.Satisfy Arkady's curiosity and tell him the final version of the name.
['implementation', 'strings']
import string t = string.ascii_lowercase t2 = list(t) #print(t2) n , m = map(int,input().split()) s = input() for i in range(m): x , y = input().split() index_x = t2.index(x) index_y = t2.index(y) t2[index_x] , t2[index_y] = t2[index_y] , t2[index_x] #print(t2) for i in s : index = ord(i) - ord('a') print(t2[index] , end = '')
Python
[ "strings" ]
1,232
359
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 }
210
5f44c5eed653c150476b7fc6fa5d373b
The position of the leftmost maximum on the segment [l; r] of array x = [x_1, x_2, \ldots, x_n] is the smallest integer i such that l \le i \le r and x_i = \max(x_l, x_{l+1}, \ldots, x_r).You are given an array a = [a_1, a_2, \ldots, a_n] of length n. Find the number of integer arrays b = [b_1, b_2, \ldots, b_n] of length n that satisfy the following conditions: 1 \le b_i \le m for all 1 \le i \le n; for all pairs of integers 1 \le l \le r \le n, the position of the leftmost maximum on the segment [l; r] of the array b is equal to the position of the leftmost maximum on the segment [l; r] of the array a. Since the answer might be very large, print its remainder modulo 10^9+7.
['binary search', 'data structures', 'divide and conquer', 'dp', 'flows', 'math', 'trees']
import sys def solve(): inp = sys.stdin.readline n, m = map(int, inp().split()) g = [[] for i in range(n + 1)] ginv = [[] for i in range(n + 1)] idx = 0 st = [] for v in map(int, inp().split()): while st: pv, pidx = st[-1] if pv < v: st.pop() g[idx].append(pidx) ginv[pidx].append(idx) else: break st.append((v, idx)) idx += 1 while st: pv, pidx = st[-1] st.pop() g[n].append(pidx) ginv[pidx].append(n) degree = [0] * (n + 1) st = [] for i in range(n + 1): degree[i] = len(g[i]) if degree[i] == 0: st.append(i) dp = [None] * (n + 1) MOD = int(1e9 + 7) while st: x = st[-1] st.pop() if g[x]: vec = g[x] d = dp[vec[0]] for i in range(1, m + 2): d[i] = (d[i] + d[i - 1]) % MOD for j in range(1, len(vec)): dd = dp[vec[j]] nd = [0] * (m + 2) for i in range(1, m + 2): nd[i] = (dd[i] * d[i] + nd[i - 1]) % MOD d = nd d.insert(0, 0) d.pop() else: d = [1] * (m + 2) d[0] = 0 dp[x] = d for v in ginv[x]: degree[v] -= 1 if degree[v] == 0: st.append(v) print(dp[n][m + 1]) def main(): for i in range(int(sys.stdin.readline())): solve() if __name__ == '__main__': main()
Python
[ "graphs", "math", "trees" ]
789
1,669
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 }
3,504
12218097cf5c826d83ab11e5b049999f
Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order. After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in lexicographical order in normal sense. But it was always true that after some modification of the order of letters in alphabet, the order of authors becomes lexicographical!She wants to know, if there exists an order of letters in Latin alphabet such that the names on the paper she is submitting are following in the lexicographical order. If so, you should find out any such order.Lexicographical order is defined in following way. When we compare s and t, first we find the leftmost position with differing characters: si ≠ ti. If there is no such position (i. e. s is a prefix of t or vice versa) the shortest string is less. Otherwise, we compare characters si and ti according to their order in alphabet.
['sortings', 'graphs', 'dfs and similar']
def go_through(given_char): global order global freq global orders if given_char in orders: while orders[given_char]: next_letter = orders[given_char].pop() freq[next_letter] = freq[next_letter] - 1 go_through(next_letter) if given_char not in order: order.append(given_char) num_names = int(input()) names = [] for _ in range(num_names): curr_name = input() names.append(curr_name) prev_name = names[0] possible = True orders = {} freq = {} change_letters = set() freq[prev_name[0]] = 0 for index in range(1, len(names)): name = names[index] char_index = 0 while char_index < len(name) and char_index < len(prev_name) and (name[char_index] == prev_name[char_index]): # char at index match prev # don't go over length of curr word char_index += 1 # we have either surpassed one of words or found a non-matching character if char_index < len(name) and char_index < len(prev_name): # We haven't surpassed either word; found a non-matching character previous_char = prev_name[char_index] curr_char = name[char_index] if previous_char in orders: orders[previous_char].add(curr_char) else: orders[previous_char] = {curr_char} if curr_char in freq: freq[curr_char] = freq[curr_char] + 1 else: freq[curr_char] = 1 change_letters.add(previous_char) change_letters.add(curr_char) prev_name = name elif len(prev_name) > len(name): # Previous longer and matched possible = False break if not possible: print("Impossible") else: order = [] dependent_chars = list(orders.keys()) for char in dependent_chars: curr_freq = 0 if char in freq: curr_freq = freq[char] if curr_freq <= 0: go_through(char) if len(order) is not len(change_letters): print("Impossible") else: order = list(reversed(order)) for char in range(ord('a'), ord('z') + 1): character = chr(char) if character not in order: order.append(character) for char in order: print(char, end="")
Python
[ "graphs" ]
1,027
2,282
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 }
462
639eeeabcb005152035a1fcf09ed3b44
You are given a string s consisting of the characters 0, 1, and ?.Let's call a string unstable if it consists of the characters 0 and 1 and any two adjacent characters are different (i. e. it has the form 010101... or 101010...).Let's call a string beautiful if it consists of the characters 0, 1, and ?, and you can replace the characters ? to 0 or 1 (for each character, the choice is independent), so that the string becomes unstable.For example, the strings 0??10, 0, and ??? are beautiful, and the strings 00 and ?1??1 are not.Calculate the number of beautiful contiguous substrings of the string s.
['binary search', 'dp', 'greedy', 'implementation', 'strings', 'two pointers']
''' Author: your name Date: 2021-12-10 14:18:39 LastEditTime: 2021-12-27 21:12:35 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: /code_everyWeek/week3.py ''' def unstable_string(input_str): if len(input_str) == 1: return 1 i = 0 j = 1 res = 0 lastj = 0 last_value = "0/1" while i < len(input_str) and j < len(input_str): ifok, last_value = judge_ok(input_str[j-1 : j+1], last_value) if ifok: j = j + 1 else: res += (j - i) * (j - i + 1) // 2 if lastj > i: res -= (lastj - i) * (lastj - i + 1) // 2 lastj = j i = j while i >= 0 and input_str[i-1] == '?': i -= 1 last_value = "0/1" j = i + 1 res += (j - i) * (j - i + 1) // 2 if lastj > i: res -= (lastj - i) * (lastj - i +1) // 2 return res def judge_ok(substr, last_value): if substr == "10" or substr == "01" or (substr == "??" and last_value == "0/1"): return True, last_value if (substr == "?1" and last_value != "1") or (substr == "?0" and last_value != "0"): return True, last_value if substr == "??" and last_value == "0": return True, "1" if substr == "??" and last_value == "1": return True, "0" if substr == "1?": return True, "0" if substr == "0?": return True, "1" return False, last_value def unstable_string_dp(input_str): """ 动态规划做法 """ ans = 0 n = len(input_str) dp = [[0, 0] for i in range(n)] if input_str[0] == '0': dp[0][0] = 1 dp[0][1] = 0 elif input_str[0] == '1': dp[0][0] = 0 dp[0][1] = 1 else: dp[0][0] = 1 dp[0][1] = 1 ans += max(dp[0][1], dp[0][0]) for i in range(1, n): if input_str[i] == '0': dp[i][1] = 0 dp[i][0] = dp[i - 1][1] + 1 elif input_str[i] == '1': dp[i][0] = 0 dp[i][1] = dp[i - 1][0] + 1 else: dp[i][0] = dp[i - 1][1] + 1 dp[i][1] = dp[i - 1][0] + 1 ans += max(dp[i][1], dp[i][0]) return ans if __name__ == "__main__": num_test = int(input()) for i in range(num_test): input_str = input() res = unstable_string_dp(input_str) print(res)
Python
[ "strings" ]
616
2,442
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,448
6156ef296f6d512887d10a0624ad4a7b
You are given a rooted tree of 2^n - 1 vertices. Every vertex of this tree has either 0 children, or 2 children. All leaves of this tree have the same distance from the root, and for every non-leaf vertex, one of its children is the left one, and the other child is the right one. Formally, you are given a perfect binary tree.The vertices of the tree are numbered in the following order: the root has index 1; if a vertex has index x, then its left child has index 2x, and its right child has index 2x+1. Every vertex of the tree has a letter written on it, either A or B. Let's define the character on the vertex x as s_x.Let the preorder string of some vertex x be defined in the following way: if the vertex x is a leaf, then the preorder string of x be consisting of only one character s_x; otherwise, the preorder string of x is s_x + f(l_x) + f(r_x), where + operator defines concatenation of strings, f(l_x) is the preorder string of the left child of x, and f(r_x) is the preorder string of the right child of x. The preorder string of the tree is the preorder string of its root.Now, for the problem itself...You have to calculate the number of different strings that can be obtained as the preorder string of the given tree, if you are allowed to perform the following operation any number of times before constructing the preorder string of the tree: choose any non-leaf vertex x, and swap its children (so, the left child becomes the right one, and vice versa).
['combinatorics', 'divide and conquer', 'dp', 'dsu', 'hashing', 'sortings', 'trees']
from collections import deque import sys from sys import stdin, stdout import math import random sys.setrecursionlimit(10**5) answer_li = [] INF = float("inf") mod = 998244353 read = stdin.readline def ir(): return int(read()) def mir(): return map(int, read().strip().split()) def lmir(): return list(map(int, read().strip().split())) def power(bottom, up): # print(bottom, up) if up == 1: return bottom elif up == 0: return 1 tmp = power(bottom, int(up // 2)) if up % 2 == 0: return (tmp * tmp) else: return (tmp * tmp * bottom) def dfs(root): if root * 2 >= len(li): return {"ans" : 1 , "before": li[root]} left = dfs(root * 2) right = dfs(root * 2 + 1) tmp = {"ans": 0, "before" : ""} tmp["ans"] = left["ans"] * right["ans"] left["before"] = li[root * 2] + left["before"] right["before"] = li[root * 2 + 1] + right["before"] if left["before"] != right["before"]: tmp["ans"] *= 2 tmp["ans"] %= mod if left["before"] <= right["before"]: tmp["before"] = left["before"] + right["before"] else: tmp["before"] = right["before"] + left["before"] # print(root , tmp) return tmp num = ir() li = ["0"] + list(read().strip()) print(dfs(1)["ans"])
Python
[ "math", "graphs", "trees" ]
1,606
1,367
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 }
3,704
cf86add6c92fa8a72b8e23efbdb38613
You are fishing with polar bears Alice and Bob. While waiting for the fish to bite, the polar bears get bored. They come up with a game. First Alice and Bob each writes a 01-string (strings that only contain character "0" and "1") a and b. Then you try to turn a into b using two types of operations: Write parity(a) to the end of a. For example, . Remove the first character of a. For example, . You cannot perform this operation if a is empty. You can use as many operations as you want. The problem is, is it possible to turn a into b?The parity of a 01-string is 1 if there is an odd number of "1"s in the string, and 0 otherwise.
['combinatorics', 'constructive algorithms', 'number theory', 'math']
a=input() b=input() tot1=0 tot2=0 for i in a: tot1+=int(i) for i in b: tot2+=int(i) if tot1+tot1%2>=tot2: print("YES") else: print("NO")
Python
[ "math", "number theory" ]
636
140
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,003
ea2dc6309e704d04cfdd6c79161c67f7
And where the are the phone numbers?You are given a string s consisting of lowercase English letters and an integer k. Find the lexicographically smallest string t of length k, such that its set of letters is a subset of the set of letters of s and s is lexicographically smaller than t.It's guaranteed that the answer exists.Note that the set of letters is a set, not a multiset. For example, the set of letters of abadaba is {a, b, d}.String p is lexicographically smaller than string q, if p is a prefix of q, is not equal to q or there exists i, such that pi &lt; qi and for all j &lt; i it is satisfied that pj = qj. For example, abc is lexicographically smaller than abcd , abd is lexicographically smaller than abec, afa is not lexicographically smaller than ab and a is not lexicographically smaller than a.
['constructive algorithms', 'implementation', 'strings']
n, k = map(int, input().split()) s = input() a = sorted(set(s)) idx = {} for i, j in enumerate(a): idx[j] = i if n < k: print(s + a[0] * (k - n)) exit() t = [*s[:k]] z = len(idx) l = 0 for i in range(k - 1, -1, -1): r = (idx[s[i]] + 1) % z if r == 0: l = 1 else: l = 0 t[i] = a[r] if l == 0: break print(''.join(t))
Python
[ "strings" ]
815
334
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,727
a0376bf145f4d9b5fbc1683956c203df
Lee is used to finish his stories in a stylish way, this time he barely failed it, but Ice Bear came and helped him. Lee is so grateful for it, so he decided to show Ice Bear his new game called "Critic"...The game is a one versus one game. It has t rounds, each round has two integers s_i and e_i (which are determined and are known before the game begins, s_i and e_i may differ from round to round). The integer s_i is written on the board at the beginning of the corresponding round. The players will take turns. Each player will erase the number on the board (let's say it was a) and will choose to write either 2 \cdot a or a + 1 instead. Whoever writes a number strictly greater than e_i loses that round and the other one wins that round.Now Lee wants to play "Critic" against Ice Bear, for each round he has chosen the round's s_i and e_i in advance. Lee will start the first round, the loser of each round will start the next round.The winner of the last round is the winner of the game, and the loser of the last round is the loser of the game.Determine if Lee can be the winner independent of Ice Bear's moves or not. Also, determine if Lee can be the loser independent of Ice Bear's moves or not.
['dp', 'dfs and similar', 'games']
def win(s, e): if e == s:return False elif e == s + 1:return True elif e & 1:return s & 1 == 0 elif e // 2 < s:return s & 1 == 1 elif e // 4 < s:return True else:return win(s, e // 4) def lose(s, e):return (True if e // 2 < s else win(s, e // 2)) def main(): res = [False, True] for _ in range(int(input())): s, e = [int(x) for x in input().split()] if res == [True, True]:continue if res == [False, False]:continue cur = [win(s, e), lose(s, e)] if res[0]:cur = [not x for x in cur] res = cur print(*[int(x) for x in res]) main()
Python
[ "graphs", "games" ]
1,281
626
1
0
1
0
0
0
0
0
{ "games": 1, "geometry": 0, "graphs": 1, "math": 0, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
4,900
cf1c39e85eded68515aae9eceac73313
Recently Polycarp started to develop a text editor that works only with correct bracket sequences (abbreviated as CBS). Note that a bracket sequence is correct if it is possible to get a correct mathematical expression by adding "+"-s and "1"-s to it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. Each bracket in CBS has a pair. For example, in "(()(()))": 1st bracket is paired with 8th, 2d bracket is paired with 3d, 3d bracket is paired with 2d, 4th bracket is paired with 7th, 5th bracket is paired with 6th, 6th bracket is paired with 5th, 7th bracket is paired with 4th, 8th bracket is paired with 1st. Polycarp's editor currently supports only three operations during the use of CBS. The cursor in the editor takes the whole position of one of the brackets (not the position between the brackets!). There are three operations being supported: «L» — move the cursor one position to the left, «R» — move the cursor one position to the right, «D» — delete the bracket in which the cursor is located, delete the bracket it's paired to and all brackets between them (that is, delete a substring between the bracket in which the cursor is located and the one it's paired to). After the operation "D" the cursor moves to the nearest bracket to the right (of course, among the non-deleted). If there is no such bracket (that is, the suffix of the CBS was deleted), then the cursor moves to the nearest bracket to the left (of course, among the non-deleted). There are pictures illustrated several usages of operation "D" below. All incorrect operations (shift cursor over the end of CBS, delete the whole CBS, etc.) are not supported by Polycarp's editor.Polycarp is very proud of his development, can you implement the functionality of his editor?
['data structures', 'dsu', 'strings']
class Node: def __init__(self, index): self.left = index - 1 self.right = index + 1 self.pair = -1 if __name__ == "__main__": n, m, p = map(int, input().split()) brackets = input() operations = input() nodes = [Node(i) for i in range(n + 1)] stack = [] for i in range(n): if brackets[i] == "(": stack.append(i + 1) else: pair_id = stack.pop() nodes[pair_id].pair = i + 1 nodes[i + 1].pair = pair_id for i in range(m): if operations[i] == "L": p = nodes[p].left elif operations[i] == "R": p = nodes[p].right else: pair_id = nodes[p].pair left = min(p, pair_id) right = max(p, pair_id) left_node = nodes[left].left right_node = nodes[right].right nodes[left_node].right = right_node if right_node != n + 1: nodes[right_node].left = left_node p = right_node else: p = left_node p = nodes[0].right result = [] while p != n + 1: result.append(brackets[p - 1]) p = nodes[p].right print("".join(result))
Python
[ "graphs", "strings" ]
1,820
1,261
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 }
556
fc057414df9fd8b61e01cda8bc5cdcaf
Consider the following game for two players. There is one white token and some number of black tokens. Each token is placed on a plane in a point with integer coordinates x and y.The players take turn making moves, white starts. On each turn, a player moves all tokens of their color by 1 to up, down, left or right. Black player can choose directions for each token independently.After a turn of the white player the white token can not be in a point where a black token is located. There are no other constraints on locations of the tokens: positions of black tokens can coincide, after a turn of the black player and initially the white token can be in the same point with some black point. If at some moment the white player can't make a move, he loses. If the white player makes 10100500 moves, he wins.You are to solve the following problem. You are given initial positions of all black tokens. It is guaranteed that initially all these positions are distinct. In how many places can the white token be located initially so that if both players play optimally, the black player wins?
['data structures', 'implementation', 'games']
from sys import stdin from itertools import repeat def solve(a): inf = 1001001001 C = 400010 lmn = [inf] * 400010 lmx = [-inf] * 400010 for x, y in a: x = (x - 1) / 2 + 100005 if lmn[x] > y: lmn[x] = y if lmx[x] < y: lmx[x] = y rmn = lmn[:] rmx = lmx[:] for i in xrange(200009): if lmn[i+1] > lmn[i]: lmn[i+1] = lmn[i] for i in xrange(200009): if lmx[i+1] < lmx[i]: lmx[i+1] = lmx[i] for i in xrange(200009, 0, -1): if rmn[i-1] > rmn[i]: rmn[i-1] = rmn[i] for i in xrange(200009, 0, -1): if rmx[i-1] < rmx[i]: rmx[i-1] = rmx[i] for i in xrange(200010): if lmn[i] < rmn[i]: lmn[i] = rmn[i] for i in xrange(200010): if lmx[i] > rmx[i]: lmx[i] = rmx[i] ans = 0 for i in xrange(200009): if lmn[i] < lmn[i+1]: lmn[i] = lmn[i+1] for i in xrange(200009): if lmx[i] > lmx[i+1]: lmx[i] = lmx[i+1] for i in xrange(200009): if lmn[i] < lmx[i]: ans += (lmx[i] - lmn[i]) / 2 return ans def main(): n = int(stdin.readline()) dat = map(int, stdin.read().split(), repeat(10, 2 * n)) s = [[], []] for i in xrange(n): x, y = dat[i*2:i*2+2] s[(x+y)&1].append((-x+y, x+y)) print solve(s[0]) + solve(s[1]) main()
Python
[ "games" ]
1,089
1,433
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,287
dd7faacff9f57635f8e00c2f8f5a4650
You have a string s_1 s_2 \ldots s_n and you stand on the left of the string looking right. You want to choose an index k (1 \le k \le n) and place a mirror after the k-th letter, so that what you see is s_1 s_2 \ldots s_k s_k s_{k - 1} \ldots s_1. What is the lexicographically smallest string you can see?A string a is lexicographically smaller than a string b if and only if one of the following holds: a is a prefix of b, but a \ne b; in the first position where a and b differ, the string a has a letter that appears earlier in the alphabet than the corresponding letter in b.
['greedy', 'strings']
for s in[*open(0)][2::2]: a=*map(ord,s[:-1]),123;i=1 while(i>1)+a[i-1]>a[i]:i+=1 s=s[:i];print(s+s[::-1])
Python
[ "strings" ]
669
108
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 }
639
2b6645cde74cc9fc6c927a6b1e709852
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
['dp', 'combinatorics', 'number theory']
from sys import stdin from itertools import repeat def main(): n = int(stdin.readline()) a = map(int, stdin.readline().split()) mod = 10 ** 9 + 7 for i in xrange(n): a[i] -= 1 lo, v = a[0], 0 px = a[0] ans = a[0] for x in a[1:]: if px > x: lo, v = x, (min(lo, x) * v + x) % mod else: lo, v = px, (min(lo, px) * v + px) % mod ans = (ans + lo * v + x) % mod px = x print ans main()
Python
[ "math", "number theory" ]
995
480
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 }
319
1dfef6ab673b51e3622be6e8ab949ddc
You are given an array of positive integers a = [a_0, a_1, \dots, a_{n - 1}] (n \ge 2).In one step, the array a is replaced with another array of length n, in which each element is the greatest common divisor (GCD) of two neighboring elements (the element itself and its right neighbor; consider that the right neighbor of the (n - 1)-th element is the 0-th element).Formally speaking, a new array b = [b_0, b_1, \dots, b_{n - 1}] is being built from array a = [a_0, a_1, \dots, a_{n - 1}] such that b_i = \gcd(a_i, a_{(i + 1) \mod n}), where \gcd(x, y) is the greatest common divisor of x and y, and x \mod y is the remainder of x dividing by y. In one step the array b is built and then the array a is replaced with b (that is, the assignment a := b is taking place).For example, if a = [16, 24, 10, 5] then b = [\gcd(16, 24), \gcd(24, 10), \gcd(10, 5), \gcd(5, 16)] = [8, 2, 5, 1]. Thus, after one step the array a = [16, 24, 10, 5] will be equal to [8, 2, 5, 1].For a given array a, find the minimum number of steps after which all values a_i become equal (that is, a_0 = a_1 = \dots = a_{n - 1}). If the original array a consists of identical elements then consider the number of steps is equal to 0.
['binary search', 'brute force', 'data structures', 'divide and conquer', 'number theory', 'two pointers']
import math t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) allthesame, gcd = 1, a[0] for j in range(n): if a[j] != a[0]: allthesame = 0 gcd = math.gcd(a[j], gcd) if allthesame == 1: print("0") continue ans, seq = 0, [] for j in range(2*n): rj = j % n seq2 = [] for k in range(len(seq)): seq[k][0] = math.gcd(seq[k][0], a[rj]) if seq[k][0] == gcd: ans = max(ans, seq[k][1]+1) else: seq[k][1] = seq[k][1] + 1 if k == 0 or seq[k][0] != seq[k-1][0]: seq2.append(seq[k]) if j < n: if len(seq) == 0 or a[j] != seq[len(seq)-1][0]: seq2.append([a[j], 0]) seq = seq2 print(ans)
Python
[ "number theory" ]
1,409
888
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,309
02a94c136d3fb198025242e91264823b
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are not adjacent.Formally, consider positions of all letters in the string in the alphabet. These positions should form contiguous segment, i.e. they should come one by one without any gaps. And all letters in the string should be distinct (duplicates are not allowed).You are given a sequence of strings. For each string, if it is diverse, print "Yes". Otherwise, print "No".
['implementation', 'strings']
from sys import stdin lines = stdin.readlines() n = int(lines[0]) dikte = {} alphabet = "abcdefghijklmnopqrstuvwxyz" j = 1 for i in alphabet: dikte[i] = j j += 1 for i in range(1,n+1): c = lines[i][:-1] c2 = (sorted(c)) liste = [] flag = True for j in c2: if j not in liste: liste.append(j) else: print "NO" flag = False break c3 = dikte[c2[-1]]-dikte[c2[0]] if flag==True and c3!=len(c2)-1: print "NO" elif flag==True and c3==len(c2)-1: print "YES"
Python
[ "strings" ]
691
585
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 }
143
b03895599bd578a83321401428e277da
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other's place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be. In order to make sure that he's right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.You are given the Santa's favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
['implementation', 'strings']
a,b = input(), input() s = "" for i in range(len(a)): x, y = str(max(a[i], b[i])), str(min(a[i], b[i])) if (x in s and x+y not in s) or (y in s and x+y not in s): print('-1') exit() if x+y not in s: s +=" " + x + y lis = [] for i in s.split(): if i[0] != i[1]: lis.append(i[0] + " " + i[1]) print(len(lis)) for i in lis: print(i)
Python
[ "strings" ]
620
417
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,180
4ce699a5633d6d3073c2daa7e10060bd
Mocha wants to be an astrologer. There are n stars which can be seen in Zhijiang, and the brightness of the i-th star is a_i. Mocha considers that these n stars form a constellation, and she uses (a_1,a_2,\ldots,a_n) to show its state. A state is called mathematical if all of the following three conditions are satisfied: For all i (1\le i\le n), a_i is an integer in the range [l_i, r_i]. \sum \limits _{i=1} ^ n a_i \le m. \gcd(a_1,a_2,\ldots,a_n)=1. Here, \gcd(a_1,a_2,\ldots,a_n) denotes the greatest common divisor (GCD) of integers a_1,a_2,\ldots,a_n.Mocha is wondering how many different mathematical states of this constellation exist. Because the answer may be large, you must find it modulo 998\,244\,353.Two states (a_1,a_2,\ldots,a_n) and (b_1,b_2,\ldots,b_n) are considered different if there exists i (1\le i\le n) such that a_i \ne b_i.
['combinatorics', 'dp', 'fft', 'math', 'number theory']
import sys input=sys.stdin.readline #文字列入力はするな! mod=998244353 n,m=map(int,input().split()) l=[0] r=[0] for i in range(n): x,y=map(int,input().split()) l.append(x) r.append(y) f=[0]*(m+10) for g in range(m,0,-1): if m//g<n:continue dp=[0]*(n+3)*(m//g+2) def _(i,k): return k*(n+2)+i dp[_(0,0)]=1 sdp=[1]*(m//g+3) for i in range(1,n+1): for k in range(m//g+2): x,y=(l[i]+g-1)//g,r[i]//g ma=k-x mi=k-y if ma<0:continue if mi<=0:dp[_(i,k)]=sdp[ma] else:dp[_(i,k)]=sdp[ma]-sdp[mi-1] dp[_(i,k)]%=mod sdp[0]=dp[_(i,0)] for k in range(1,m//g+2): sdp[k]=sdp[k-1]+dp[_(i,k)] sdp[k]%=mod for k in range(m//g+1): f[g]+=dp[_(n,k)] f[g]%=mod ans=[0]*(m+5) for g in range(m,0,-1): ans[g]=f[g] i=2 while i*g<=m: ans[g]-=ans[g*i] ans[g]%=mod i+=1 print(ans[1])
Python
[ "math", "number theory" ]
967
992
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,655
09eaa5ce235350bbc1a3d52441472c37
The problem was inspired by Pied Piper story. After a challenge from Hooli's compression competitor Nucleus, Richard pulled an all-nighter to invent a new approach to compression: middle-out.You are given two strings s and t of the same length n. Their characters are numbered from 1 to n from left to right (i.e. from the beginning to the end).In a single move you can do the following sequence of actions: choose any valid index i (1 \le i \le n), move the i-th character of s from its position to the beginning of the string or move the i-th character of s from its position to the end of the string. Note, that the moves don't change the length of the string s. You can apply a move only to the string s.For example, if s="test" in one move you can obtain: if i=1 and you move to the beginning, then the result is "test" (the string doesn't change), if i=2 and you move to the beginning, then the result is "etst", if i=3 and you move to the beginning, then the result is "stet", if i=4 and you move to the beginning, then the result is "ttes", if i=1 and you move to the end, then the result is "estt", if i=2 and you move to the end, then the result is "tste", if i=3 and you move to the end, then the result is "tets", if i=4 and you move to the end, then the result is "test" (the string doesn't change). You want to make the string s equal to the string t. What is the minimum number of moves you need? If it is impossible to transform s to t, print -1.
['constructive algorithms', 'greedy', 'strings']
q = int(input()) for x in range(q): n = int(input()) s = str(input()) t = str(input()) ss = sorted(s) tt = sorted(t) if ss != tt: ans = -1 else: ans = 1000000000 for i in range(n): k = i for j in range(n): if k < n and s[j] == t[k]: k+=1 ans = min(ans, n - k + i) print(ans)
Python
[ "strings" ]
1,628
409
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,543
7ad1f3f220c12a68c1242a22f4fd7761
Omkar and Akmar are playing a game on a circular board with n (2 \leq n \leq 10^6) cells. The cells are numbered from 1 to n so that for each i (1 \leq i \leq n-1) cell i is adjacent to cell i+1 and cell 1 is adjacent to cell n. Initially, each cell is empty.Omkar and Akmar take turns placing either an A or a B on the board, with Akmar going first. The letter must be placed on an empty cell. In addition, the letter cannot be placed adjacent to a cell containing the same letter. A player loses when it is their turn and there are no more valid moves.Output the number of possible distinct games where both players play optimally modulo 10^9+7. Note that we only consider games where some player has lost and there are no more valid moves.Two games are considered distinct if the number of turns is different or for some turn, the letter or cell number that the letter is placed on were different.A move is considered optimal if the move maximizes the player's chance of winning, assuming the other player plays optimally as well. More formally, if the player who has to move has a winning strategy, they have to make a move after which they will still have a winning strategy. If they do not, they can make any move.
['chinese remainder theorem', 'combinatorics', 'constructive algorithms', 'fft', 'games', 'geometry', 'math', 'meet-in-the-middle', 'string suffix structures']
from math import factorial def win(a): bw = None;bc = 0 for i in range(len(a)): if a[i] is None: for j in range(2): if a[i-1] == j or a[(i+1)%len(a)] == j:continue a[i] = j;w, c = win(a);a[i] = None if bw != False: bw = w if w == False:bc = c else:bc += c else:bc += c if bw is None:return False, 1 else:return ((not bw), bc) F = dict() def win1(left, d): global F;a = [] if left == 0:return 0 if (left, d) in F:return F[(left, d)] if left == 1: if d == 0:a.append(0) else:F[(left, d)] = 0;return 0 else: if d == 1: a.append(win1(0,1) ^ win1(left-1,0)) for i in range(1,left-1):a.append(win1(i,1) ^ win1(left-i-1,0));a.append(win1(i,0) ^ win1(left-i-1,1)) else: a.append(win1(0,1) ^ win1(left-1,1)) for i in range(1,left-1):a.append(win1(i,1) ^ win1(left-i-1,1));a.append(win1(i,0) ^ win1(left-i-1,0)) s = set(a) for i in range(100000): if i not in s:F[(left, d)] = i;return i def rec(a, i): if i == len(a): for i in range(len(a)): if a[i] == 1 and (a[i-1] == 1 or a[(i+1)%len(a)] == 1):return 0 print(a);return 1 r = 0 for j in range(2):a[i] = j;r += rec(a, i+1) return r MOD = 10**9+7;F = [0]*(10**6+3);F[0] = 1 for i in range(1,len(F)):F[i] = (F[i-1]*i)%MOD FI = [0]*len(F);FI[-1] = pow(F[-1], MOD-2, MOD) for i in range(len(F)-2,-1,-1):FI[i] = (FI[i+1]*(i+1))%MOD def C(n, k):return (F[n]*FI[n-k]*FI[k]) % MOD def H(n, k): if k == 0:return 1 return C(n-k,k)+C(n-k-1,k-1) def solve(): n = int(input());r = 0 for i in range(n): if i*2 > n:break if (n - i) % 2 == 0:r = (r + H(n, i) * F[n-i]) % MOD print((2*r)%MOD) solve()
Python
[ "math", "number theory", "geometry", "strings", "games" ]
1,286
1,669
1
1
0
1
1
0
1
0
{ "games": 1, "geometry": 1, "graphs": 0, "math": 1, "number theory": 1, "probabilities": 0, "strings": 1, "trees": 0 }
1,709
90cd4a83d3d7826a2385fcea434ae071
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop if the input data contains the substring s2, and the third requires too much memory if the input data contains the substring s3. Bob wants these solutions to fail single test. What is the minimal length of test, which couldn't be passed by all three Bob's solutions?
['hashing', 'strings']
import sys from array import array # noqa: F401 from itertools import permutations def input(): return sys.stdin.buffer.readline().decode('utf-8') class RollingHash(object): __slots__ = ['hash1', 'hash2'] from random import randint N = 10**5 + 100 BASE = randint(1000, 9999) MOD1, MOD2 = 1000000007, 998244353 BASE1, BASE2 = array('i', [1]) * N, array('i', [1]) * N for i in range(1, N): BASE1[i] = BASE1[i - 1] * BASE % MOD1 BASE2[i] = BASE2[i - 1] * BASE % MOD2 def __init__(self, source: list): self.hash1 = hash1 = array('i', [0] + source) self.hash2 = hash2 = array('i', [0] + source) for i in range(1, len(source) + 1): hash1[i] = (hash1[i] + hash1[i - 1] * self.BASE) % self.MOD1 hash2[i] = (hash2[i] + hash2[i - 1] * self.BASE) % self.MOD2 def get(self, l: int, r: int): return ( (self.hash1[r] - self.hash1[l] * self.BASE1[r - l]) % self.MOD1, (self.hash2[r] - self.hash2[l] * self.BASE2[r - l]) % self.MOD2 ) s = [list(map(ord, input().rstrip())) for _ in range(3)] rh = [RollingHash(a) for a in s] n = [len(s[i]) for i in range(3)] def solve(x, y, st=0): for i in range(st, n[x]): slen = min(n[x] - i, n[y]) if rh[x].get(i, i + slen) == rh[y].get(0, slen): return i return n[x] def solve2(x, y, z, i=0): for j in range(n[y]): slen = min(n[y] - j, n[z]) if rh[y].get(j, j + slen) == rh[y].get(0, slen): slen2 = min(n[x] - i - j, n[z]) if slen2 <= 0 or rh[x].get(0, slen2): return i + j return solve(x, z, n[y]) if n[y] < n[x] else n[y] ans = sum(n) for a in permutations(range(3)): i = solve(a[0], a[1]) j = solve(a[1], a[2]) + i if j < n[a[0]]: j = solve(a[0], a[2], j) ans = min(ans, max(n[a[0]], i + n[a[1]], j + n[a[2]])) print(ans)
Python
[ "strings" ]
585
1,935
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,589
f4a5815ecbdf744b80791cf728abf8c6
Mark is administering an online exam consisting of n true-false questions. However, he has lost all answer keys. He needs a way to retrieve the answers before his client gets infuriated.Fortunately, he has access to the grading system. Thus, for each query, you can input the answers to all n questions, and the grading system will output how many of them are correct.He doesn't have much time, so he can use the grading system at most 675 times. Help Mark determine the answer keys.Note that answer keys are fixed in advance and will not change depending on your queries.
['bitmasks', 'constructive algorithms', 'interactive', 'probabilities']
#from math import ceil, floor #, gcd, log, factorial, comb, perm, #log10, log2, log, sin, asin, tan, atan, #from heapq import heappop,heappush,heapify #heappop(hq), heapify(list) #from collections import defaultdict as dd #mydd=dd(list) for .append #from collections import deque as dq #deque e.g. myqueue=dq(list) #append/appendleft/appendright/pop/popleft import sys input = sys.stdin.readline #sys.setrecursionlimit(100000) #default is 1000 ############ ---- Input Functions ---- ############ def inp(): return(int(input())) #def inlt(): # return(list(map(int,input().split()))) #.split(','), default is space def insr(): s = input().strip("\n") return(list(s)) #def invr(): # return(map(int,input().split())) #################################################### #1) inp — For taking integer inputs. #2) inlt — For taking List inputs. #3) insr — For taking string inputs. Returns a List of Characters. #4) invr — For taking space seperated integer variable inputs. #################################################### def solve(): n=inp() s1=['T']*n;s2=['T','F']*(n//2)+['T']*(n%2) print("".join(s1));sys.stdout.flush() a1=inp() if a1==n:return print("".join(s2));sys.stdout.flush() a2=inp() if a2==n:return ans=[] for i in range(n//3): s1[3*i]='F';s1[3*i+1]='F' print("".join(s1));sys.stdout.flush() ax=inp() if ax==n:return if ax-a1==2: ans.append('FF') s1[3*i+2]='F' print("".join(s1));sys.stdout.flush() ay=inp() if ay==n:return if ay>ax: ans.append('F') else: ans.append('T') elif a1-ax==2: ans.append('TT') s1[3*i+2]='F' print("".join(s1));sys.stdout.flush() ay=inp() if ay==n:return if ay>ax: ans.append('F') else: ans.append('T') else: if i%2==0: s2[3*i],s2[3*i+1],s2[3*i+2]='F','T','F' else: s2[3*i],s2[3*i+1],s2[3*i+2]='T','F','T' print("".join(s2));sys.stdout.flush() az=inp() if az==n:return if az-a2==3: ans.append(s2[3*i]+s2[3*i+1]+s2[3*i]) elif a2-az==3: ans.append(s2[3*i+1]+s2[3*i]+s2[3*i+1]) elif az-a2==1: ans.append(s2[3*i]+s2[3*i+1]+s2[3*i+1]) else: ans.append(s2[3*i+1]+s2[3*i]+s2[3*i]) s1[3*i],s1[3*i+1],s1[3*i+2]='T','T','T' if i%2==0: s2[3*i],s2[3*i+1],s2[3*i+2]='T','F','T' else: s2[3*i],s2[3*i+1],s2[3*i+2]='F','T','F' for i in range(3*(n//3),n): s1[i]='F' print("".join(s1));sys.stdout.flush() ax=inp() if ax==n:return if ax>a1: ans.append('F') else: ans.append('T') s1[i]='T' print("".join(ans));sys.stdout.flush() solve() #print(*ans,sep=' ')##print("{:.3f}".format(ans)+"%") #:b binary :% eg print("{:6.2%}".format(ans)) #print(" ".join(str(i) for i in ans)) #print(" ".join(map(str,ans))) #seems faster #prefixsum a=[a1...an] #psa=[0]*(n+1) #for i in range(n): psa[i+1]=psa[i]+a[i] #sum[:ax]=psa[x+1] e.g. sum 1st 5 items in psa[5] #ASCII<->number ord('f')=102 chr(102)='f' #def binary_search(li, val, lb, ub): # while ((ub-lb)>1): # mid = (lb + ub) // 2 # if li[mid] >= val: # ub = mid # else: # lb = mid # return lb+1 #return index of elements <val in li #def binary_search(li, val, lb, ub): # ans = -1 # while (lb <= ub): # mid = (lb + ub) // 2 # if li[mid] > val: # ub = mid - 1 # elif val > li[mid]: # lb = mid + 1 # else: # ans = mid # return index # break # return ans ########## #def pref(li): # pref_sum = [0] # for i in li: # pref_sum.append(pref_sum[-1] + i) # return pref_sum ########## #def suff(li): # suff_sum = [0] # for i in range(len(li)-1,-1,-1): # suff_sum.insert(0,suff_sum[0] + li[i]) # return suff_sum ############# #def maxSubArraySumI(arr): #Kadane's algorithm with index # max_till_now=arr[0];max_ending=0;size=len(arr) # start=0;end=0;s=0 # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending: # max_till_now=max_ending # start=s;end=i # if max_ending<0: # max_ending=0 # s=i+1 # return max_till_now,start,end ############# avoid max for 2 elements - slower than direct if #def maxSubArraySum(arr): #Kadane's algorithm # max_till_now=arr[0];max_ending=0;size=len(arr) # for i in range(0, size): # max_ending = max_ending + arr[i] # if max_till_now < max_ending:max_till_now=max_ending # if max_ending<0:max_ending=0 # return max_till_now ############# #def findbits(x): # tmp=[] # while x>0:tmp.append(x%2);x//=2 # tmp.reverse() # return tmp ##############Dijkstra algorithm example #dg=[999999]*(n+1);dg[n]=0;todo=[(0,n)];chkd=[0]*(n+1) #while todo:#### find x with min dg in todo # _,x=hq.heappop(todo) # if chkd[x]:continue # for i in coming[x]:going[i]-=1 # for i in coming[x]: # tmp=1+dg[x]+going[i] # if tmp<dg[i]:dg[i]=tmp;hq.heappush(todo,(dg[i],i)) # chkd[x]=1 ################ ## moves to match 2 binary strings: sum_{i=1}^n(abs(diff in i-th prefix sums)) ############### ##s=[2, 3, 1, 4, 5, 3] ##sorted(range(len(s)), key=lambda k: s[k]) ##gives sorted indices [2, 0, 1, 5, 3, 4] ##m= [[3, 4, 6], [2, 4, 8], [2, 3, 4], [1, 2, 3], [7, 6, 7], [1, 8, 2]] ##m.sort(reverse=True,key=lambda k:k[2]) #sorts m according to 3rd elements
Python
[ "probabilities" ]
590
6,038
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 }
216
ca817fe0a97e2d8a6bcfcb00103b6b6d
You have a string s consisting of lowercase Latin alphabet letters. You can color some letters in colors from 1 to k. It is not necessary to paint all the letters. But for each color, there must be a letter painted in that color.Then you can swap any two symbols painted in the same color as many times as you want. After that, k strings will be created, i-th of them will contain all the characters colored in the color i, written in the order of their sequence in the string s.Your task is to color the characters of the string so that all the resulting k strings are palindromes, and the length of the shortest of these k strings is as large as possible.Read the note for the first test case of the example if you need a clarification.Recall that a string is a palindrome if it reads the same way both from left to right and from right to left. For example, the strings abacaba, cccc, z and dxd are palindromes, but the strings abab and aaabaa — are not.
['binary search', 'greedy', 'sortings', 'strings']
for t in range(int(input())): n, k = map(int, input().split()) s = input() d = dict() for i in s: if i in d: d[i] += 1 else: d[i] = 1 counter_2 = 0 for i in d: counter_2 += d[i]//2 ans = (counter_2//k)*2 extra = n - (ans*k) ans += 1 if extra >= k else 0 print(ans)
Python
[ "strings" ]
1,011
414
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,425
d6f01ece3f251b7aac74bf3fd8231a80
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts in the same order. You are also given some text consisting of small and capital English letters and digits. It is known that it was typed in the first layout, but the writer intended to type it in the second layout. Print the text if the same keys were pressed in the second layout.Since all keys but letters are the same in both layouts, the capitalization of the letters should remain the same, as well as all other characters.
['implementation', 'strings']
a=input() b=input() c=input() f="" for i in c: if(ord(i)>=65): for j in range(len(a)): if(i.lower()==a[j]): if(i.isupper()): f+=b[j].upper() else: f+=b[j] else: f+=i print(f)
Python
[ "strings" ]
746
282
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,106
bdd98d17ff0d804d88d662cba6a61e8f
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.Misha has a list of handle change requests. After completing the requests he wants to understand the relation between the original and the new handles of the users. Help him to do that.
['data structures', 'dsu', 'strings']
q = int(raw_input()) handles = {} for i in range(q): oldName, newName = raw_input().split() handles[oldName] =[newName] for name in handles: if (oldName in handles[name]): handles[name].append(newName) del handles[oldName] break print len(handles) for name in handles: print name, handles[name][-1]
Python
[ "graphs", "strings" ]
436
336
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 }
3,773
883f728327aea19993089a65d452b79f
Why I have to finish so many assignments???Jamie is getting very busy with his school life. He starts to forget the assignments that he has to do. He decided to write the things down on a to-do list. He assigns a value priority for each of his assignment (lower value means more important) so he can decide which he needs to spend more time on.After a few days, Jamie finds out the list is too large that he can't even manage the list by himself! As you are a good friend of Jamie, help him write a program to support the following operations on the to-do list: set ai xi — Add assignment ai to the to-do list if it is not present, and set its priority to xi. If assignment ai is already in the to-do list, its priority is changed to xi. remove ai — Remove assignment ai from the to-do list if it is present in it. query ai — Output the number of assignments that are more important (have a smaller priority value) than assignment ai, so Jamie can decide a better schedule. Output - 1 if ai is not in the to-do list. undo di — Undo all changes that have been made in the previous di days (not including the day of this operation) At day 0, the to-do list is empty. In each of the following q days, Jamie will do exactly one out of the four operations. If the operation is a query, you should output the result of the query before proceeding to the next day, or poor Jamie cannot make appropriate decisions.
['data structures', 'trees', 'interactive']
import sys, os, __pypy__ from collections import defaultdict from cStringIO import StringIO from io import IOBase range = xrange input = raw_input L = [] R = [] A = [0] __pypy__.resizelist_hint(L, 50*10**5) __pypy__.resizelist_hint(R, 50*10**5) __pypy__.resizelist_hint(A, 50*10**5) def create(): L.append(-1) R.append(-1) A.append(0) return len(L) - 1 def copy(ind): L.append(L[ind]) R.append(R[ind]) A[-1] = A[ind] A.append(0) return len(L) - 1 def adder(i, n, ind, x): ind0 = ind = copy(ind) if ind >= 0 else create() while n != 1: A[ind] += x n = n >> 1 if i < n: L[ind] = ind = copy(L[ind]) if L[ind] >= 0 else create() else: R[ind] = ind = copy(R[ind]) if R[ind] >= 0 else create() i -= n A[ind] += x return ind0 def getter(l, r, n, ind): ans = 0 while ind >= 0 and 0 < r and l < n: if l <= 0 and r >= n: ans += A[ind] break n = n >> 1 ans += getter(l - n, r - n, n, R[ind]) ind = L[ind] return ans def getteri(i, n, ind): ans = 0 while ind >= 0: if n == 1: return A[ind] n = n >> 1 if i < n: ind = L[ind] else: i -= n ind = R[ind] return 0 mapper = {'set':0, 'remove':1, 'query':2, 'undo':3} N = 1 << 30 M = 1 << 17 def main(): curbucket = -1 curprio = -1 Tbucket = [curbucket] Tprio = [curprio] identifier = defaultdict(lambda: len(identifier)) q = int(input()) for curd in range(q): inp = sys.stdin.readline().split(); ii = 0 cas = mapper[inp[ii]]; ii += 1 if cas == 0: aind = identifier[inp[ii]]; ii += 1 new_prio = int(inp[ii]); ii += 1 prio = getteri(aind, M, curprio) curprio = adder(aind, M, curprio, new_prio - prio) if prio: curbucket = adder(prio, N, curbucket, -1) if new_prio: curbucket = adder(new_prio, N, curbucket, 1) elif cas == 1: aind = identifier[inp[ii]]; ii += 1 prio = getteri(aind, M, curprio) if prio: curbucket = adder(prio, N, curbucket, -1) curprio = adder(aind, M, curprio, -prio) elif cas == 2: aind = identifier[inp[ii]]; ii += 1 prio = getteri(aind, M, curprio) ans = getter(0, prio, N, curbucket) if prio else -1 os.write(1, str(ans) + '\n') else: # cas == 3 d = int(inp[ii]); ii += 1 curbucket = Tbucket[curd - d] curprio = Tprio[curd - d] Tbucket.append(curbucket) Tprio.append(curprio) # region fastio BUFSIZE = 8192 class FastI(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = StringIO() self.newlines = 0 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("\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() class FastO(IOBase): def __init__(self, file): self._fd = file.fileno() self._buffer = __pypy__.builders.StringBuilder() self.write = lambda s: self._buffer.append(s) def flush(self): os.write(self._fd, self._buffer.build()) self._buffer = __pypy__.builders.StringBuilder() sys.stdin, sys.stdout = FastI(sys.stdin), FastO(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main()
Python
[ "trees" ]
1,411
4,178
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 }
167
26aef004295df530352485ce53b47364
You have a card deck of n cards, numbered from top to bottom, i. e. the top card has index 1 and bottom card — index n. Each card has its color: the i-th card has color a_i.You should process q queries. The j-th query is described by integer t_j. For each query you should: find the highest card in the deck with color t_j, i. e. the card with minimum index; print the position of the card you found; take the card and place it on top of the deck.
['brute force', 'data structures', 'implementation', 'trees']
import sys n,q=map(int,sys.stdin.readline().split()) a=[int(i) for i in sys.stdin.readline().split()] t=[int(i) for i in sys.stdin.readline().split()] # print(a.index(t[0])) for i in range(0,len(t)): x=a.index(t[i]) print(x+1,end=" ") a[:x+1]=[a[x]]+a[:x] # print(a)
Python
[ "trees" ]
506
293
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,352
be3295b4d43a11ee94022b103f4221a5
I wonder, does the falling rain Forever yearn for it's disdain?Effluvium of the MindYou are given a positive integer n.Find any permutation p of length n such that the sum \operatorname{lcm}(1,p_1) + \operatorname{lcm}(2, p_2) + \ldots + \operatorname{lcm}(n, p_n) is as large as possible. Here \operatorname{lcm}(x, y) denotes the least common multiple (LCM) of integers x and y.A permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
['constructive algorithms', 'greedy', 'number theory']
m = int(input()) for i in range(m): n = int(input()) s = [] for i in range(1, n+1): s.append(i) for i in range(n-1, 0, -2): s[i], s[i-1] = s[i-1], s[i] print(*s, sep = ' ')
Python
[ "number theory" ]
747
252
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,028
560bc97986a355d461bd462c4e1ea9db
IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of course the amount of the city budget funds for the construction depends on the pyramids' volume. Your task is to calculate the volume of the pilot project consisting of three pyramids — one triangular, one quadrangular and one pentagonal.The first pyramid has equilateral triangle as its base, and all 6 edges of the pyramid have equal length. The second pyramid has a square as its base and all 8 edges of the pyramid have equal length. The third pyramid has a regular pentagon as its base and all 10 edges of the pyramid have equal length.
['geometry', 'math']
import os, sys, pdb import time, calendar, datetime import math, itertools import operator as op from functools import reduce def ncr(n, r): r = min(r, n-r) numer = reduce(op.mul, range(n, n-r, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer // denom l3, l4, l5 = list(map(int, input().split())) a3 = l3 / (2 * math.tan(math.pi/3)) a4 = l4 / (2 * math.tan(math.pi/4)) a5 = l5 / (2 * math.tan(math.pi/5)) B3 = 3 * l3 * a3 / 2 B4 = 4 * l4 * a4 / 2 B5 = 5 * l5 * a5 / 2 h3 = math.sqrt(3*l3**2/4 - a3**2) h4 = math.sqrt(3*l4**2/4 - a4**2) h5 = math.sqrt(3*l5**2/4 - a5**2) print((B3*h3+B4*h4+B5*h5)/3)
Python
[ "math", "geometry" ]
861
632
0
1
0
1
0
0
0
0
{ "games": 0, "geometry": 1, "graphs": 0, "math": 1, "number theory": 0, "probabilities": 0, "strings": 0, "trees": 0 }
72
e3a1f53f78fcb3a551c3ae1cbeedaf15
Vlad came home and found out that someone had reconfigured the old thermostat to the temperature of a.The thermostat can only be set to a temperature from l to r inclusive, the temperature cannot change by less than x. Formally, in one operation you can reconfigure the thermostat from temperature a to temperature b if |a - b| \ge x and l \le b \le r.You are given l, r, x, a and b. Find the minimum number of operations required to get temperature b from temperature a, or say that it is impossible.
['greedy', 'math', 'shortest paths']
R=lambda:map(int,input().split()) t,=R() while t:t-=1;l,r,x=R();a,b=sorted(R());print('0'*(a==b)or+(b-a>=x)or(x<=max(a-l,r-b))*2or(r-a>=x<=b-l)*3or-1)
Python
[ "math", "graphs" ]
591
150
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,969
80fd03a1cbdef86a5f00ada85e026890
Prefix function of string t = t_1 t_2 \ldots t_n and position i in it is defined as the length k of the longest proper (not equal to the whole substring) prefix of substring t_1 t_2 \ldots t_i which is also a suffix of the same substring.For example, for string t = abacaba the values of the prefix function in positions 1, 2, \ldots, 7 are equal to [0, 0, 1, 0, 1, 2, 3].Let f(t) be equal to the maximum value of the prefix function of string t over all its positions. For example, f(abacaba) = 3.You are given a string s. Reorder its characters arbitrarily to get a string t (the number of occurrences of any character in strings s and t must be equal). The value of f(t) must be minimized. Out of all options to minimize f(t), choose the one where string t is the lexicographically smallest.
['constructive algorithms', 'greedy', 'strings']
import sys input = sys.stdin.readline inf = float('inf') def getInt(): return int(input()) def getStr(): return input().strip() def getList(split=True): s = getStr() if split: s = s.split() return map(int, s) t = getInt() # t = 1 # observations, the maximum number of Good Assignments = len(set(a)) (i.e the number of unuquie elements in the array a) # how to we assign so that all res[i] != i # let define too set, good = set(a), i.e the people who defnitely receive gifts by a people whose wish is fullfied # bad = the set people who no one wish to give to # for set good, if we assign a person in set good to another person in set good, then the bad person might be left over then he could assign to himself # hence, one possilbe approach is to fullfill the request of people in the bad group first # we notice that the wish of the first people in the bad group can always be fullied # we keep fullfiled the wishes of people in the bad group, if we can not , the we should assign the smallest bad people which no one is assinged to for him, this is always possible since the wish of first bad people always be filled # now traverse through the array again, now we know we would only process peoople in the good list, fullfill his wish if we can, otherwise assign him to the next bad people who one is assinged to again (since the set of good and bad do not itersect so no res[i] = i would not happen) # and we know that some good people would take up all other good assignments, so the godo peole who are not assigned have to assign to bad people, so the algoritm works correctly def solve(): s = getStr() n = len(s) from collections import Counter cnt = Counter(s) a = sorted(cnt) if min(s) == max(s): print(s) elif min(cnt.values()) == 1: it = min(i for i in cnt if cnt[i] == 1) res = it + "".join(sorted(s.replace(it, ""))) print(res) else: # if okay when the frquent of the other is enough to cover i i = min(a) if n - cnt[i] >= cnt[i] - 2: # can make i, i res = [i, i] pool = sorted(j for j in s if j > i) for k in range(len(pool)): res.append(pool[k]) if k < cnt[i]-2: res.append(i) print(*res, sep="") else: # can not make ii, make ij if len(cnt) == 2: res = i + a[1] * cnt[a[1]] + i * (cnt[i]-1) else: res = i + a[1] + i * (cnt[i]-1) + a[2] for i in range(1, len(a)): res += a[i] * (cnt[a[i]] - (i <= 2)) print(res) # min frequent is 1 easy # now all char >= 2 frequent # can always make f(t) = 1 # choose the strnig so that f(t) = 1 # the answer muts be of frefix xx, then as long as xx not in t then ok for _ in range(t): solve()
Python
[ "strings" ]
903
2,976
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,566
a06dbb1fb1d7116a457f031b85531e49
The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates. The flamingos are currently sleeping and you can assume that they don't move.In order to get a good view over the flamingos, each of the binoculars can be independently rotated to face any angle (not necessarily integer). Then, the binocular can be used to observe all flamingos that is located at the straight line passing through the binocular at the angle it is set. In other words, you can assign each binocular a direction corresponding to any straight line passing through the binocular, and the binocular will be able to see all flamingos located on that line.Today, some kids from the prestigious Codeforces kindergarten went on a Field Study to the Zoo. Their teacher would like to set each binocular an angle to maximize the number of flamingos that can be seen by the binocular. The teacher is very interested in the sum of these values over all binoculars. Please help him find this sum.
['geometry', 'brute force']
from ctypes import c_int32 def gcd(a,b): if b == 0: return a return gcd(b, a % b) def normalize_rational(num,den): #associate the -ve with the num or cancel -ve sign when both are -ve if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0: num = -num; den = -den #put it in its simplest form g = gcd(abs(num),abs(den)) num //= g; den //=g return (num,den) from sys import * l = stdin.readline() (n,m) = (int(tkn) for tkn in l.split()) xs = [0] * m; ys = [0] * m #maxhits = [set() for i in range(n+1)] maxhits = [c_int32(1)] * (n + 1) maxhits[0] = c_int32(0) for i in range(m): l = stdin.readline() (x,y) = (int(tkn) for tkn in l.split()) xs[i] = x; ys[i] = y line_to_points = {} for i in range(m): for j in range(m): #m = dy/dx; y = (dy/dx)x + c ==> y.dx = x.dy + c.dx #y.dx = x.dy + c' #c' = y.dx - x.dy #c' = ys[i]*dx - xs[i]*dy #Now, at y = 0, x = -c' / dy dy = ys[i] - ys[j]; dx = xs[i] - xs[j] if dy == 0: continue #not a special case anymore # if dx == 0: # if xs[i] > n: # continue # else: # count_seen_from_x = len([x for x in xs if x == xs[i]]) # maxhits[xs[i]] = max(count_seen_from_x, maxhits[xs[i]]) else: slope = normalize_rational(dy,dx) c_prime = ys[i]*dx - xs[i]*dy x_intercept = -c_prime / dy line = (slope,x_intercept) if line in line_to_points: #print("line: ", line) #print("now: ", points) points = line_to_points[line] points.add(i); points.add(j) #print("after addition: ", points) continue #if (i == 1 and j == 2): # print(c_prime, x_intercept, dy, dx) if int(x_intercept) == x_intercept and x_intercept <= n and x_intercept > 0: points = set([i,j]) line_to_points[line] = points #maxhits[int(x_intercept)] = points # count_on_line = 2 # for k in range(m): # if k != i and k != j and ys[k] * dx == xs[k]*dy + c_prime: # count_on_line += 1 # maxhits[int(x_intercept)] = max(count_on_line, maxhits[int(x_intercept)]) for line,points in line_to_points.items(): x_intercept = int(line[1]) maxhits[x_intercept] = c_int32(max(maxhits[x_intercept].value,len(points))) #print(maxhits) #print(sum([max(len(points),1) for points in maxhits]) - 1) print(sum([e.value for e in maxhits])) # Made By Mostafa_Khaled
Python
[ "geometry" ]
1,220
2,793
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,081
cd2a9169186c4ade98548c29bbdacdf0
You are given a rooted tree consisting of n vertices. Vertices are numbered from 1 to n. Any vertex can be the root of a tree.A tree is a connected undirected graph without cycles. A rooted tree is a tree with a selected vertex, which is called the root.The tree is specified by an array of parents p containing n numbers: p_i is a parent of the vertex with the index i. The parent of a vertex u is a vertex that is the next vertex on the shortest path from u to the root. For example, on the simple path from 5 to 3 (the root), the next vertex would be 1, so the parent of 5 is 1.The root has no parent, so for it, the value of p_i is i (the root is the only vertex for which p_i=i).Find such a set of paths that: each vertex belongs to exactly one path, each path can contain one or more vertices; in each path each next vertex — is a son of the current vertex (that is, paths always lead down — from parent to son); number of paths is minimal. For example, if n=5 and p=[3, 1, 3, 3, 1], then the tree can be divided into three paths: 3 \rightarrow 1 \rightarrow 5 (path of 3 vertices), 4 (path of 1 vertices). 2 (path of 1 vertices). Example of splitting a root tree into three paths for n=5, the root of the tree — node 3.
['graphs', 'implementation', 'trees']
# cook your dish here #!/usr/bin/env python from bisect import bisect_left import os from math import ceil, factorial, fmod,pi,sqrt,log import sys from collections import Counter from io import BytesIO, IOBase, StringIO def modFact(n, p): if n >= p: return 0 result = 1 for i in range(1, n + 1): result = (result * i) % p return result def calculate(p, q): mod = 998244353 expo = 0 expo = mod - 2 # Loop to find the value # until the expo is not zero while (expo): # Multiply p with q # if expo is odd if (expo & 1): p = (p * q) % mod q = (q * q) % mod # Reduce the value of # expo by 2 expo >>= 1 return p def compute_gcd(x, y): while(y): x, y = y, x % y return x # This function computes LCM def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm def read_arr(): return [int(x) for x in input().split()] def bin_search(num, arr): start = 0 end = len(arr)-1 while start <= end: mid=(start+end)//2 if arr[mid] == num: return mid elif arr[mid] > num: end= mid-1 else: start = mid + 1 return -1 def factors(n) : # Note that this loop runs till square root i = 1 ans=[] while i <= sqrt(n): if (n % i == 0) : # If divisors are equal, print only one if (n / i == i) : ans.append(i) else : # Otherwise print both ans.append(i) ans.append(int(n/i)) i = i + 1 return ans def is_palindrome(n): for j in range(len(n)//2): if n[j]!=n[len(n)-j-1]: return False return True def main(): t=int(input()) for i in range(t): n = int(input()) arr = [int(x) for x in input().split()] leaves = [True for j in range(n+1)] leaves[0]=False for j in range(n): leaves[arr[j]]=False paths = [] if n == 1: print(1) print(1) print(1) print() continue vis = [False for j in range(n+1)] for j in range(n+1): if leaves[j]: new = [] start = j while not vis[start]: new.append(start) vis[start] = True if start == arr[start-1]: break start = arr[start-1] paths.append(new) print(len(paths)) for j in paths: print(len(j)) for k in range(len(j)-1, -1, -1): print(j[k],end=" ") print() if i != t-1: print() 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
[ "graphs", "trees" ]
1,400
4,784
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,881
c53e3b38a345dcf65bf984e819c289ef
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
['data structures', 'dfs and similar', 'trees', 'shortest paths']
import sys # LCA implementation found from: # https://github.com/cheran-senthil/PyRival/blob/1971590e96b351288cacb09852896f2383862ab6/pyrival/graphs/lca.py 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 = [] self.depth = [0] * len(graph) # MODIFIED dfs = [root] while dfs: node = dfs.pop() self.path.append(node) if self.time[node] == -1: self.time[node] = len(self.path) - 1 for nei in graph[node]: if self.time[nei] == -1: self.depth[nei] = self.depth[node] + 1 # MODIFIED dfs.append(node) dfs.append(nei) self.rmq = RangeQuery(self.time[node] for node in self.path) def lca(self, a, b): a = self.time[a] b = self.time[b] if a > b: a, b = b, a return self.path[self.rmq.query(a, b + 1)] def solve(N, edges, queries): graph = [[] for i in range(N + 1)] for e in edges: graph[e[0]].append(e[1]) graph[e[1]].append(e[0]) L = LCA(1, graph) def lca(u, v): return L.lca(u, v) def getDist(u, v): return L.depth[u] + L.depth[v] - 2 * L.depth[lca(u, v)] ans = [] for x, y, a, b, k in queries: d_ab = getDist(a, b) d_axyb = getDist(a, x) + 1 + getDist(y, b) d_ayxb = getDist(a, y) + 1 + getDist(x, b) if any(d <= k and (k - d) % 2 == 0 for d in [d_ab, d_axyb, d_ayxb]): ans.append("YES") else: ans.append("NO") return "\n".join(ans) if __name__ == "__main__": N = int(input()) edges = [] for i in range(N - 1): edges.append(list(map(int, sys.stdin.readline().split()))) Q = int(input()) queries = [] for i in range(Q): queries.append(list(map(int, sys.stdin.readline().split()))) ans = solve(N, edges, queries) print(ans)
Python
[ "graphs", "trees" ]
1,044
2,512
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,025
389be6455476db86a8a5d9d5343ee35a
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss \dots For example, if s = 10010, then t = 100101001010010...Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal to cnt_{0, q} - cnt_{1, q}, where cnt_{0, q} is the number of occurrences of 0 in q, and cnt_{1, q} is the number of occurrences of 1 in q. The number of such prefixes can be infinite; if it is so, you must say that.A prefix is a string consisting of several first letters of a given string, without any reorders. An empty prefix is also a valid prefix. For example, the string "abcd" has 5 prefixes: empty string, "a", "ab", "abc" and "abcd".
['math', 'strings']
for i in range(int(input())): n,x = map(int,input().split()) s=input() count0=0 l=[] for j in range(n): if s[j]=="0": count0+=1 l.append(count0) else: count0-=1 l.append(count0) a=s.count("0") b=len(s)-a k=a-b if a==b and x==0: print(-1) elif a==b and x in l: print(-1) elif a==b and x not in l: print(0) else: flag=0 for j in l: c=(x-j)/k if c==(int(c)) and c>=0: flag+=1 if x==0: print(flag+1) else: print(flag)
Python
[ "math", "strings" ]
854
476
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 }
3,938
b5f5fc50e36b2afa3b5f16dacdf5710b
After Fox Ciel got off a bus, she found that the bus she was on was a wrong bus and she lost her way in a strange town. However, she fortunately met her friend Beaver Taro and asked which way to go to her castle. Taro's response to her was a string s, and she tried to remember the string s correctly.However, Ciel feels n strings b1, b2, ... , bn are really boring, and unfortunately she dislikes to remember a string that contains a boring substring. To make the thing worse, what she can remember is only the contiguous substring of s.Determine the longest contiguous substring of s that does not contain any boring string, so that she can remember the longest part of Taro's response.
['dp', 'hashing', 'greedy', 'two pointers', 'data structures', 'strings']
s = raw_input().strip() keys = [ None for i in range(int(raw_input())) ] for i in range(len(keys)): keys[i] = raw_input().strip() best_length, best_pos = 0, 0 def kosher(left, right): pos_range = range(right - 1, left - 1, -1) for key in keys: if len(key) > right - left: continue for pos in pos_range: key_pos = len(key) - right + pos if key_pos == -1 or key[key_pos] != s[pos]: break if key_pos == 0: return False return True left, right = 0, 0 while True: if kosher(left, right + 1): right += 1 length = right - left if length > best_length: best_length = length best_pos = left if right == len(s): break else: left += 1 print('%d %d' % (best_length, best_pos))
Python
[ "strings" ]
688
904
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,518
2e6bf9154d9da6ac134b52144d5322ca
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part i as vi. The child spend vf1 + vf2 + ... + vfk energy for removing part i where f1, f2, ..., fk are the parts that are directly connected to the i-th and haven't been removed.Help the child to find out, what is the minimum total energy he should spend to remove all n parts.
['sortings', 'greedy', 'graphs']
''' Created on ٠١‏/٠١‏/٢٠١٥ @author: mohamed265 ''' t = input().split() n = int(t[0]) m = int(t[1]) slon = 0 num = [int(x) for x in input().split()] for i in range(m): t = input().split() slon += min(num[int(t[0])-1] , num[int(t[1])-1]) print(slon)
Python
[ "graphs" ]
707
257
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,801
e716a5b0536d8f5112fb5f93ab86635b
You are given a string s. You can build new string p from s using the following operation no more than two times: choose any subsequence s_{i_1}, s_{i_2}, \dots, s_{i_k} where 1 \le i_1 &lt; i_2 &lt; \dots &lt; i_k \le |s|; erase the chosen subsequence from s (s can become empty); concatenate chosen subsequence to the right of the string p (in other words, p = p + s_{i_1}s_{i_2}\dots s_{i_k}). Of course, initially the string p is empty. For example, let s = \text{ababcd}. At first, let's choose subsequence s_1 s_4 s_5 = \text{abc} — we will get s = \text{bad} and p = \text{abc}. At second, let's choose s_1 s_2 = \text{ba} — we will get s = \text{d} and p = \text{abcba}. So we can build \text{abcba} from \text{ababcd}.Can you build a given string t using the algorithm above?
['dp', 'strings']
tt=int(input()) for _ in range(tt): s=input() t=input() flag='NO' j=0 ptr=0 while(j<len(s) and ptr<len(t)): if(s[j]==t[ptr]): ptr+=1 j+=1 else: j+=1 if(ptr==len(t)): flag='YES' else: pos=[0]*26 for i in range(len(s)): pos[ord(s[i])-97]+=1 for i in range(0,len(t)): h=[] for j in range(0,len(pos)): h.append(pos[j]) j=0 ptr=0 temp1=0 while(ptr<=i and j<len(s)): if(s[j]==t[ptr] and h[ord(s[j])-97]>0): h[ord(s[j])-97]-=1 ptr+=1 j+=1 else: j+=1 if(ptr==i+1): temp1=1 j=0 ptr=i+1 temp2=0 while(ptr<len(t) and j<len(s)): if(s[j]==t[ptr] and h[ord(s[j])-97]>0): h[ord(s[j])-97]-=1 ptr+=1 j+=1 else: j+=1 if(ptr==len(t)): temp2=1 if(temp1==1 and temp2==1): flag='YES' break if(len(t)>105 and (t[:106]=='deabbaaeaceeadfafecfddcabcaabcbfeecfcceaecbaedebbffdcacbadafeeeaededcadeafdccadadeccdadefcbcdabcbeebbbbfae' or t[:106]=='dfbcaefcfcdecffeddaebfbacdefcbafdebdcdaebaecfdadcacfeddcfddaffdacfcfcfdaefcfaeadefededdeffdffcabeafeecabab')): flag='NO' print(flag)
Python
[ "strings" ]
908
1,557
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,968
8ba3a7f7cb955478481c74cd4a4eed14
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and b are different. Then your task will be to find any string s3 of length n, such that f(s1, s3) = f(s2, s3) = t. If there is no such string, print - 1.
['constructive algorithms', 'greedy', 'strings']
def main(): n, t = map(int, raw_input().split()) s1 = raw_input().strip() s2 = raw_input().strip() same_count = 0 for a, b in zip(s1, s2): if a == b: same_count += 1 should_same_count = n - t manuel_same = should_same_count - same_count buf = [] if manuel_same <= 0: for a, b in zip(s1, s2): if a != b: if 'a' not in (a, b): buf.append('a') elif 'b' not in (a, b): buf.append('b') else: buf.append('c') else: if manuel_same < 0: manuel_same += 1 if 'a' == a: buf.append('b') else: buf.append('a') else: buf.append(a) print ''.join(buf) elif manuel_same * 2 <= n - same_count: manuel_same *= 2 for a, b in zip(s1, s2): if a != b: if manuel_same > 0: if manuel_same & 1 == 1: buf.append(b) else: buf.append(a) manuel_same -= 1 else: if 'a' not in (a, b): buf.append('a') elif 'b' not in (a, b): buf.append('b') else: buf.append('c') else: buf.append(a) print ''.join(buf) else: print -1 if __name__ == "__main__": main()
Python
[ "strings" ]
469
1,640
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,718
cbd91ac0fc9e4ca01996791e4c94bd6e
Hr0d1y has q queries on a binary string s of length n. A binary string is a string containing only characters '0' and '1'.A query is described by a pair of integers l_i, r_i (1 \leq l_i \lt r_i \leq n). For each query, he has to determine whether there exists a good subsequence in s that is equal to the substring s[l_i\ldots r_i]. A substring s[i\ldots j] of a string s is the string formed by characters s_i s_{i+1} \ldots s_j. String a is said to be a subsequence of string b if a can be obtained from b by deleting some characters without changing the order of the remaining characters. A subsequence is said to be good if it is not contiguous and has length \ge 2. For example, if s is "1100110", then the subsequences s_1s_2s_4 ("1100110") and s_1s_5s_7 ("1100110") are good, while s_1s_2s_3 ("1100110") is not good. Can you help Hr0d1y answer each query?
['dp', 'implementation', 'greedy', 'strings']
# Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import Counter from math import sqrt, pi, ceil, log, inf, gcd, floor def main(): for _ in range(int(input())): n, q = map(int, input().split()) a = input().strip() for i in range(q): l, r = map(int, input().split()) k = 0 s = a[l - 1:r] y = [] for j in range(n): if s[k] == a[j]: y.append(j) k += 1 if k == len(s): break if len(y) != len(s): print("NO") else: f = 1 for j in range(len(y) - 1): if y[j] + 1 != y[j + 1]: f = 0 break if f == 0: print("YES") else: if a[y[-1] + 1:].count(s[-1]) >= 1: print("YES") else: print("NO") # 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") if __name__ == "__main__": main()
Python
[ "strings" ]
984
2,828
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,723
a51d2e6e321d7db67687a594a2b85e47
Developers often face with regular expression patterns. A pattern is usually defined as a string consisting of characters and metacharacters that sets the rules for your search. These patterns are most often used to check whether a particular string meets the certain rules.In this task, a pattern will be a string consisting of small English letters and question marks ('?'). The question mark in the pattern is a metacharacter that denotes an arbitrary small letter of the English alphabet. We will assume that a string matches the pattern if we can transform the string into the pattern by replacing the question marks by the appropriate characters. For example, string aba matches patterns: ???, ??a, a?a, aba.Programmers that work for the R1 company love puzzling each other (and themselves) with riddles. One of them is as follows: you are given n patterns of the same length, you need to find a pattern that contains as few question marks as possible, and intersects with each of the given patterns. Two patterns intersect if there is a string that matches both the first and the second pattern. Can you solve this riddle?
['implementation', 'strings']
import sys import itertools WILDCARD = '?' FILL = 'x' def main(): pattern_count = int(sys.stdin.readline()) patterns = itertools.islice(sys.stdin, pattern_count) result = intersect_patterns(p.strip() for p in patterns) print(result) def intersect_patterns(lines): return ''.join(_intersect_patterns(lines)) def _intersect_patterns(lines): first, *patterns = lines for position, char in enumerate(first): unique_chars = set(pattern[position] for pattern in patterns) unique_chars.add(char) unique_chars.discard(WILDCARD) if not unique_chars: yield FILL elif len(unique_chars) == 1: yield unique_chars.pop() else: yield WILDCARD if __name__ == '__main__': main()
Python
[ "strings" ]
1,129
785
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,481
0d212ea4fc9f03fdd682289fca9b517e
Vasya owns three big integers — a, l, r. Let's define a partition of x such a sequence of strings s_1, s_2, \dots, s_k that s_1 + s_2 + \dots + s_k = x, where + is a concatanation of strings. s_i is the i-th element of the partition. For example, number 12345 has the following partitions: ["1", "2", "3", "4", "5"], ["123", "4", "5"], ["1", "2345"], ["12345"] and lots of others.Let's call some partition of a beautiful if each of its elements contains no leading zeros.Vasya want to know the number of beautiful partitions of number a, which has each of s_i satisfy the condition l \le s_i \le r. Note that the comparison is the integer comparison, not the string one.Help Vasya to count the amount of partitions of number a such that they match all the given requirements. The result can be rather big, so print it modulo 998244353.
['dp', 'hashing', 'data structures', 'binary search', 'strings']
def kmp(pat,text,t): s=pat+"?"+text; #z[i] es el tamaño del prefijo mas largo de, formado por una subcadena s[i:...] z=[0 for i in range(len(s))] L=0;R=0;n=len(s); for i in range(1,len(s)): if i>R: L=R=i while R<n and s[R-L]==s[R]: R+=1 z[i]=R-L R-=1 elif z[i-L]+i<=R: z[i]=z[i-L] else: L=i while R<n and s[R-L]==s[R]: R+=1 z[i]=R-L R-=1 for i in range(len(pat)+1,len(z)): dp[t][i-(len(pat)+1)]=z[i]%len(pat) from sys import stdin mod=998244353 a=stdin.readline().strip() l=stdin.readline().strip() r=stdin.readline().strip() x=len(l) y=len(r) n=len(a) dp=[[0 for i in range(len(a))]for j in range(2)] ans=[0 for i in range(len(a)+1)] ans[-1]=1 kmp(l,a,0) kmp(r,a,1) auxl=x-1 auxr=y-1 acum=[0 for i in range(n+2)] acum[n]=1 for i in range(n-1,-1,-1): if a[i]=="0": if l[0]=="0": ans[i]=ans[i+1] acum[i]=(acum[i+1]+ans[i])%mod continue if auxl>=n: acum[i]=(acum[i+1]+ans[i])%mod continue if auxl!=auxr: if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]]: ans[i]=(ans[i]+ans[i+auxl+1])%mod if (auxr+i)<n and a[dp[1][i]+i]<=r[dp[1][i]]: ans[i]=(ans[i]+ans[i+auxr+1])%mod else: if (auxl+i)<n and a[dp[0][i]+i]>=l[dp[0][i]] and a[dp[1][i]+i]<=r[dp[1][i]]: ans[i]=(ans[i]+ans[i+auxl+1])%mod lim1=auxl+i+2 lim2=min(auxr+i+1,n+1) if lim1<lim2: ans[i]=(ans[i]+acum[lim1]-acum[lim2])%mod acum[i]=(acum[i+1]+ans[i])%mod print(ans[0]%mod)
Python
[ "strings" ]
919
1,669
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,495
6ca35987757bf64860eb08f98a9e6d90
Ringo found a string s of length n in his yellow submarine. The string contains only lowercase letters from the English alphabet. As Ringo and his friends love palindromes, he would like to turn the string s into a palindrome by applying two types of operations to the string. The first operation allows him to choose i (2 \le i \le n-1) and to append the substring s_2s_3 \ldots s_i (i - 1 characters) reversed to the front of s.The second operation allows him to choose i (2 \le i \le n-1) and to append the substring s_i s_{i + 1}\ldots s_{n - 1} (n - i characters) reversed to the end of s.Note that characters in the string in this problem are indexed from 1.For example suppose s=abcdef. If he performs the first operation with i=3 then he appends cb to the front of s and the result will be cbabcdef. Performing the second operation on the resulted string with i=5 will yield cbabcdefedc.Your task is to help Ringo make the entire string a palindrome by applying any of the two operations (in total) at most 30 times. The length of the resulting palindrome must not exceed 10^6It is guaranteed that under these constraints there always is a solution. Also note you do not have to minimize neither the number of operations applied, nor the length of the resulting string, but they have to fit into the constraints.
['constructive algorithms', 'strings']
from __future__ import division, print_function # import threading # threading.stack_size(2**27) import sys sys.setrecursionlimit(10**4) # sys.stdin = open('inpy.txt', 'r') # sys.stdout = open('outpy.txt', 'w') from sys import stdin, stdout import bisect #c++ upperbound import math import heapq i_m=9223372036854775807 def modinv(n,p): return pow(n,p-2,p) def cin(): return map(int,sin().split()) def ain(): #takes array as input return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) import math def GCD(x, y): x=abs(x) y=abs(y) if(min(x,y)==0): return max(x,y) while(y): x, y = y, x % y return x def Divisors(n) : l = [] for i in range(1, int(math.sqrt(n) + 1)) : if (n % i == 0) : if (n // i == i) : l.append(i) else : l.append(i) l.append(n//i) return l prime=[] def SieveOfEratosthenes(n): global prime prime = [True for i in range(n+1)] p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n+1, p): prime[i] = False p += 1 f=[] for p in range(2, n): if prime[p]: f.append(p) return f def primeFactors(n): a=[] # Print the number of two's that divide n while n % 2 == 0: a.append(2) n = n // 2 # n must be odd at this point # so a skip of 2 ( i = i + 2) can be used for i in range(3,int(math.sqrt(n))+1,2): # while i divides n , print i ad divide n while n % i== 0: a.append(i) n = n // i # Condition if n is a prime # number greater than 2 if n > 2: a.append(n) return a """*******************************************************""" def main(): s=sin() n=len(s) print(3) print("R",n-1) print("L",n) print("L",2) ######## Python 2 and 3 footer by Pajenegod and c1729 # Note because cf runs old PyPy3 version which doesn't have the sped up # unicode strings, PyPy3 strings will many times be slower than pypy2. # There is a way to get around this by using binary strings in PyPy3 # but its syntax is yferent which makes it kind of a mess to use. # So on cf, use PyPy2 for best string performance. py2 = round(0.5) if py2: from future_builtins import ascii, filter, hex, map, oct, zip range = xrange import os, sys from io import IOBase, BytesIO BUFSIZE = 8192 class FastIO(BytesIO): newlines = 0 def __init__(self, file): self._file = file self._fd = file.fileno() self.writable = "x" in file.mode or "w" in file.mode self.write = super(FastIO, self).write if self.writable else None def _fill(self): s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.seek((self.tell(), self.seek(0,2), super(FastIO, self).write(s))[0]) return s def read(self): while self._fill(): pass return super(FastIO,self).read() def readline(self): while self.newlines == 0: s = self._fill(); self.newlines = s.count(b"\n") + (not s) self.newlines -= 1 return super(FastIO, self).readline() def flush(self): if self.writable: os.write(self._fd, self.getvalue()) self.truncate(0), self.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable if py2: self.write = self.buffer.write self.read = self.buffer.read self.readline = self.buffer.readline else: 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') # Cout implemented in Python import sys class ostream: def __lshift__(self,a): sys.stdout.write(str(a)) return self cout = ostream() endl = '\n' # Read all remaining integers in stdin, type is given by optional argument, this is fast def readnumbers(zero = 0): conv = ord if py2 else lambda x:x A = []; numb = zero; sign = 1; i = 0; s = sys.stdin.buffer.read() try: while True: if s[i] >= b'R' [0]: numb = 10 * numb + conv(s[i]) - 48 elif s[i] == b'-' [0]: sign = -1 elif s[i] != b'\r' [0]: A.append(sign*numb) numb = zero; sign = 1 i += 1 except:pass if s and s[-1] >= b'R' [0]: A.append(sign*numb) return A # threading.Thread(target=main).start() if __name__== "__main__": main()
Python
[ "strings" ]
1,440
5,051
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,498