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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6608fadf1677e5cb78b6ed092a23777 | One of Timofey's birthday presents is a colourbook in a shape of an infinite plane. On the plane n rectangles with sides parallel to coordinate axes are situated. All sides of the rectangles have odd length. Rectangles cannot intersect, but they can touch each other.Help Timofey to color his rectangles in 4 different colors in such a way that every two rectangles touching each other by side would have different color, or determine that it is impossible.Two rectangles intersect if their intersection has positive area. Two rectangles touch by sides if there is a pair of sides such that their intersection has non-zero length The picture corresponds to the first example | ['geometry'] | '''plan
noticed that if both upperle
'''
from sys import stdin, stdout
# n = int(stdin.readline().rstrip())
# n = int(input())
all_lines = stdin.read().split('\n')
stdout.write('YES\n')
for line in all_lines[1:-1]:
x1, y1, x2, y2 = (int(x) % 2 for x in line.split())
num = 2 * x2 + y2 + 1
# stdout.write(str(x2) + ' ' + str(y2) + '\n')
stdout.write(str(num) + '\n')
#stdout.flush()
#exit()
# for i in range(n):
# coordinates.append([int(x) % 2 for x in input().split()])
# for i in range(n):
# coordinates.append([int(x) % 2 for x in stdin.readline().rstrip().split()])
# stdout.write('YES\n')
# for coordinate in coordinates:
# x1, y1, x2, y2 = coordinate
# stdout.write(str(2 * x2 + y2 + 1) + '\n')
| Python | [
"geometry"
] | 678 | 740 | 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,474 |
c90c7a562c8221dd428c807c919ae156 | Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first n olympiads the organizers introduced the following rule of the host city selection.The host cities of the olympiads are selected in the following way. There are m cities in Berland wishing to host the olympiad, they are numbered from 1 to m. The host city of each next olympiad is determined as the city that hosted the olympiad the smallest number of times before. If there are several such cities, the city with the smallest index is selected among them.Misha's mother is interested where the olympiad will be held in some specific years. The only information she knows is the above selection rule and the host cities of the first n olympiads. Help her and if you succeed, she will ask Misha to avoid flooding your house. | ['two pointers', 'implementation', 'sortings', 'data structures', 'binary search', 'trees'] | class seg:
def __init__(self, n):
self.n = n
m = 1
while m < n: m *= 2
self.m = m
self.data = [0]*(2 * m)
def add(self, ind):
ind += self.m
while ind:
self.data[ind] += 1
ind >>= 1
def binary(self,k):
ind = 1
while ind < self.m:
ind <<= 1
if self.data[ind] < k:
k -= self.data[ind]
ind |= 1
return ind - self.m
# This mergesort can be like 7 times faster than build in sort
# (for stupid reasons)
def mergesort(n, key, reverse=False):
A = list(range(n))
B = list(A)
n = len(A)
for i in range(0, n - 1, 2):
if key(A[i]) > key(A[i ^ 1]):
A[i], A[i ^ 1] = A[i ^ 1], A[i]
width = 2
while width < n:
for i in range(0, n, 2 * width):
R1, R2 = min(i + width, n), min(i + 2 * width, n)
j, k = R1, i
while i < R1 and j < R2:
if key(A[i]) > key(A[j]):
B[k] = A[j]
j += 1
else:
B[k] = A[i]
i += 1
k += 1
while i < R1:
B[k] = A[i]
k += 1
i += 1
while k < R2:
B[k] = A[k]
k += 1
A, B = B, A
width *= 2
if reverse:
A.reverse()
return A
def main():
n, m, q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
hosts = [0.0]*m
for a in A:
hosts[a-1] += 1.0
order = mergesort(m, hosts.__getitem__)
years = []
s = 0.0
for before,i in enumerate(order):
years.append(before * hosts[i] - s)
s += hosts[i]
big = 1000000000000
big -= big % m
bigf = float(big)
def mapper(x):
if len(x) <= 12:
return float(x)
return (int(x) % m) + bigf
B = [mapper(x) - n - 1 for x in sys.stdin.buffer.read().split()]
qorder = mergesort(q, B.__getitem__, reverse=True)
ans = [0]*q
segg = seg(m)
for before,i in enumerate(order):
segg.add(i)
while qorder and (before == m-1 or years[before + 1] > B[qorder[-1]]):
qind = qorder.pop()
q = int((B[qind] - years[before]) % (before + 1))
ans[qind] = segg.binary(q + 1) + 1
print '\n'.join(str(x) for x in ans)
######## 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 different 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()
# 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'0' [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'0' [0]:
A.append(sign*numb)
return A
if __name__== "__main__":
main() | Python | [
"trees"
] | 1,044 | 5,385 | 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
} | 206 |
9640b7197bd7b8a59f29aecf104291e1 | A string is called square if it is some string written twice in a row. For example, the strings "aa", "abcabc", "abab" and "baabaa" are square. But the strings "aaa", "abaaab" and "abcdabc" are not square.For a given string s determine if it is square. | ['implementation', 'strings'] | n = int(input())
m = []
for i in range(n):
a = input()
m.append(a)
for j in m:
if len(j) == 1:
print('NO')
else:
b = len(j) // 2
if len(j) % 2 == 0:
if j[:b] == j[b:]:
print('YES')
else:
print('NO')
else:
print('NO')
| Python | [
"strings"
] | 258 | 364 | 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,054 |
ea011f93837fdf985f7eaa7a43e22cc8 | Let's define a function f(x) (x is a positive integer) as follows: write all digits of the decimal representation of x backwards, then get rid of the leading zeroes. For example, f(321) = 123, f(120) = 21, f(1000000) = 1, f(111) = 111.Let's define another function g(x) = \dfrac{x}{f(f(x))} (x is a positive integer as well).Your task is the following: for the given positive integer n, calculate the number of different values of g(x) among all numbers x such that 1 \le x \le n. | ['constructive algorithms', 'number theory', 'math'] | from sys import stdin, stdout
readline, writeline = stdin.readline, stdout.write
def iint():
return int(readline().strip())
for _ in range(iint()):
n = readline().strip()
writeline("{}\n".format(len(n)))
| Python | [
"number theory",
"math"
] | 558 | 220 | 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,989 |
1df8aad60e5dff95bffb9adee5f8c460 | One warm and sunny day king Copa decided to visit the shooting gallery, located at the Central Park, and try to win the main prize — big pink plush panda. The king is not good at shooting, so he invited you to help him.The shooting gallery is an infinite vertical plane with Cartesian coordinate system on it. The targets are points on this plane. Each target is described by it's coordinates xi, and yi, by the time of it's appearance ti and by the number pi, which gives the probability that Copa hits this target if he aims at it.A target appears and disappears instantly, so Copa can hit the target only if at the moment ti his gun sight aimed at (xi, yi). Speed of movement of the gun sight on the plane is equal to 1. Copa knows all the information about the targets beforehand (remember, he is a king!). He wants to play in the optimal way, which maximizes the expected value of the amount of hit targets. He can aim at any target at the moment 0. | ['dp', 'probabilities'] | import heapq
def is_reachable(from_state, target):
return (from_state[0]-target[0])**2 + (from_state[1]-target[1])**2 <= (target[2] - from_state[2])**2
num_iter = int(input())
targets = sorted([list(map(float, input().strip().split(' '))) for dummy in range(0, num_iter)], key=lambda single_target: single_target[2])
states = []
for i, target in enumerate(targets):
score_estimate = target[3]
sorted_states = heapq.nlargest(len(states), states)
for j in range(len(sorted_states)):
if is_reachable(sorted_states[j][1], target):
score_estimate += sorted_states[j][1][3]
break;
target[3] = score_estimate
heapq.heappush(states, (score_estimate, target))
max_score = heapq.nlargest(1, states)[0][1][3]
print(max_score)
| Python | [
"probabilities"
] | 954 | 780 | 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
} | 2,113 |
bf89bc12320f635cc121eba99c542444 | The only difference with E2 is the question of the problem..Vlad built a maze out of n rooms and n-1 bidirectional corridors. From any room u any other room v can be reached through a sequence of corridors. Thus, the room system forms an undirected tree.Vlad invited k friends to play a game with them.Vlad starts the game in the room 1 and wins if he reaches a room other than 1, into which exactly one corridor leads.Friends are placed in the maze: the friend with number i is in the room x_i, and no two friends are in the same room (that is, x_i \neq x_j for all i \neq j). Friends win if one of them meets Vlad in any room or corridor before he wins.For one unit of time, each participant of the game can go through one corridor. All participants move at the same time. Participants may not move. Each room can fit all participants at the same time. Friends know the plan of a maze and intend to win. Vlad is a bit afraid of their ardor. Determine if he can guarantee victory (i.e. can he win in any way friends play).In other words, determine if there is such a sequence of Vlad's moves that lets Vlad win in any way friends play. | ['dfs and similar', 'greedy', 'shortest paths', 'trees', 'two pointers'] | # RANK1ZEN; 3966 PEAK NA FLEX SUPPORT; Battlenet ID: Knuckles#11791
# region -----------------------------------------------------------------------------------------|
# oooo+oshdy+/smooyNMNNMMMmo/::----/dNsomMMMNNMy/::--::/mNoodNdmdo/:-://////::::::::.
# ooooyNMMMyssNyosmMMMMMMNs+::----::++//+oooooo/::----:/ys+oNNdMMo/:-/+mmdy+///::::::.
# ooooNMMMdyoNdoosNmmdyhyo/::------:::::::::::::-------::::/+++so/:::/+dMMNhydosso+///.``````
# oo/yNmMms+oyo///++///:::::-.------------------------------::::::::-:/odmNhyNsdMNmmy+/......
# o//oooo+/-:::::::::::::::---------------------.---------------:::-.::://+++yohMMMMNs+-.....
# +:::::::--::::::::::--::-.-::::::::----------.-:----:-----------:---:-::::::/ohhNMNo+-.....
# ::::::::.-:::::::::-:::-`.:::::::::-:::::::----::::::--::::::-::::d:---::::::://+os//-`.`..
# --------.:::::::--:::::. -::::::::--::::::--o/:::::::-::::::::::-yNs-:.::::::::::::::-..`..
# --------.:-::::-::::::- `::::::::-:::::::-:ym:::::::-:::::::::::+NMN+---:::::::::::::-.....
# --------.-----::::::::. .:://///::////:::+dMy//////:////////:::/mMMMm/:-:::::::::::::--....
# --------.----:::::::::``://////:///////+yNMM+++++//++++/////://hmmNNNd::-::::::::::::--....
# --------.----::::::::-``://++//+++++++ymmNMd+oo+++ooo++++++/++dNmdhhhys:-::::::::::::-:`...
# --------.----::::::::-``//++//++++++hNMMMMMoso++ooooooooo++o+dmNNNMMMMMm+://:::::://::/....
# --------:----::::::::-``////++++++/--+smNNhsooosssssoooo+oosmNMMMMMMMMMMN///////////-:/....
# -------/o-----:::::::-``://+++:. :NMydhohhooosssssssso+osodMNMNhyssyyhdmMo++++++++++./+....
# -------sd-----:::::::-`.:/oo/.://.-hddMMh+ossssssssss+soyNms/.` `:- ` `:++++/++++/ /+-.-.
# -------ym/-----:::::::/shhyh:/ymddo./mdysssssssssoyyossmMMh- .mMhdNds:ooo/ooooo- ++---.
# -------hhy----------:-sNNNNmhysyssoyysssoossssoshmyosdMMMMs ..///`-hysMMh/oo/ooooo/ `oo----
# ----`-..od/---::::::::oNNNNNNNNmdysoooooooooyhmNdsymMMMMMMm:/oydds+:ymmMhoo+oooooo` `oo----
# ----``- `-.---:::::::+dddddhyo++++oooosyhmNMNhshNMMMMMMMMMNmmhhyo+sydNmoo++ooooo. -oo----
# ----- `` ----:::::::ooooooosssyhhdNNNMMNdyydNMMmMMMMMMMMNNNNmNmmmNmmoohsoooo+. :++.---
# -----. `----:::::-mNNNNmNNMMMMMMMNmdhhdNMMMMMMMMMMMMMMNMNNmNmmmmmhshs:ooo/` `/+:----
# ------` .::::::::-yMMMMNNNNmmddhyhdNNMMMMMMMMMMMMMMMMMMMMNNNNNmmNh+-`/o+- .//--::-
# .------` -::-::::::osssssyhhdmNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMh` -/-` ://--::-
# `.-----` ---------yNNNMMMMMMMMNNmmmmmmNNNMMMMMMMMMMMMMMMMMMMMMh. `. . `:::--::-
# /` `-----` `--:-----+MMMMMMMMMMMh++++++++ooosyhNMMMMMMMMMMMMMMMy` `- -::--::::
# o+. `.---` `-::-----mMMMMMMMMMMNy+ssyyyyso++/+dMMMMMMMMMMMMMN+` -. .:::-:::::
# -//-` `.--.` `-------oMMMMMMMMMMMMNmdddmmmmmhdNMMMMMMMMMMMMmo. `:. `:::-::::::
# :-``` `..` .------ymNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNmy/` -:. -:::-::::::
# ooo+//:-.` ` .-----:ddddmNMMMMMMMMMMMMMMMMMMMMMMMNho:` -::` .///-:::::::
# oooooo+++- `-:::-+ddddhddmNMMMMMMMMMMMMMMNdy+-` `-:::` `////-:::::::
# oooooo++: .::::.+dddddddhddmmMMMMNds+-` `.-:::::` `/+++-::::::::
# oooooo+: `:/// `sdmddddddddhdy-` .-::::::::: /ooo/-::::::/:
# ----..../hNMMMMNNNmyyhdddyhmmmmdddmmmmmmmNmy- `.-+hmdsmmNmmmmhydmmmhs/.+NNNMh-...------:/+y
# --....+mMMMMMNNNmyydmmhosddmmdoyhymmmmmmmm+``-/shmmhsddmmmmmmmdsydmmmmmyodNNMNy.`...----:+s
# -...omMMNNNNNNNyydmhyosdmmmmyohs/hmmmmmmm/-:ohmmNmhymhsdmmmsddmdhsddmmdhhdNNMMMNs-`....-:+o
# ..+dMNNNmdmmmhshhyys:hdmmmdohdyymNNmmmmmmdddmmmhsdommmohdmmdohddddshdmmmmdhmMMMMMNh/....:/o
# :dNdNNNmmdydsyysyy+sdysdmssddsdNNNmmmmdmmmdmmm:.-hdmddhoddddd+hddddsyddmmmmhhdNMMMMMd+.`-/o
# NNy+Nmmmmmdoyyhy/+hdmddh+shdsdNNmmmmhydds:hmm:``.ydmmddyoddddh+ysdddyyddddmdddyhdmNMMMNy//o
# +.`ommmmmh+yhhs+ydddddh-+ydohmNNmmmyyhs-`-mmo``..ymmmmmdssdddm+yysdddsshddddddddhyydNMMMMNd
# ``-mmmmmy/ydyoyddmdddy.-yhoydhmmmmohs-```+Nd.....smNmmdddosdddh:h+yddhssdddddddddmdhydmNMMM
# `.dNmmmoshysydmdddddy.`+dysdhsNNd/+-..```hNs.....+mmmmyhdd+sddm/hohshhhoydddhddddmmmmdyhNMM
# `yNmmmsysoyddmmdddmd.`.hdomhsmNd-``.``.:-mN:``..`.mmmmmddddoodm+hoddsyhdohddsoydmmmmmmmhhMM
# +NNNmsooysosddmddddo``:mohNodNm-````.-+o:Nm. -`.``smmmmmmmmmo:s/oodmdsydd/ohdh+/shmmmmmmdNM
# NNmhyosoy+hdddddddd...oh/Nh+Nm:````-+oso:md`-o/```-mmmmmmmmmmh:`-/ddhdyymy.-odmy/:odmddmNNM
# yoo+yhdmhydmdddmddy`::hosNohNs```./oymNd:mh`shs/. `smmdsmmmmmNm/-`+s+/syymo`.:ymNs-/yy+dNMM
# y/ooNNNm+/ydddmmmdh-/sd/dN+dN-`./ohmMMMN/my:NMMmy:`.hds+:odNNNNy`/-.-.-/++m/`.-/dNh--+//mMM
# :`:/so+:.:dmmmmmmmdo:hy+NN/mh.-+ohmmmddd:y+oNMMMMmy/:hs/+.-+hNN/-Nmy:...../d-``-:smh....oMM
# ` ---..``-mmmmmmmdyy.y+yNN.d/ohmNNNNmmdd+o-:oodMMMMNy/y::+.`.:o`yMMMmh+:...:/```--+dy..-/mM
# - ---.-h+.dmmmmmdmho++/dMm -`:/:://ososy+/:oNNNMMMMMMmos-:/-. `+ymNNmdhy+:-` ..`-:/ho.-+hM
# -`---:mMd-dmmmmmdmmms/`++- ./-++hmMMMMMMMMNs+.s+-` ``.-/syhhso+:.````::/o.-+yN
# -`-:-:NMMssmmmmmmdmmNh+./-.-`. `` /-..:-sMMMMMMMMMMMMd:ohyo:.`-//:--:+yhhs/-.` .:::.-+yh
# /-./:-+NMm-dmmdddddmmmmho-om- ://s+ /Nddmmo:MMMMMMMMMMMMMh``-::/:.`-osyyso.:.-:...-:....+sy
# :-.:/:-/Nm-+mmmmddddmmmmmhosy.ssy++yNMMMMMN/mMMMMMMMMMMMy.` .. -yNNmy....::.`:-.-``/hM
# `-::-+mmohmmmddddddddmmmdy+yNMMMMMMMMMMMdoNNNNNNNNMMMy`.`.. sd: `+MNo.--.`://`..---`-hM
# :::-.` ``:dMyymmmdddddddddddddysymNMMMMMMMMNyodmdmmmmNNNy/oo::.oMMmhdmy-...:.`:/:`-//:-``hM
# `` `...-oy:ymmmhsddddddddhdhyysyhmNMMMNNNmyddddsydmmNNhhyshNMMMMMN+.``:.`.`:/-://///:.:y
# .://:..-:-.`yNNd+-ohdddddddho+ssssshmNNNNmmdddh`-ydmNNMMMMMMMMMMh-...`.:- :://::///:/ss
# ./++/--::`:-. `hNNm+`.odmmmdddhsosyso+osdNNNmmmmh`.hmNMMMMMMMMMMMs..---.`.-. -.-::::-:/+yh
# -+///--:::`---. .dNNN+ -sdmdmdddhyshNdy+/ohNNNmdy:yNNMMMMMMMMMMN+..--:::::-. .--`.-//-:+yd
# /::::`-:::-`-`/ `-mMMm-` .ohmmdddddysdNNho/+ymdhdMMMMMMMMMMMMMN/..---:::::/:-:-..`.----:yd
# h:::-``.----`.:``.+NNNo`` -/yddmmdddyyNMMdo-oNMMMMMMMMMMMMMMd:.----::::::/-:///:.``..``:y
# Ms---.`...--.:.`:o:mMNd``` -//:osshdddyoyNNNy`sMMMMMMMMMMMMNs..---:::::::/::////+:` :/:--.
# sNh/-.````` .`./oo/yNMN-``` :+++/:+/:ydddo+dmNy-MMMMMMMMMNdo-.---:::::::://:///+++/ ./++o+
# -omMh/. ./++++:hNNN: `` :oooo+///./hddoyNMN/MMMMMNmy+-.---::::::://///////+++/.. ./+oyh
# `-:smmo:+o+osss+/:-mNNs` ` `///+ooo+-: -hmm/dMMsMNho/-.---:::::::///////////+++/--/+`/++oys
# endregion---------------------------------------------------------------------------------------|
import sys
from heapq import *
from bisect import *
from collections import *
from math import ceil, floor, log, sqrt, gcd
mod = 1000000007
mod9 = 998244353
MX = 200003
nl = "\n"
def file_io():
sys.stdin = open(r"", "r")
sys.stdout = open(r"", "w")
def re(data=str): return data(sys.stdin.readline().rstrip())
def mp(data=str): return map(data, sys.stdin.readline().split())
def solve(tc):
re()
n, k = mp(int)
x = list(mp(int))
G = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = mp(int)
G[u - 1].append(v - 1)
G[v - 1].append(u - 1)
Q = deque([])
colour = [0] * n
def bfs(start):
for i in x:
Q.append(i - 1)
colour[i - 1] = 2
Q.append(0)
colour[0] = 1
while (Q):
cur = Q.popleft()
for nxt in G[cur]:
if not colour[nxt]:
colour[nxt] = colour[cur]
Q.append(nxt)
bfs(0)
for i in range(1, n):
if len(G[i]) == 1 and colour[i] == 1:
print("YES"); return
print("NO")
return None
def main():
# file_io()
tests = 1; tests = re(int)
for tc in range(1, tests + 1): solve(tc)
if __name__ == "__main__":
main()
| Python | [
"graphs",
"trees"
] | 1,202 | 7,908 | 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,272 |
8da703549a3002bf9131d6929ec026a2 | Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is a non-empty string of length not more than 10, consisting of lowercase English letters, and pricei (the price of the i-th purchase) is a non-empty string, consisting of digits and dots (decimal points). It is possible that purchases with equal names have different prices.The price of each purchase is written in the following format. If the price is an integer number of dollars then cents are not written.Otherwise, after the number of dollars a dot (decimal point) is written followed by cents in a two-digit format (if number of cents is between 1 and 9 inclusively, there is a leading zero).Also, every three digits (from less significant to the most) in dollars are separated by dot (decimal point). No extra leading zeroes are allowed. The price always starts with a digit and ends with a digit.For example: "234", "1.544", "149.431.10", "0.99" and "123.05" are valid prices, ".333", "3.33.11", "12.00", ".33", "0.1234" and "1.2" are not valid. Write a program that will find the total price of all purchases in the given bill. | ['implementation', 'expression parsing', 'strings'] | #import resource
#import sys
#resource.setrlimit(resource.RLIMIT_STACK, [0x100000000, resource.RLIM_INFINITY])
#import threading
#threading.stack_size(2**26)
#sys.setrecursionlimit(0x1000000)
from sys import stdin, stdout
mod=(10**9)+7
mod1=mod-1
def modinv(n,p):
return pow(n,p-2,p)
fact=[1]
for i in range(1,100001):
fact.append((fact[-1]*i)%mod)
def ncr(n,r,p):
t=((fact[n])*(modinv(fact[r],p)%p)*(modinv(fact[n-r],p)%p))%p
return t
def GCD(x, y):
while(y):
x, y = y, x % y
return x
def BS(arr, l, r, x):
if r >= l:
mid = l + (r - l)/2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return BS(arr, l, mid-1, x)
else:
return BS(arr, mid+1, r, x)
else:n -1
from bisect import bisect_left as bl
from bisect import bisect_right as br
import itertools
import math
import heapq
from random import randint as rn
from Queue import Queue as Q
def comp(x,y):
if(x[0]<y[0]):
return -1
elif(x[0]==y[0]):
if(x[1]<y[1]):
return -1
else:
return 1
else:
return 1
def find(x):
if(p[x]!=x):
p[x]=find(p[x])
return p[x]
def union(x,y):
m=find(x)
n=find(y)
if(m!=n):
s[0]-=1
if(r[m]>r[n]):
p[n]=m
elif(r[n]>r[m]):
p[m]=n
else:
p[n]=m
r[m]+=1
"""*********************************************************************************"""
a=raw_input()
d=[]
i=0
while(i<len(a)):
if(a[i].isdigit()==True):
h=i
while(h<len(a) and (a[h].isdigit()==True or a[h]==".")):
h+=1
k=a[i:h]
if(len(k)>2):
if(k[-3]=="."):
r=k[-2]+k[-1]
p=len(r)
r=int(r)/float(pow(10,p))
u=1
w=0
for j in range(-4,-len(k)-1,-1):
if(k[j].isdigit()==True):
w+=int(k[j])*u
u*=10
w+=r
d.append(w)
else:
u=1
w=0
for j in range(-1,-len(k)-1,-1):
if(k[j].isdigit()==True):
w+=int(k[j])*u
u*=10
d.append(w)
else:
d.append(int(k))
i+=len(k)
else:
i+=1
r=str(sum(d))
k=[]
if(len(r)>=2 and r[-2]=="." and r[-1]=="0"):
r=r[:len(r)-2]
elif(len(r)>=2 and r[-2]=="."):
k.append("0")
k.append(r[-1])
k.append(".")
r=r[:len(r)-2]
elif(len(r)>=3 and r[-3]=="."):
k.append(r[-1])
k.append(r[-2])
k.append(".")
r=r[:len(r)-3]
h=0
for i in range(-1,-len(r)-1,-1):
k.append(r[i])
h+=1
if(h%3==0 and i!=(-len(r))):
k.append(".")
k=k[::-1]
print "".join(k)
| Python | [
"strings"
] | 1,356 | 2,856 | 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,656 |
607e670403a40e4fddf389caba79607e | You are given two integers a and b. Moreover, you are given a sequence s_0, s_1, \dots, s_{n}. All values in s are integers 1 or -1. It's known that sequence is k-periodic and k divides n+1. In other words, for each k \leq i \leq n it's satisfied that s_{i} = s_{i - k}.Find out the non-negative remainder of division of \sum \limits_{i=0}^{n} s_{i} a^{n - i} b^{i} by 10^{9} + 9.Note that the modulo is unusual! | ['number theory', 'math', 'matrices'] | n, a, b, k = [int(i) for i in input().split()]
st = input()
l = (n + 1) // k
s = 0
mod = 1000000009
def f_pow(a, k):
if k == 0:
return 1
if k % 2 == 1:
return f_pow(a, k - 1) * a % mod
else:
return f_pow(a * a % mod, k // 2) % mod
def rev(b):
return f_pow(b, mod - 2)
q = f_pow(b, k) * rev(f_pow(a, k))
qn = f_pow(q, l)
rq = rev(q - 1)
g1 = f_pow(a, n)
ra = rev(a)
for i in range(len(st)):
sgn = 1 - 2 * (st[i] == '-')
res = g1 * (qn - 1) * rq
if (q % mod) != 1:
s = (s + sgn * res) % mod
else:
s = (s + sgn * g1 * l) % mod
g1 = g1 * ra * b % mod
print(s)
| Python | [
"math",
"number theory"
] | 490 | 645 | 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,892 |
2022f53e5a88d5833e133dc3608a122c | A class of students wrote a multiple-choice test.There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.The students remember what answers they gave on the exam, but they don't know what are the correct answers. They are very optimistic, so they want to know what is the maximum possible total score of all students in the class. | ['implementation', 'strings'] | stu_ex = input().split(" ")
student, exam = [int(a) for a in stu_ex]
ans = [[0, 0, 0, 0, 0] for i in range(0, exam)]
#print(ans)
for i in range(0, student):
std_ans = input()
for j in range(0, exam):
choose = 0
if std_ans[j] == 'B':
choose = 1
elif std_ans[j] == 'C':
choose = 2
elif std_ans[j] == 'D':
choose = 3
elif std_ans[j] == 'E':
choose = 4
ans[j][choose] += 1
score = [int(a) for a in input().split(" ")]
max_score = 0
for i in range(0, exam):
max_score += score[i] * max(ans[i])
print(max_score)
| Python | [
"strings"
] | 574 | 615 | 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,885 |
ad02cead427d0765eb642203d13d3b99 | You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string a. String a should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string s). By all other words you should build string b in the same way (the order of numbers should remain the same as in the string s).Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.For example, for the string aba,123;1a;0 the string a would be equal to "123,0" and string b would be equal to "aba,1a". | ['implementation', 'strings'] | s = input()
a = s.replace(';', ',').split(',')
c, d = [], []
for elem in a:
if elem.isdigit() and (elem[0] != '0' or len(elem) == 1):
c.append(elem)
else:
d.append(elem)
if (len(c) == 0):
print('-')
#print('"' + ','.join(c) + '"')
print('"' + ','.join(d) + '"')
elif (len(d) == 0):
print('"' + ','.join(c) + '"')
#print('"' + ','.join(d) + '"')
print('-')
else:
print('"' + ','.join(c) + '"')
print('"' + ','.join(d) + '"') | Python | [
"strings"
] | 910 | 492 | 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,790 |
14b65af01caf1f3971a2f671589b86a8 | Generous sponsors of the olympiad in which Chloe and Vladik took part allowed all the participants to choose a prize for them on their own. Christmas is coming, so sponsors decided to decorate the Christmas tree with their prizes. They took n prizes for the contestants and wrote on each of them a unique id (integer from 1 to n). A gift i is characterized by integer ai — pleasantness of the gift. The pleasantness of the gift can be positive, negative or zero. Sponsors placed the gift 1 on the top of the tree. All the other gifts hung on a rope tied to some other gift so that each gift hung on the first gift, possibly with a sequence of ropes and another gifts. Formally, the gifts formed a rooted tree with n vertices.The prize-giving procedure goes in the following way: the participants come to the tree one after another, choose any of the remaining gifts and cut the rope this prize hang on. Note that all the ropes which were used to hang other prizes on the chosen one are not cut. So the contestant gets the chosen gift as well as the all the gifts that hang on it, possibly with a sequence of ropes and another gifts.Our friends, Chloe and Vladik, shared the first place on the olympiad and they will choose prizes at the same time! To keep themselves from fighting, they decided to choose two different gifts so that the sets of the gifts that hang on them with a sequence of ropes and another gifts don't intersect. In other words, there shouldn't be any gift that hang both on the gift chosen by Chloe and on the gift chosen by Vladik. From all of the possible variants they will choose such pair of prizes that the sum of pleasantness of all the gifts that they will take after cutting the ropes is as large as possible.Print the maximum sum of pleasantness that Vladik and Chloe can get. If it is impossible for them to choose the gifts without fighting, print Impossible. | ['dp', 'dfs and similar', 'trees', 'graphs'] | from collections import defaultdict
#import sys
#sys.setrecursionlimit(3*10**5)
n = int(raw_input())
A = [0]+map(int, raw_input().split())
AdjOf = [ [] for x in xrange(n+5)]
for i in xrange(n-1):
u,v = map(int, raw_input().split())
AdjOf[u].append(v)
AdjOf[v].append(u)
ChildrenOf = [ [] for x in xrange(n+5)]#defaultdict(list)
Seen = [0] * (n+5)
que = [1]*n
dq,cq = 0,0
while dq<=cq:
u = que[dq]
dq+=1
Seen[u]=1
for v in AdjOf[u]:
if Seen[v]<1:
ChildrenOf[u].append(v)
cq+=1
que[cq]=v
NINF = -10**16
TakeSum = [NINF] * (n+5)
BestSum = [NINF]* (n+5)
ans = NINF
for x in que[::-1]:
if len(ChildrenOf[x])<1:
TakeSum[x] = A[x]
BestSum[x] = A[x]
continue
TakeSum[x]=A[x]
#for c in ChildrenOf[x]:
# TakeSum[x] += TakeSum[c]
BestSum[x] = NINF
fi,se = NINF, NINF
for c in ChildrenOf[x]:
TakeSum[x] += TakeSum[c]
BestSum[x] = max(BestSum[x], BestSum[c])
if BestSum[c]>fi:
se,fi = fi, BestSum[c]
elif BestSum[c]>se:
se = BestSum[c]
BestSum[x] = max(BestSum[x], TakeSum[x])
if fi>NINF and se>NINF:
ans = max(ans, fi+se)
"""
def takeSum(x):
global TakeSum
if len(ChildrenOf[x])<1:
TakeSum[x] = A[x]
return A[x]
if TakeSum[x]>NINF: return TakeSum[x]
TakeSum[x]=A[x]
for c in ChildrenOf[x]:
TakeSum[x] += takeSum(c)
return TakeSum[x]
def bestSum(x):
global BestSum
if len(ChildrenOf[x])<1:
BestSum[x] = A[x]
return A[x]
if BestSum[x]>NINF: return BestSum[x]
BestSum[x] = takeSum(x)
for c in ChildrenOf[x]:
if A[x]>0:
BestSum[x] = max(BestSum[x], bestSum(c))
else:
BestSum[x] = max(BestSum[x], bestSum(c))
return BestSum[x]
for u in que[::-1]:
takeSum(u)
bestSum(u)
#print TakeSum
#print BestSum
#print ChildrenOf
def getAns(bestList):
if len(bestList)<2: return NINF
fi,se = NINF, NINF
for x in bestList:
if x>fi:
se=fi
fi=x
elif x>se:
se=x
return fi+se
ans = NINF
for x in que:#[::-1]:
fi,se = NINF, NINF
bestList = [BestSum[c] for c in ChildrenOf[x] if BestSum[c]>NINF]
if len(bestList)<2: continue
fi,se = NINF, NINF
for x in bestList:
if x>fi:
se=fi
fi=x
elif x>se:
se=x
ans = max(ans, se+fi)
#if ans>NINF: break
ans = NINF
Seen = set([1])
que = [1]
dq,cq = 0,0
while dq<=cq:
u = que[dq]
dq+=1
Seen.add(u)
best=[]
for v in ChildrenOf[u]:
if v not in Seen:
que.append(v)
cq+=1
if BestSum[v]>NINF: best.append(BestSum[v])
ans = max(ans, getAns(best))
"""
print ans if ans>NINF else "Impossible"
| Python | [
"graphs",
"trees"
] | 1,892 | 2,875 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 1,346 |
43b8e9fb2bd0ec5e0250a33594417f63 | Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all.Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the maximum number of candies has b candies. Then Santa will be satisfied, if the both conditions are met at the same time: b - a \le 1 (it means b = a or b = a + 1); the number of kids who has a+1 candies (note that a+1 not necessarily equals b) does not exceed \lfloor\frac{k}{2}\rfloor (less than or equal to \lfloor\frac{k}{2}\rfloor). \lfloor\frac{k}{2}\rfloor is k divided by 2 and rounded down to the nearest integer. For example, if k=5 then \lfloor\frac{k}{2}\rfloor=\lfloor\frac{5}{2}\rfloor=2.Your task is to find the maximum number of candies Santa can give to kids so that he will be satisfied.You have to answer t independent test cases. | ['math'] | for _ in range(int(input())):
x, y = map(int, input().split())
print(x - max(0, x % y - y // 2))
| Python | [
"math"
] | 1,078 | 99 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 2,275 |
6e85f83d544eeb16f57523eb532abf04 | Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different!Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c — one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him.Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city.When rhombi are compared, the order of intersections b and d doesn't matter. | ['combinatorics', 'dfs and similar', 'brute force', 'graphs'] | from __future__ import division, print_function
import bisect
import math
import itertools
import sys
from atexit import register
if sys.version_info[0] < 3:
from io import BytesIO as stream
else:
from io import StringIO as stream
if sys.version_info[0] < 3:
class dict(dict):
"""dict() -> new empty dictionary"""
def items(self):
"""D.items() -> a set-like object providing a view on D's items"""
return dict.iteritems(self)
def keys(self):
"""D.keys() -> a set-like object providing a view on D's keys"""
return dict.iterkeys(self)
def values(self):
"""D.values() -> an object providing a view on D's values"""
return dict.itervalues(self)
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
def sync_with_stdio(sync=True):
"""Set whether the standard Python streams are allowed to buffer their I/O.
Args:
sync (bool, optional): The new synchronization setting.
"""
global input, flush
if sync:
flush = sys.stdout.flush
else:
sys.stdin = stream(sys.stdin.read())
input = lambda: sys.stdin.readline().rstrip('\r\n')
sys.stdout = stream()
register(lambda: sys.__stdout__.write(sys.stdout.getvalue()))
def main():
g=[]
n,m=map(int, input().split())
for i in range(n):
g.append([])
for j in range(m):
p,q=map(int, input().split())
g[p-1].append(q)
cnt=0
#print(g)
for i in range(n):
a=[0]*n
for j in range(len(g[i])):
for k in range(len(g[g[i][j]-1])):
a[g[g[i][j]-1][k]-1]+=1
#print(a)
for t in range(n):
if t==i:
continue
j=a[t]
if j>1:
cnt+=(((j-1)*j)//2)
print(cnt)
if __name__ == '__main__':
sync_with_stdio(False)
main() | Python | [
"math",
"graphs"
] | 1,090 | 2,037 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,953 |
eee1ad545b2c4833e871989809355baf | It is the easy version of the problem. The only difference is that in this version a_i \le 200.You are given an array of n integers a_0, a_1, a_2, \ldots a_{n - 1}. Bryap wants to find the longest beautiful subsequence in the array.An array b = [b_0, b_1, \ldots, b_{m-1}], where 0 \le b_0 < b_1 < \ldots < b_{m - 1} < n, is a subsequence of length m of the array a.Subsequence b = [b_0, b_1, \ldots, b_{m-1}] of length m is called beautiful, if the following condition holds: For any p (0 \le p < m - 1) holds: a_{b_p} \oplus b_{p+1} < a_{b_{p+1}} \oplus b_p. Here a \oplus b denotes the bitwise XOR of a and b. For example, 2 \oplus 4 = 6 and 3 \oplus 1=2.Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question. | ['bitmasks', 'brute force', 'dp', 'strings', 'trees', 'two pointers'] |
twopow = []
for i in range(19):
twopow.append(2 ** i)
twopow.reverse()
maxN = int(40e6)
trie = [0] * maxN # in segments of 6. [l, r, 00, 01, 10, 11]
for i in range(0, maxN, 6):
trie[i] = trie[i + 1] = -1 # -1 if not linked to any node
idx_of_trie = 6
def get_next_idx_of_trie():
global idx_of_trie
idx_of_trie += 6
return idx_of_trie - 6
def clear_trie():
global idx_of_trie
temp = idx_of_trie
while idx_of_trie >= 1:
idx_of_trie -= 1
trie[idx_of_trie] = 0
for i in range(0, temp, 6):
trie[i] = trie[i + 1] = -1
idx_of_trie = 6
bitmap = [(1, 0), (0, 0), (1, 1), (0, 1)]
# bitmap[ibit * 2 + aibit] = (jbit, ajbit) where j < i and (aibit ^ jbit) > (ajbit ^ ibit)
def main():
def add(i, ai):
value = i ^ ai
node = 0
currmax = 1
for tp in twopow:
if (i & tp) > 0: ibit = 1
else: ibit = 0
if (ai & tp) > 0: aibit = 1
else: aibit = 0
if (value & tp) > 0:
if trie[node + 1] == -1:
trie[node + 1] = get_next_idx_of_trie()
neighbour = trie[node]
node = trie[node + 1]
else:
if trie[node] == -1:
trie[node] = get_next_idx_of_trie()
neighbour = trie[node + 1]
node = trie[node]
if neighbour != -1:
# ai ^ j == aj ^ i right up to before this node.
# Need to find max dp for ai ^ j > aj ^ i,
# where i is current index and j is a previous index.
# for jbit in range(2):
# for ajbit in range(2):
# if (aibit ^ jbit) > (ajbit ^ ibit):
# currmax = max(currmax, 1 + neighbour.dp[jbit][ajbit])
# Casework. (aibit ^ jbit) > (ajbit ^ ibit)
jbit, ajbit = bitmap[ibit * 2 + aibit]
currmax = max(currmax, 1 + trie[neighbour + 2 + jbit * 2 + ajbit])
# update trie
node = 0
for tp in twopow:
if (i & tp) > 0: ibit = 1
else: ibit = 0
if (ai & tp) > 0: aibit = 1
else: aibit = 0
if (value & tp) > 0:
node = trie[node + 1]
else:
node = trie[node]
# node.dp[ibit][aibit] = max(node.dp[ibit][aibit], currmax)
trie[node + 2 + ibit * 2 + aibit] = max(currmax,
trie[node + 2 + ibit * 2 + aibit])
return currmax
t = int(input())
allans = []
for _ in range(t):
n = int(input())
a = readIntArr()
# testdp = [1] * n
ans = 0
for i, ai in enumerate(a):
res = add(i, ai)
# testdp[i] = res
ans = max(ans, res)
# print(testdp) # TEST
allans.append(ans)
clear_trie()
multiLineArrayPrint(allans)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
# input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(x1, x2):
print('! {} {}'.format(x1, x2))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | Python | [
"strings",
"trees"
] | 921 | 4,526 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 1
} | 2,455 |
81abcdc77ffcf8858b4e81f3db5ee7fb | You wanted to write a text t consisting of m lowercase Latin letters. But instead, you have written a text s consisting of n lowercase Latin letters, and now you want to fix it by obtaining the text t from the text s.Initially, the cursor of your text editor is at the end of the text s (after its last character). In one move, you can do one of the following actions: press the "left" button, so the cursor is moved to the left by one position (or does nothing if it is pointing at the beginning of the text, i. e. before its first character); press the "right" button, so the cursor is moved to the right by one position (or does nothing if it is pointing at the end of the text, i. e. after its last character); press the "home" button, so the cursor is moved to the beginning of the text (before the first character of the text); press the "end" button, so the cursor is moved to the end of the text (after the last character of the text); press the "backspace" button, so the character before the cursor is removed from the text (if there is no such character, nothing happens). Your task is to calculate the minimum number of moves required to obtain the text t from the text s using the given set of actions, or determine it is impossible to obtain the text t from the text s.You have to answer T independent test cases. | ['brute force', 'dp', 'greedy', 'strings'] | #!/usr/bin/env PyPy3
from collections import Counter, defaultdict, deque
import itertools
import re
import math
from functools import reduce
import operator
import bisect
from heapq import *
import functools
mod=998244353
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
INF = 1 << 31
T = int(input())
for _ in range(T):
n,m = map(int,input().split())
s = input().rstrip()
t = input().rstrip()
dp = [[INF] * (m+1) for _ in range(3)]
dp[0][0] = 1
dp[1][0] = 0
for i in range(n):
ndp = [[INF] * (m+1) for _ in range(3)]
for k in range(2):
for j in range(m+1):
dp[k+1][j] = min(dp[k+1][j],dp[k][j])
for j in range(m+1):
ndp[0][j] = min(ndp[0][j],dp[0][j] + 2)
ndp[2][j] = min(ndp[2][j],dp[2][j] + 1)
if j < m:
if s[i] == t[j]:
ndp[0][j+1] = min(ndp[0][j+1],dp[0][j]+1)
ndp[1][j+1] = min(ndp[1][j+1],dp[1][j])
ndp[2][j+1] = min(ndp[2][j+1],dp[2][j]+1)
dp = ndp
ans = min(dp[0][-1],dp[1][-1],dp[2][-1])
if ans == INF:
print(-1)
else:
print(ans)
| Python | [
"strings"
] | 1,404 | 2,897 | 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,563 |
cdf42ae9f76a36295c701b0606ea5bfc | There are n officers in the Army of Byteland. Each officer has some power associated with him. The power of the i-th officer is denoted by p_{i}. As the war is fast approaching, the General would like to know the strength of the army.The strength of an army is calculated in a strange way in Byteland. The General selects a random subset of officers from these n officers and calls this subset a battalion.(All 2^n subsets of the n officers can be chosen equally likely, including empty subset and the subset of all officers).The strength of a battalion is calculated in the following way:Let the powers of the chosen officers be a_{1},a_{2},\ldots,a_{k}, where a_1 \le a_2 \le \dots \le a_k. The strength of this battalion is equal to a_1a_2 + a_2a_3 + \dots + a_{k-1}a_k. (If the size of Battalion is \leq 1, then the strength of this battalion is 0).The strength of the army is equal to the expected value of the strength of the battalion.As the war is really long, the powers of officers may change. Precisely, there will be q changes. Each one of the form i x indicating that p_{i} is changed to x.You need to find the strength of the army initially and after each of these q updates.Note that the changes are permanent.The strength should be found by modulo 10^{9}+7. Formally, let M=10^{9}+7. It can be shown that the answer can be expressed as an irreducible fraction p/q, where p and q are integers and q\not\equiv 0 \bmod M). Output the integer equal to p\cdot q^{-1} \bmod M. In other words, output such an integer x that 0 \leq x < M and x ⋅ q \equiv p \bmod M). | ['data structures', 'divide and conquer', 'probabilities'] | import sys, os
range = xrange
input = raw_input
import __pypy__
mulmod = __pypy__.intop.int_mulmod
sub = __pypy__.intop.int_sub
mul = __pypy__.intop.int_mul
MOD = 10**9 + 7
MODINV = 1.0/MOD
def mulmod(a,b):
x = sub(mul(a,b), mul(MOD, int(a * MODINV * b)))
return x + MOD if (x < 0) else (x if x < MOD else x - MOD)
#precalc 2^-1 powers
invpow = pow(2, MOD - 2, MOD)
pow2 = [1]
for _ in range(3 * 10**5 + 10):
pow2.append(mulmod(pow2[-1], invpow))
# returns order such that A[order[i]] <= A[order[i + 1]]
def sqrtsorted(A, maxval = 10**9):
asqrt = int((maxval)**0.5 + 2)
blocks1 = [[] for _ in range(asqrt)]
blocks2 = [[] for _ in range(asqrt)]
for i in range(len(A)):
blocks1[A[i] % asqrt].append(i)
for block in blocks1:
for i in block:
blocks2[A[i]//asqrt].append(i)
ret = []
for block in blocks2:
ret += block
return ret
# Keeps track of expected power using the structure of the segment tree
class segtree:
def __init__(self, data, counter):
n = len(data)
m = 1
while m < n: m *= 2
self.m = m
self.dataL = [0]*(m+m)
self.dataR = [0]*(m+m)
self.counter = [0]*(m+m)
self.power = 0
self.dataL[m:m+n] = data
self.dataR[m:m+n] = data
self.counter[m:m+n] = counter
for ind in reversed(range(1,m)):
self.counter[ind] = self.counter[ind << 1] + self.counter[(ind << 1) + 1]
self.dataL[ind] = (mulmod(self.dataL[ind << 1], pow2[self.counter[(ind << 1) + 1]]) + self.dataL[(ind << 1) + 1] ) % MOD
self.dataR[ind] = (self.dataR[ind << 1] + mulmod(self.dataR[(ind << 1) + 1], pow2[self.counter[ind << 1]]) ) % MOD
self.power = (self.power + mulmod(self.dataL[ind << 1], self.dataR[(ind << 1) + 1]) ) % MOD
# Keeps track of expected power when the segment tree is modified
def add(self, ind, val, c = 1):
ind += self.m
while ind > 1:
self.counter[ind] += c
self.power = self.power - mulmod(self.dataL[ind & ~1], self.dataR[ind | 1])
# If first time
if ind >= self.m:
self.dataL[ind] = val
self.dataR[ind] = val
else:
self.dataL[ind] = (mulmod(self.dataL[ind << 1], pow2[self.counter[(ind << 1) + 1]]) + self.dataL[(ind << 1) + 1] ) % MOD
self.dataR[ind] = (self.dataR[ind << 1] + mulmod(self.dataR[(ind << 1) + 1], pow2[self.counter[ind << 1]]) ) % MOD
self.power = (self.power + mulmod(self.dataL[ind & ~1], self.dataR[ind | 1]) ) % MOD
ind >>= 1
def rem(self, ind):
self.add(ind, 0, -1)
def get_power(self):
return mulmod(self.power, pow2[2])
#############
### READ INPUT
inp = [int(x) for x in os.read(0, os.fstat(0).st_size).split()]; ii = 0
n = inp[ii]; ii += 1
# Order all involved powers
values = inp[ii: ii + n] + inp[ii + n + 2:: 2]
order = sqrtsorted(values)
invorder = [-1]*len(order)
for i in range(len(order)):
invorder[order[i]] = i
# Initialize the seg tree containing powers
P = inp[ii: ii + n]; ii += n
who = list(range(n))
##############
### POPULATE SEGTREE
power = 0
data = [0]*len(order)
counter = [0]*len(order)
for i in range(n):
data[invorder[i]] = P[i]
counter[invorder[i]] = 1
seg = segtree(data, counter)
##############
### SOLVE QUERIES
import __pypy__
out = __pypy__.builders.StringBuilder()
q = inp[ii]; ii += 1
out.append(str(seg.get_power()))
out.append('\n')
for _ in range(q):
i = inp[ii] - 1; ii += 1
x = inp[ii]; ii += 1
# Remove power at who[i]
ind = invorder[who[i]]
seg.rem(ind)
# Add new power at i
ind = invorder[n + _]
who[i] = n + _
seg.add(ind, x)
out.append(str(seg.get_power()))
out.append('\n')
os.write(1, out.build()) | Python | [
"probabilities"
] | 1,739 | 3,978 | 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
} | 3,323 |
ffdd1de4be537234e8a0e7127bec43a7 | While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).The gift bundle also includes a square scoop of size r × r, designed for fishing. If the lower-left corner of the scoop-net is located at cell (x, y), all fishes inside the square (x, y)...(x + r - 1, y + r - 1) get caught. Note that the scoop-net should lie completely inside the pond when used.Unfortunately, Sasha is not that skilled in fishing and hence throws the scoop randomly. In order to not frustrate Sasha, Misha decided to release k fishes into the empty pond in such a way that the expected value of the number of caught fishes is as high as possible. Help Misha! In other words, put k fishes in the pond into distinct cells in such a way that when the scoop-net is placed into a random position among (n - r + 1)·(m - r + 1) possible positions, the average number of caught fishes is as high as possible. | ['greedy', 'graphs', 'probabilities', 'shortest paths', 'data structures'] | import heapq as hq
from queue import PriorityQueue
import math
n,m,r, k= input().split()
N = int(n)
M = int(m)
R = int(r)
K = int(k)
q = PriorityQueue()
for i in range(1,math.floor((N+1)/2) + 1):
maxi = min(min(i,N-i+1),min(R,N-R+1)) * min(min(R,M-R+1),math.ceil(M/2))
num = M - (2 * min(min(R,M-R+1),math.ceil(M/2))-2)
mult = 2
if(i > math.floor(N/2)):
mult = 1
q.put((-maxi,num * mult,i))
#print(str(maxi) + " " + str(num) + " " + str(mult))
ans = 0
while(K > 0):
pop = q.get()
#print(pop)
a = -1 * pop[0]
b = pop[1]
c = pop[2]
d = min(min(c,N-c+1),min(R,N-R+1))
if(d != a):
# if(q.)
# if(q.get(-(a - d)) != )
mult = 2
if (c > N / 2):
mult = 1
q.put((-(a - d),2*mult,c))
ans += a * min(b,K)
K -= b;
tot = (N-R+1) * (M-R+1)
#print("ANS = " + str(ans))
#print("FINANS = " + str(ans/tot))
print(str(ans/tot))
'''
d = []
for i in range(0,N):
d.append([])
for j in range(0,M):
d[i].append(0)
tot = 0
for i in range(0,N-R+1):
for j in range(0,M-R+1):
for k in range(i,i+R):
for l in range(j,j+R):
d[k][l] += 1
tot += 1
print((N-R+1)*(M-R+1) * (R*R))
print(tot)
print()
for i in d:
print(i)
'''
| Python | [
"graphs",
"probabilities"
] | 1,055 | 1,299 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 702 |
3d38584c3bb29e6f84546643b1be8026 | This is an interactive task.Dasha and NN like playing chess. While playing a match they decided that normal chess isn't interesting enough for them, so they invented a game described below.There are 666 black rooks and 1 white king on the chess board of size 999 \times 999. The white king wins if he gets checked by rook, or, in other words, if he moves onto the square which shares either a row or column with a black rook.The sides take turns, starting with white. NN plays as a white king and on each of his turns he moves a king to one of the squares that are adjacent to his current position either by side or diagonally, or, formally, if the king was on the square (x, y), it can move to the square (nx, ny) if and only \max (|nx - x|, |ny - y|) = 1 , 1 \leq nx, ny \leq 999. NN is also forbidden from moving onto the squares occupied with black rooks, however, he can move onto the same row or column as a black rook.Dasha, however, neglects playing by the chess rules, and instead of moving rooks normally she moves one of her rooks on any space devoid of other chess pieces. It is also possible that the rook would move onto the same square it was before and the position wouldn't change. However, she can't move the rook on the same row or column with the king.Each player makes 2000 turns, if the white king wasn't checked by a black rook during those turns, black wins. NN doesn't like losing, but thinks the task is too difficult for him, so he asks you to write a program that will always win playing for the white king. Note that Dasha can see your king and play depending on its position. | ['constructive algorithms', 'games', 'interactive'] | import sys
kx, ky = [int(z) for z in sys.stdin.readline().split()]
lx = [0] * 667
ly = [0] * 667
bp = []
for i in range(1001):
bp.append([0 for z in range(1001)])
for i in range(1, 667):
lx[i], ly[i] = [int(z) for z in sys.stdin.readline().split()]
bp[lx[i]][ly[i]] = 1
los = [0] * 4
for i in range(1, 667):
sta = 0
if lx[i] > kx:
sta += 1
if ly[i] > ky:
sta += 2
los[sta] += 1
tkx, tky = 500, 500
ntut = False
stnse = True
while True:
if kx == tkx and ky == tky:
ntut = True
if ntut:
sos = [0, 1, 2, 3]
sos.sort(key=lambda z: los[z])
tkx = (1 - sos[0] % 2) * 998 + 1
tky = (1 - sos[0] // 2) * 998 + 1
ntut = False
stnse = False
dkx = 0
dky = 0
if tkx > kx:
dkx = 1
elif tkx < kx:
dkx = -1
if tky > ky:
dky = 1
elif tky < ky:
dky = -1
if bp[kx+dkx][ky+dky] == 1:
dky = 0
kx += dkx
ky += dky
print(kx, ky, flush=True)
l, nlx, nly = [int(z) for z in sys.stdin.readline().split()]
soa = l + nlx + nly
if soa == 0 or soa == -3:
exit(0)
if stnse:
std = 0
if lx[l] > kx:
std += 1
if ly[l] > ky:
std += 2
sta = 0
if nlx > kx:
sta += 1
if nly > ky:
sta += 2
los[std] -= 1
los[sta] += 1
bp[lx[l]][ly[l]] = 0
bp[nlx][nly] = 1
lx[l] = nlx
ly[l] = nly
| Python | [
"games"
] | 1,653 | 1,484 | 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,882 |
328291f7ef1de8407d8167a1881ec2bb | You are given a simple connected undirected graph, consisting of n vertices and m edges. The vertices are numbered from 1 to n.A vertex cover of a graph is a set of vertices such that each edge has at least one of its endpoints in the set.Let's call a lenient vertex cover such a vertex cover that at most one edge in it has both endpoints in the set.Find a lenient vertex cover of a graph or report that there is none. If there are multiple answers, then print any of them. | ['dfs and similar', 'divide and conquer', 'dsu', 'graphs', 'trees'] | input = __import__('sys').stdin.readline
DFS_IN = 0
DFS_OUT = 1
def solve():
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for _ in range(m):
u, v = map(lambda x: int(x)-1, input().split())
adj[u].append(v)
adj[v].append(u)
cnt_odd = 0
dfs_in = [0]*n
dfs_out = [0]*n
depth = [0]*n + [-1]
color = [-1]*n + [1]
removed_back_edge = None
dp = [[0]*2 for _ in range(n+1)]
i = 0
stack = [(0, -1, DFS_IN)]
while len(stack) > 0:
i += 1
u, par, state = stack.pop()
if state == DFS_IN:
if color[u] != -1:
continue
dfs_in[u] = i
color[u] = color[par]^1
depth[u] = depth[par] + 1
stack.append((u, par, DFS_OUT))
for v in adj[u]:
if color[v] == -1:
stack.append((v, u, DFS_IN))
elif depth[v] - depth[u] not in (-1, 1) and depth[u] > depth[v]:
# back edge
if color[u] == color[v]:
if removed_back_edge is None:
removed_back_edge = (u, v)
else:
removed_back_edge = (n, n)
parity = color[u] ^ color[v] ^ 1
dp[u][parity] += 1
dp[v][parity] -= 1
cnt_odd += parity
if state == DFS_OUT:
dfs_out[u] = i
# update dp
dp[par][0] += dp[u][0]
dp[par][1] += dp[u][1]
color.pop()
if removed_back_edge is None or removed_back_edge != (n, n):
# remove back edge if possible
xor = 1 if removed_back_edge is not None and (color[removed_back_edge[0]], color[removed_back_edge[1]]) == (0, 0) else 0
print('YES')
print(''.join(str(x ^ xor) for x in color))
return
# try removing a span edge
invert_node = next((u for u in range(1, n) if dp[u][1] == cnt_odd and dp[u][0] == 0), None)
if invert_node is None:
print('NO')
return
xor = color[invert_node]
xor_subtree = lambda u: dfs_in[invert_node] <= dfs_in[u] <= dfs_out[invert_node]
print('YES')
print(''.join(str(x ^ (1 if xor_subtree(u) else 0) ^ xor) for u, x in enumerate(color)))
for _ in range(int(input())):
solve() | Python | [
"graphs",
"trees"
] | 498 | 2,527 | 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,165 |
c412a489a0bd2327a46f1e47a78fd03f | You are given a tree (a connected acyclic undirected graph) of n vertices. Vertices are numbered from 1 to n and each vertex is assigned a character from a to t.A path in the tree is said to be palindromic if at least one permutation of the labels in the path is a palindrome.For each vertex, output the number of palindromic paths passing through it. Note: The path from vertex u to vertex v is considered to be the same as the path from vertex v to vertex u, and this path will be counted only once for each of the vertices it passes through. | ['data structures', 'bitmasks', 'trees', 'divide and conquer'] | import sys
range = xrange
input = raw_input
def centroid_decomp(coupl):
n = len(coupl)
bfs = [n - 1]
for node in bfs:
bfs += coupl[node]
for nei in coupl[node]:
coupl[nei].remove(node)
size = [0] * n
for node in reversed(bfs):
size[node] = 1 + sum(size[child] for child in coupl[node])
def centroid_reroot(root):
N = size[root]
while True:
for child in coupl[root]:
if size[child] > N // 2:
size[root] = N - size[child]
coupl[root].remove(child)
coupl[child].append(root)
root = child
break
else:
return root
bfs = [n - 1]
for node in bfs:
centroid = centroid_reroot(node)
bfs += coupl[centroid]
yield centroid
inp = sys.stdin.read().split(); ii = 0
n = int(inp[ii]); ii += 1
coupl = [[] for _ in range(n)]
for _ in range(n - 1):
u = int(inp[ii]) - 1; ii += 1
v = int(inp[ii]) - 1; ii += 1
coupl[u].append(v)
coupl[v].append(u)
A = [1 << ord(c) - ord('a') for c in inp[ii]]; ii += 1
palistates = [0] + [1 << i for i in range(20)]
ans = [0.0] * n
dp = [0.0] * n
val = [0] * n
counter = [0] * (1 << 20)
for centroid in centroid_decomp(coupl):
bfss = []
for root in coupl[centroid]:
bfs = [root]
for node in bfs:
bfs += coupl[node]
bfss.append(bfs)
for node in bfs:
val[node] ^= A[node]
for child in coupl[node]:
val[child] = val[node]
entire_bfs = [centroid]
for bfs in bfss:
entire_bfs += bfs
for node in entire_bfs:
val[node] ^= A[centroid]
counter[val[node]] += 1
for bfs in bfss:
for node in bfs:
counter[val[node]] -= 1
for node in bfs:
v = val[node] ^ A[centroid]
for p in palistates:
dp[node] += counter[v ^ p]
for node in bfs:
counter[val[node]] += 1
for node in reversed(entire_bfs):
dp[node] += sum(dp[child] for child in coupl[node])
dp[centroid] += 1
for p in palistates:
dp[centroid] += counter[p]
dp[centroid] //= 2
for node in entire_bfs:
ans[node] += dp[node]
counter[val[node]] = val[node] = 0
dp[node] = 0.0
print ' '.join(str(int(x)) for x in ans)
| Python | [
"trees"
] | 544 | 2,496 | 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,426 |
bc375e27bd52f413216aaecc674366f8 | Berland, 2016. The exchange rate of currency you all know against the burle has increased so much that to simplify the calculations, its fractional part was neglected and the exchange rate is now assumed to be an integer.Reliable sources have informed the financier Anton of some information about the exchange rate of currency you all know against the burle for tomorrow. Now Anton knows that tomorrow the exchange rate will be an even number, which can be obtained from the present rate by swapping exactly two distinct digits in it. Of all the possible values that meet these conditions, the exchange rate for tomorrow will be the maximum possible. It is guaranteed that today the exchange rate is an odd positive integer n. Help Anton to determine the exchange rate of currency you all know for tomorrow! | ['greedy', 'math', 'strings'] | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# pylint: disable=C0111
def main():
n = list(raw_input().strip())
maxswap = (0, -1)
for x in xrange(len(n) - 2, -1, -1):
if int(n[x]) % 2 == 0:
if maxswap[0] == 0 or (int(n[-1]) - int(n[x]) > 0):
maxswap = (int(n[-1]) - int(n[x]), x)
if maxswap[1] != -1:
x = maxswap[1]
n[x], n[-1] = n[-1], n[x]
print ''.join(n)
else:
print -1
main()
| Python | [
"math",
"strings"
] | 808 | 475 | 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,072 |
d638f524fe07cb8e822b5c6ec3fe8216 | You are given an array a consisting of n integers.Let's call a pair of indices i, j good if 1 \le i < j \le n and \gcd(a_i, 2a_j) > 1 (where \gcd(x, y) is the greatest common divisor of x and y).Find the maximum number of good index pairs if you can reorder the array a in an arbitrary way. | ['brute force', 'greedy', 'math', 'number theory', 'sortings'] | from math import gcd
for _ in range(int(input())):
n = int(input())
cnt = 0
seq = tuple(map(int, input().split()))
for i in range(n):
for j in range(i + 1, n):
a, b = seq[i], seq[j]
if gcd(a, 2 * b) > 1 or gcd(b, a * 2) > 1:
cnt += 1
print(cnt)
| Python | [
"math",
"number theory"
] | 356 | 330 | 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,774 |
79ee1ff924432a184d8659db5f960304 | You are given a tree G with n vertices and an integer k. The vertices of the tree are numbered from 1 to n.For a vertex r and a subset S of vertices of G, such that |S| = k, we define f(r, S) as the size of the smallest rooted subtree containing all vertices in S when the tree is rooted at r. A set of vertices T is called a rooted subtree, if all the vertices in T are connected, and for each vertex in T, all its descendants belong to T.You need to calculate the sum of f(r, S) over all possible distinct combinations of vertices r and subsets S, where |S| = k. Formally, compute the following: \sum_{r \in V} \sum_{S \subseteq V, |S| = k} f(r, S), where V is the set of vertices in G.Output the answer modulo 10^9 + 7. | ['combinatorics', 'dfs and similar', 'dp', 'math', 'trees'] | import sys
sys.setrecursionlimit(300000)
import faulthandler
faulthandler.enable()
n, k = map(int, input().split())
MOD = 10**9 + 7
fact = [1 for i in range(n+1)]
for i in range(2, n+1):
fact[i] = i*fact[i-1] % MOD
inv_fact = [1 for i in range(n+1)]
inv_fact[-1] = pow(fact[-1], MOD-2, MOD)
for i in range(1, n):
inv_fact[n-i] = (n-i+1)*inv_fact[n-i+1] % MOD
def comb(a, b):
if a < b:
return 0
return fact[a]*inv_fact[b]*inv_fact[a-b] % MOD
edges = [[] for i in range(n)]
for _ in range(n-1):
x, y = map(lambda a: int(a)-1, input().split())
edges[x].append(y)
edges[y].append(x)
ends = [[] for i in range(n)]
visited = [0 for i in range(n)]
totals = [1 for i in range(n)]
dfs_stack = [0]
while len(dfs_stack) > 0:
node = dfs_stack[-1]
if visited[node] == 1:
visited[node] = 2
for next_node in edges[node]:
if visited[next_node] == 2:
totals[node] += totals[next_node]
ends[node].append(totals[next_node])
ends[node].append(n-totals[node])
dfs_stack.pop()
else:
visited[node] = 1
for next_node in edges[node]:
if visited[next_node] == 0:
dfs_stack.append(next_node)
z = n*n * comb(n, k) % MOD
node_v = [0 for i in range(n)]
for i in range(n):
node_v[i] = sum(comb(e, k) for e in ends[i]) % MOD
for e in ends[i]:
z = (z - e*e * (comb(n-e, k) + comb(e, k) - node_v[i])) % MOD
print(z) | Python | [
"math",
"graphs",
"trees"
] | 872 | 1,408 | 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,168 |
d1c53bd1359efa662604d55176d8af75 | Once upon a time in the galaxy of far, far away...Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star.When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — space mines. Let's describe a space mine's build.Each space mine is shaped like a ball (we'll call it the mine body) of a certain radius r with the center in the point O. Several spikes protrude from the center. Each spike can be represented as a segment, connecting the center of the mine with some point P, such that (transporting long-spiked mines is problematic), where |OP| is the length of the segment connecting O and P. It is convenient to describe the point P by a vector p such that P = O + p.The Death Star is shaped like a ball with the radius of R (R exceeds any mine's radius). It moves at a constant speed along the v vector at the speed equal to |v|. At the moment the rebels noticed the Star of Death, it was located in the point A.The rebels located n space mines along the Death Star's way. You may regard the mines as being idle. The Death Star does not know about the mines' existence and cannot notice them, which is why it doesn't change the direction of its movement. As soon as the Star of Death touched the mine (its body or one of the spikes), the mine bursts and destroys the Star of Death. A touching is the situation when there is a point in space which belongs both to the mine and to the Death Star. It is considered that Death Star will not be destroyed if it can move infinitely long time without touching the mines.Help the rebels determine whether they will succeed in destroying the Death Star using space mines or not. If they will succeed, determine the moment of time when it will happen (starting from the moment the Death Star was noticed). | ['geometry'] | import math
inf = float('inf')
ax,ay,az,vx,vy,vz,R=map(int,raw_input().split())
n=input()
t=inf
def check(ox,oy,oz,r):
x,y,z=ax-ox,ay-oy,az-oz
a=vx**2+vy**2+vz**2
b=2*(x*vx+y*vy+z*vz)
c=x**2+y**2+z**2-r**2
d=b*b-4*a*c
if d<0: return
x1=(-b+d**0.5)/a/2
x2=(-b-d**0.5)/a/2
global t
if x1>=0: t=min(t,x1)
if x2>=0: t=min(t,x2)
for i in xrange(n):
ox,oy,oz,r,m = map(int,raw_input().split())
check(ox,oy,oz,r+R)
for j in xrange(m):
rx,ry,rz = map(int,raw_input().split())
check(rx+ox,ry+oy,rz+oz,R)
print -1 if t==inf else "%.20f"%t
| Python | [
"geometry"
] | 1,897 | 555 | 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,387 |
cc4cdcd162a83189c7b31a68412f3fe7 | You are given a string s consisting of n lowercase Latin letters. n is even.For each position i (1 \le i \le n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every position must be changed exactly once.For example, letter 'p' should be changed either to 'o' or to 'q', letter 'a' should be changed to 'b' and letter 'z' should be changed to 'y'.That way string "codeforces", for example, can be changed to "dpedepqbft" ('c' \rightarrow 'd', 'o' \rightarrow 'p', 'd' \rightarrow 'e', 'e' \rightarrow 'd', 'f' \rightarrow 'e', 'o' \rightarrow 'p', 'r' \rightarrow 'q', 'c' \rightarrow 'b', 'e' \rightarrow 'f', 's' \rightarrow 't').String s is called a palindrome if it reads the same from left to right and from right to left. For example, strings "abba" and "zz" are palindromes and strings "abca" and "zy" are not.Your goal is to check if it's possible to make string s a palindrome by applying the aforementioned changes to every position. Print "YES" if string s can be transformed to a palindrome and "NO" otherwise.Each testcase contains several strings, for each of them you are required to solve the problem separately. | ['implementation', 'strings'] | t = int(input())
for _ in range(t):
n = int(input())
s = input()
ans = True
for i in range(n // 2):
if abs(ord(s[i]) - ord(s[n - i - 1])) not in (0, 2):
ans = False
break
print('YES' if ans else 'NO')
| Python | [
"strings"
] | 1,394 | 254 | 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,516 |
882deb8385fb175b4547f43b1eb01fc6 | You are given an array a of n integers and a set B of m positive integers such that 1 \leq b_i \leq \lfloor \frac{n}{2} \rfloor for 1\le i\le m, where b_i is the i-th element of B. You can make the following operation on a: Select some x such that x appears in B. Select an interval from array a of size x and multiply by -1 every element in the interval. Formally, select l and r such that 1\leq l\leq r \leq n and r-l+1=x, then assign a_i:=-a_i for every i such that l\leq i\leq r. Consider the following example, let a=[0,6,-2,1,-4,5] and B=\{1,2\}: [0,6,-2,-1,4,5] is obtained after choosing size 2 and l=4, r=5. [0,6,2,-1,4,5] is obtained after choosing size 1 and l=3, r=3. Find the maximum \sum\limits_{i=1}^n {a_i} you can get after applying such operation any number of times (possibly zero). | ['dp', 'greedy', 'number theory'] | from __future__ import division, print_function
import os,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
from bisect import bisect_left as lower_bound, bisect_right as upper_bound
def so(): return int(input())
def st(): return input()
def mj(): return map(int,input().strip().split(" "))
def msj(): return list(map(str,input().strip().split(" ")))
def le(): return list(map(int,input().split()))
def rc(): return map(float,input().split())
def lebe():return list(map(int, input()))
def dmain():
sys.setrecursionlimit(1000000)
threading.stack_size(1024000)
thread = threading.Thread(target=main)
thread.start()
def joro(L):
return(''.join(map(str, L)))
def decimalToBinary(n): return bin(n).replace("0b","")
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def npr(n, r):
return factorial(n) // factorial(n - r) if n >= r else 0
def ncr(n, r):
import math as my
return my.factorial(n) // (my.factorial(r) * my.factorial(n - r)) if n >= r else 0
def lower_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] >= num:
answer = middle
end = middle - 1
else:
start = middle + 1
return answer # min index where x is not less than num
def upper_bound(li, num):
answer = -1
start = 0
end = len(li) - 1
while (start <= end):
middle = (end + start) // 2
if li[middle] <= num:
answer = middle
start = middle + 1
else:
end = middle - 1
return answer # max index where x is not greater than num
def tir(a,b,c):
if(0==c):
return 1
if(len(a)<=b):
return 0
if(c!=-1):
return (tir(a,1+b,c+a[b]) or tir(a,b+1,c-a[b]) or tir(a,1+b,c))
else:
return (tir(a,1+b,a[b]) or tir(a,b+1,-a[b]) or tir(a,1+b,-1))
hoi=int(2**20)
def abs(x):
return x if x >= 0 else -x
def binary_search(li, val, lb, ub):
# print(lb, ub, li)
ans = -1
while (lb <= ub):
mid = (lb + ub) // 2
# print('mid is',mid, li[mid])
if li[mid] > val:
ub = mid - 1
elif val > li[mid]:
lb = mid + 1
else:
ans = mid # return index
break
return ans
def kadane(x): # maximum sum contiguous subarray
sum_so_far = 0
current_sum = 0
for i in x:
current_sum += i
if current_sum < 0:
current_sum = 0
else:
sum_so_far = max(sum_so_far, current_sum)
return sum_so_far
def pref(li):
pref_sum = [0]
for i in li:
pref_sum.append(pref_sum[-1] + i)
return pref_sum
def gosa(a,b):
if(b==0):
return a
else:
return gosa(b,a%b)
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
li = []
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
for p in range(2, len(prime)):
if prime[p]:
li.append(p)
return li
def primefactors(n):
factors = []
while (n % 2 == 0):
factors.append(2)
n //= 2
for i in range(3, int(sqrt(n)) + 1, 2): # only odd factors left
while n % i == 0:
factors.append(i)
n //= i
if n > 2: # incase of prime
factors.append(n)
return factors
def read():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
def tr(n):
return n*(n+1)//2
boi=int(1e9-7)
doi=int(1e9+7)
hoi=int(100+1e6)
y="Yes"
n="No"
x=[0]*hoi
y=[0]*hoi
def cal(jp,op,u):
re=0
te=1
while(te<=op):
z=0
p=int(2e9)
ad=0
for i in range(te,jp+1,op):
if(0>x[i]):
z=z^1
ad=abs(x[i])+ad
p=min(abs(x[i]),p)
if(0!=z^u):
ad=-2*p+ad
re=ad+re
te=1+te
return re
def iu():
import sys
import math as my
input=sys.stdin.readline
from collections import deque, defaultdict
jp,kp=mj()
L=le()
M=le()
for i in range(1+jp):
x[i]=L[i-1]
op=0
for i in range(1+kp):
y[i]=M[i-1]
op=gosa(y[i],op)
opp=max(cal(jp,op,0),cal(jp,op,1))
print(opp)
def main():
for i in range(so()):
iu()
# region fastio
# template taken from https://github.com/cheran-senthil/PyRival/blob/master/templates/template.py
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__":
#read()
main()
#dmain()
# Comment Read() | Python | [
"number theory"
] | 1,007 | 8,209 | 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,938 |
96ec983bfadc9e96e36ebb8ffc5279d3 | This is an interactive problem.The jury has a permutation p of length n and wants you to guess it. For this, the jury created another permutation q of length n. Initially, q is an identity permutation (q_i = i for all i).You can ask queries to get q_i for any i you want. After each query, the jury will change q in the following way: At first, the jury will create a new permutation q' of length n such that q'_i = q_{p_i} for all i. Then the jury will replace permutation q with pemutation q'. You can make no more than 2n queries in order to quess p. | ['dfs and similar', 'interactive', 'math'] | import sys
t = int(input())
for _ in range(t):
n = int(input())
p = [0] * n
todo = {j for j in range(1, n + 1)}
while todo:
x = todo.pop()
todo.add(x)
st, ls = set(), []
while True:
print('?', x)
sys.stdout.flush()
y = int(input())
if y in st:
break
else:
st.add(y)
ls.append(y)
if len(ls) == 1:
p[x - 1] = x
todo.remove(x)
else:
for j in range(len(ls)):
p[ls[j] - 1] = ls[(j + 1) % len(ls)]
for x in st:
todo.remove(x)
print('!', ' '.join(map(str, p)))
sys.stdout.flush() | Python | [
"graphs",
"math"
] | 664 | 732 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,640 |
f1c1d50865d46624294b5a31d8834097 | There are n players sitting at a round table. All of them have s cards of n colors in total. Besides, initially the first person had cards of only the first color, the second one had cards of only the second color and so on. They can swap the cards by the following rules: as the players swap, a player can give a card of his color only; a player can't accept a card of a color he already has (particularly, he can't take cards of his color, no matter whether he has given out all of them or not); during one swap a pair of people swaps cards (each person gives one card and takes one card). The aim of all n people is as follows: each of them should give out all the cards he had initially (that is, all cards of his color). Your task is to denote whether such sequence of swaps is possible. If the answer is positive, you should list all the swaps. | ['constructive algorithms', 'greedy', 'graphs'] | from heapq import *
n, s = map(int, raw_input().split())
a = map(int, raw_input().split())
q = [(-x, i) for (i, x) in enumerate(a) if x > 0]
heapify(q)
res = []
while q:
(x, i) = heappop(q)
if -x > len(q):
print 'No'
break
for (y, j) in [heappop(q) for _ in xrange(-x)]:
res.append((i + 1, j + 1))
if y + 1: heappush(q, (y + 1, j))
else:
print 'Yes'
print len(res)
for (i, j) in res: print i, j
| Python | [
"graphs"
] | 854 | 452 | 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,342 |
7dccfaab4ed17b93a27202affa9408d4 | The nation of Panel holds an annual show called The Number Games, where each district in the nation will be represented by one contestant.The nation has n districts numbered from 1 to n, each district has exactly one path connecting it to every other district. The number of fans of a contestant from district i is equal to 2^i.This year, the president decided to reduce the costs. He wants to remove k contestants from the games. However, the districts of the removed contestants will be furious and will not allow anyone to cross through their districts. The president wants to ensure that all remaining contestants are from districts that can be reached from one another. He also wishes to maximize the total number of fans of the participating contestants.Which contestants should the president remove? | ['data structures', 'greedy', 'trees'] | import sys
# import time
def calc_result(n, k, edges):
# t1 = time.clock()
storage = [-1] * (4 * n)
storage_index = 0
lookup = [-1] * (n + 1)
for u, v in edges:
storage[storage_index] = lookup[u]
storage[storage_index + 1] = v
lookup[u] = storage_index
storage_index += 2
storage[storage_index] = lookup[v]
storage[storage_index + 1] = u
lookup[v] = storage_index
storage_index += 2
# t2 = time.clock()
nodes = [0] * (2 * (n + 1))
# t3 = time.clock()
stack = [n]
stack_pop = stack.pop
stack_append = stack.append
while stack:
index = stack_pop()
parent_index = nodes[index * 2]
t = lookup[index]
while t >= 0:
v = storage[t + 1]
t = storage[t]
if v == parent_index:
continue
nodes[v * 2] = index
stack_append(v)
# t4 = time.clock()
count = n - k
for i in xrange(n, 0, -1):
new_nodes = []
p = i * 2
abort = False
while True:
flag = nodes[p + 1]
if flag == -1:
abort = True
break
elif flag == 1:
break
new_nodes.append(p)
index = nodes[p]
if index <= 0:
break
p = index * 2
if abort:
for p in new_nodes:
nodes[p + 1] = -1
continue
c = count - len(new_nodes)
if c >= 0:
for p in new_nodes:
nodes[p + 1] = 1
count = c
if count == 0:
break
else:
for j in xrange(-c):
nodes[new_nodes[j] + 1] = -1
# t5 = time.clock()
#
# print('---t5 - t1: %s' % (t5 - t1))
# print('---t2 - t1: %s' % (t2 - t1))
# print('---t3 - t2: %s' % (t3 - t2))
# print('---t4 - t3: %s' % (t4 - t3))
# print('---t5 - t4: %s' % (t5 - t4))
result = [i for i in xrange(1, n + 1) if nodes[i * 2 + 1] != 1]
print(' '.join(map(str, result)))
def main():
sys.setcheckinterval(2147483647)
n, k = map(int, sys.stdin.readline().split())
edges = [map(int, sys.stdin.readline().split()) for _ in xrange(n - 1)]
# import random
# n, k = 1000000, 19
# edges = []
# rnd = random.Random()
# rnd.seed(1)
# t = range(1, n + 1)
# random.shuffle(t, random=rnd.random)
# for i in xrange(2, n + 1):
# j = rnd.randint(1, i - 1)
# edges.append([i, j])
calc_result(n, k, edges)
if __name__ == '__main__':
main()
| Python | [
"trees"
] | 842 | 2,657 | 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,074 |
2ae1a4d4f2e58b359c898d1ff38edb9e | There are n people sitting in a circle, numbered from 1 to n in the order in which they are seated. That is, for all i from 1 to n-1, the people with id i and i+1 are adjacent. People with id n and 1 are adjacent as well.The person with id 1 initially has a ball. He picks a positive integer k at most n, and passes the ball to his k-th neighbour in the direction of increasing ids, that person passes the ball to his k-th neighbour in the same direction, and so on until the person with the id 1 gets the ball back. When he gets it back, people do not pass the ball any more.For instance, if n = 6 and k = 4, the ball is passed in order [1, 5, 3, 1]. Consider the set of all people that touched the ball. The fun value of the game is the sum of the ids of people that touched it. In the above example, the fun value would be 1 + 5 + 3 = 9.Find and report the set of possible fun values for all choices of positive integer k. It can be shown that under the constraints of the problem, the ball always gets back to the 1-st player after finitely many steps, and there are no more than 10^5 possible fun values for given n. | ['number theory', 'math'] | from collections import Counter,defaultdict,deque
#alph = 'abcdefghijklmnopqrstuvwxyz'
#from math import factorial as fact
#import math
#tt = 1#int(input())
#total=0
#n = int(input())
#n,m,k = [int(x) for x in input().split()]
#n = int(input())
#n,m = [int(x) for x in input().split()]
def divisors(n):
i = 1
divs = []
while i*i<=n:
if n%i==0:
divs.append(i)
if i*i!=n:
divs.append(n//i)
i+=1
return divs
n = int(input())
p = divisors(n)
res = []
for el in p:
a = n//el
k = (1+n-el+1)*a//2
res.append(k)
res.sort()
print(*res)
| Python | [
"math",
"number theory"
] | 1,265 | 616 | 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
} | 466 |
bb8f933f438e2c7c091716cc42dc0060 | You are given two integers n and d. You need to construct a rooted binary tree consisting of n vertices with a root at the vertex 1 and the sum of depths of all vertices equals to d.A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. The depth of the vertex v is the length of the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. The binary tree is such a tree that no vertex has more than 2 children.You have to answer t independent test cases. | ['constructive algorithms', 'trees', 'brute force'] | import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
t=II()
for _ in range(t):
n,d=MI()
s=n*(n-1)//2
diff=s-d
if d>s:
print("NO")
continue
aa=[1]*n
l=1
for r in range(n-1,-1,-1):
if l>=r:break
if diff==0:break
to=max(r-diff,l)
aa[r]=0
aa[to]+=1
diff-=r-to
if aa[l]==1<<l:l+=1
if diff:
print("NO")
continue
#print(aa)
ans=[]
pa=1
st=1
for a in aa[1:]:
for i in range(a):
ans.append(st+i%pa)
st+=pa
pa=a
print("YES")
print(*ans)
main() | Python | [
"trees"
] | 727 | 1,081 | 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
} | 215 |
5c026adda2ae3d7b707d5054bd84db3f | Vasya has got three integers n, m and k. He'd like to find three integer points (x_1, y_1), (x_2, y_2), (x_3, y_3), such that 0 \le x_1, x_2, x_3 \le n, 0 \le y_1, y_2, y_3 \le m and the area of the triangle formed by these points is equal to \frac{nm}{k}.Help Vasya! Find such points (if it's possible). If there are multiple solutions, print any of them. | ['number theory', 'geometry'] | #Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
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")
#-------------------game starts now-----------------------------------------------------
n,m,k=map(int,input().split())
g=math.gcd(n*m,k)
d=(n*m)//g
f=k//g
#print(d,f)
if d%f!=0 and f!=2:
print("NO")
else:
j=1
l=1
copy1,copy2=n,m
ch=1
if k%2==0:
k//=2
ch=0
while k%2==0:
k//=2
if n%2==0:
n//=2
else:
m//=2
for i in range (3,int(math.sqrt(k))+1,2):
while k%i==0:
k//=i
if n%i==0:
n//=i
else:
m//=i
if k>2:
if n%k==0:
n//=k
else:
m//=k
if ch==1:
if n*2<=copy1:
n*=2
else:
m*=2
print("YES")
print("0 0")
print(0,m)
print(n,0) | Python | [
"number theory",
"geometry"
] | 410 | 2,744 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,223 |
90f08c2c8f7575330639fdd158bc8e6b | This is the harder version of the problem. In this version, 1 \le n \le 10^6 and 0 \leq a_i \leq 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problemsChristmas 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 > 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. | ['greedy', 'constructive algorithms', 'two pointers', 'number theory', 'math', 'ternary search'] | # 素因数分解
def prime_decomposition(n):
i = 2
table = []
while i * i <= n:
while n % i == 0:
n //= i
table.append(i)
i += 1
if n > 1:
table.append(n)
return table
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
# かけらを移動させて共通因数を持つようにする
su = sum(A)
if su == 1:
print(-1)
exit()
primes = sorted(set(prime_decomposition(su)))
ans = 10**18
for p in primes:
an = 0
half = p >> 1
cnt = 0
for a in A:
a %= p
cnt += a
if cnt <= half:
an += cnt
else:
if cnt < p:
an += p - cnt
else:
cnt -= p
if cnt <= half:
an += cnt
else:
an += p - cnt
if ans <= an:
break
else:
ans = min(ans, an)
print(ans)
| Python | [
"number theory",
"math"
] | 1,313 | 920 | 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
} | 525 |
0eee4b8f074e02311329d5728138c7fe | 2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a game, it is eliminated, and each game results in elimination of one team (there are no ties). After that, only 2^{k-1} teams remain. If only one team remains, it is declared the champion; otherwise, 2^{k-2} games are played: in the first one of them, the winner of the game "1 vs 2" plays against the winner of the game "3 vs 4", then the winner of the game "5 vs 6" plays against the winner of the game "7 vs 8", and so on. This process repeats until only one team remains.For example, this picture describes the chronological order of games with k = 3: Let the string s consisting of 2^k - 1 characters describe the results of the games in chronological order as follows: if s_i is 0, then the team with lower index wins the i-th game; if s_i is 1, then the team with greater index wins the i-th game; if s_i is ?, then the result of the i-th game is unknown (any team could win this game). Let f(s) be the number of possible winners of the tournament described by the string s. A team i is a possible winner of the tournament if it is possible to replace every ? with either 1 or 0 in such a way that team i is the champion.You are given the initial state of the string s. You have to process q queries of the following form: p c — replace s_p with character c, and print f(s) as the result of the query. | ['data structures', 'dfs and similar', 'dp', 'implementation', 'trees'] | import sys
def upd(ix, cur):
if s[ix] == '?':
tree[cur] = tree[cur << 1] + tree[(cur << 1) + 1]
else:
tree[cur] = tree[(cur << 1) + (int(s[ix]) ^ 1)]
input = lambda: sys.stdin.buffer.readline().decode().strip()
ispow2 = lambda x: x and (not (x & (x - 1)))
k, s = int(input()), list(input())
tree, n, out = [1] * (1 << (k + 1)), len(s), []
for i in range(len(s)):
cur = n - i
upd(i, cur)
for i in range(int(input())):
ix, ch = input().split()
ix = int(ix) - 1
cur, s[ix] = n - ix, ch
while cur:
upd(ix, cur)
cur >>= 1
ix = n - cur
out.append(tree[1])
print('\n'.join(map(str, out)))
| Python | [
"graphs",
"trees"
] | 1,855 | 695 | 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,224 |
6551be8f4000da2288bf835169662aa2 | Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.A common divisor for two positive numbers is a number which both numbers are divisible by.But your teacher wants to give you a harder task, in this task you have to find the greatest common divisor d between two integers a and b that is in a given range from low to high (inclusive), i.e. low ≤ d ≤ high. It is possible that there is no common divisor in the given range.You will be given the two integers a and b, then n queries. Each query is a range from low to high and you have to answer each query. | ['binary search', 'number theory'] | a, b = map(int, input().split())
import math
g = math.gcd(a, b)
lis = [i for i in range(1, int(math.sqrt(g)) + 1) if g%i == 0]
for i in lis[::-1]: lis.append(g//i)
n = int(input())
for _ in range(n):
a, b = map(int , input().split())
import bisect
x = bisect.bisect(lis, b) - 1
if lis[x] < a: print(-1)
else: print(lis[x])
| Python | [
"number theory"
] | 668 | 351 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,434 |
ce19cc45bbe24177155ce87dfe9d5c22 | You have an integer n. Let's define following tree generation as McDic's generation: Make a complete and full binary tree of 2^{n} - 1 vertices. Complete and full binary tree means a tree that exactly one vertex is a root, all leaves have the same depth (distance from the root), and all non-leaf nodes have exactly two child nodes. Select a non-root vertex v from that binary tree. Remove v from tree and make new edges between v's parent and v's direct children. If v has no children, then no new edges will be made. You have a tree. Determine if this tree can be made by McDic's generation. If yes, then find the parent vertex of removed vertex in tree. | ['constructive algorithms', 'implementation', 'trees'] | #!/usr/bin/python3
import array
import math
import os
import sys
DEBUG = 'DEBUG' in os.environ
def inp():
return sys.stdin.readline().rstrip()
def dprint(*value, sep=' ', end='\n'):
if DEBUG:
print(*value, sep=sep, end=end)
def solve(N, M, G):
if N == 2:
return [0, 1]
degv = [set() for _ in range(5)]
for i in range(M):
d = len(G[i])
if d == 0 or d >= 5:
return []
degv[d].add(i)
layer_vcount = 1 << (N - 1)
vs = degv[1]
levels = bytearray(M)
ans = []
for level in range(1, N):
#dprint('level', level, [x for x in levels])
#dprint('vs', vs)
#dprint('layer_vcount', layer_vcount)
if len(vs) not in (layer_vcount - 1, layer_vcount):
return []
if len(vs) == layer_vcount - 1:
if ans:
return []
if level == 1:
sp_deg_off = -1
else:
sp_deg_off = 1
else:
sp_deg_off = 0
#dprint('sp_deg_off', sp_deg_off)
ndeg = 3 if level < N - 1 else 2
us = set()
ss = set()
for v in vs:
#dprint('v', v)
levels[v] = level
p = None
for u in G[v]:
if levels[u] == 0:
if p is not None:
return []
p = u
break
#dprint(' p', p)
if p is None:
return []
deg = len(G[p])
#dprint(' deg', deg)
if deg == ndeg:
us.add(p)
elif deg == ndeg + sp_deg_off:
ss.add(p)
elif sp_deg_off == 0 and deg == ndeg + 1:
ss.add(p)
else:
return []
#dprint('us', us)
#dprint('ss', ss)
if sp_deg_off != 0:
if len(ss) != 1:
return []
(sp,) = list(ss)
ans = [sp]
us.add(sp)
if sp_deg_off == 0:
if level == N - 2:
if ss:
return []
if not ans:
li = list(us)
li.sort()
return li
if len(ss) > 1:
return []
vs = us
layer_vcount >>= 1
return ans
def main():
N = int(inp())
M = (1 << N) - 2
G = [[] for _ in range(M)]
for _ in range(M - 1):
a, b = [int(e) - 1 for e in inp().split()]
G[a].append(b)
G[b].append(a)
ans = solve(N, M, G)
print(len(ans))
if ans:
print(*[v + 1 for v in ans])
if __name__ == '__main__':
main()
| Python | [
"trees"
] | 701 | 2,731 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 1
} | 3,508 |
fead36831dbcb1c0bdf6b6965b751ad8 | Berland has a long and glorious history. To increase awareness about it among younger citizens, King of Berland decided to compose an anthem.Though there are lots and lots of victories in history of Berland, there is the one that stand out the most. King wants to mention it in the anthem as many times as possible.He has already composed major part of the anthem and now just needs to fill in some letters. King asked you to help him with this work.The anthem is the string s of no more than 105 small Latin letters and question marks. The most glorious victory is the string t of no more than 105 small Latin letters. You should replace all the question marks with small Latin letters in such a way that the number of occurrences of string t in string s is maximal.Note that the occurrences of string t in s can overlap. Check the third example for clarification. | ['dp', 'strings'] | def prefix(st):
t = 0
p = [0] * (len(st) + 1)
o = [0] * (len(st) + 1)
for i in range(2, len(st)):
while t > 0 and st[i] != st[t + 1]:
t = p[t]
if st[i] == st[t + 1]:
t += 1
p[i] = t
while t > 0:
o[t] = 1
t = p[t]
return o
s = ' ' + input()
t = ' ' + input()
o = prefix(t)
m = len(t) - 1
ans = [[0, 0] for _ in range(len(s) + 5)]
ans[0][1] = float('-inf')
for i in range(1, len(s)):
j = m
ans[i][1] = float('-inf')
for j in range(m, 0, -1):
if s[i - m + j] != '?' and s[i - m + j] != t[j]:
break
if o[j - 1]:
ans[i][1] = max(ans[i][1], ans[i - m + j - 1][1] + 1)
if j == 1:
ans[i][1] = max(ans[i][1], ans[i - m][0] + 1)
ans[i][0] = max(ans[i][1], ans[i - 1][0])
if ans[len(s) - 1][0] == 7:
print(o.count(1))
else:
print(ans[len(s) - 1][0])
| Python | [
"strings"
] | 865 | 915 | 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,694 |
e83b559d99a0a41c690c68fd76f40ed3 | Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first.There are n stacks of photos. Each stack contains exactly two photos. In each turn, a player may take only a photo from the top of one of the stacks.Each photo is described by two non-negative integers a and b, indicating that it is worth a units of happiness to Alice and b units of happiness to Bonnie. Values of a and b might differ for different photos.It's allowed to pass instead of taking a photo. The game ends when all photos are taken or both players pass consecutively.The players don't act to maximize their own happiness. Instead, each player acts to maximize the amount by which her happiness exceeds her sister's. Assuming both players play optimal, find the difference between Alice's and Bonnie's happiness. That is, if there's a perfectly-played game such that Alice has x happiness and Bonnie has y happiness at the end, you should print x - y. | ['greedy', 'games'] | p=[];s=0
for i in range(input()):
a,b,c,d=map(int,raw_input().split())
if a+b>c+d:p+=[a+b,c+d];s-=b+d
elif a>d:s+=a-d
elif b>c:s-=b-c
print s+sum(sorted(p)[1::2]) | Python | [
"games"
] | 1,137 | 166 | 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
} | 373 |
cfdbe4bd1c9438de2d871768c546a580 | You are playing some computer game. One of its levels puts you in a maze consisting of n lines, each of which contains m cells. Each cell either is free or is occupied by an obstacle. The starting cell is in the row r and column c. In one step you can move one square up, left, down or right, if the target cell is not occupied by an obstacle. You can't move beyond the boundaries of the labyrinth.Unfortunately, your keyboard is about to break, so you can move left no more than x times and move right no more than y times. There are no restrictions on the number of moves up and down since the keys used to move up and down are in perfect condition.Now you would like to determine for each cell whether there exists a sequence of moves that will put you from the starting cell to this particular one. How many cells of the board have this property? | ['shortest paths', 'graphs'] | from collections import defaultdict,deque
n,m=[int(el) for el in raw_input().split()]
r,c=[int(el) for el in raw_input().split()]
x,y=[int(el) for el in raw_input().split()]
s=['*'*(m+2)]
for i in range(n):
q=raw_input()
w='*'+q+'*'
s.append(w)
s.append('*'*(m+2))
def bfs(way):
ans=0
while len(way)!=0:
x,y,l,r=way.pop()
if visited[x-1][y]==0 and s[x-1][y]=='.':
way.append([x-1,y,l,r])
visited[x-1][y]=1
ans+=1
if visited[x+1][y]==0 and s[x+1][y]=='.':
way.append([x+1,y,l,r])
visited[x+1][y]=1
ans+=1
if visited[x][y-1]==0 and s[x][y-1]=='.' and l>0:
way.appendleft([x,y-1,l-1,r])
visited[x][y-1]=1
ans+=1
if visited [x][y+1]==0 and s[x][y+1]=='.' and r>0:
way.appendleft([x,y+1,l,r-1])
visited[x][y+1]=1
ans+=1
return ans
way=deque()
way.append((r,c,x,y))
visited = [[0 for i in range(m+2)] for j in range(n+2)]
visited[r][c]=1
ans=bfs(way)
#visited=set(visited)
print(ans+1) | Python | [
"graphs"
] | 850 | 1,096 | 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,233 |
0646a23b550eefea7347cef831d1c69d | Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it!Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from left to right, and the i-th piece has a colour si, denoted by a lowercase English letter. Nadeko will repaint at most m of the pieces to give each of them an arbitrary new colour (still denoted by a lowercase English letter). After this work, she finds out all subsegments of the garland containing pieces of only colour c — Brother Koyomi's favourite one, and takes the length of the longest among them to be the Koyomity of the garland.For instance, let's say the garland is represented by "kooomo", and Brother Koyomi's favourite colour is "o". Among all subsegments containing pieces of "o" only, "ooo" is the longest, with a length of 3. Thus the Koyomity of this garland equals 3.But problem arises as Nadeko is unsure about Brother Koyomi's favourite colour, and has swaying ideas on the amount of work to do. She has q plans on this, each of which can be expressed as a pair of an integer mi and a lowercase letter ci, meanings of which are explained above. You are to find out the maximum Koyomity achievable after repainting the garland according to each plan. | ['dp', 'two pointers', 'brute force', 'strings'] | import string
import bisect
import sys
def main():
lines = sys.stdin.readlines()
n = int(lines[0])
s = lines[1]
vals = {}
for c in string.ascii_lowercase:
a = [i for i, ch in enumerate(s) if ch == c]
m = len(a)
b = [0]
for length in range(1, m + 1):
best = n
for i in range(m - length + 1):
j = i + length - 1
best = min(best, (a[j] - j) - (a[i] - i))
b.append(best)
vals[c] = b
q = int(lines[2])
r = []
idx = 3
while q > 0:
q -= 1
query = lines[idx].split()
idx += 1
m = int(query[0])
c = query[1]
i = bisect.bisect_right(vals[c], m)
r.append(str(min(n, i + m - 1)))
print('\n'.join(r))
main() | Python | [
"strings"
] | 1,386 | 699 | 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
} | 969 |
8063c96cf62727f1b98e476e43679da2 | We say that a positive integer n is k-good for some positive integer k if n can be expressed as a sum of k positive integers which give k distinct remainders when divided by k.Given a positive integer n, find some k \geq 2 so that n is k-good or tell that such a k does not exist. | ['constructive algorithms', 'math', 'number theory'] | import array
import bisect
import heapq
import json
import math
import collections
import sys
import copy
from functools import reduce
import decimal
from io import BytesIO, IOBase
import os
import itertools
import functools
from types import GeneratorType
import fractions
from typing import Tuple, List, Union
# sys.setrecursionlimit(10 ** 9)
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
graphDict = collections.defaultdict
queue = collections.deque
################## pypy deep recursion handling ##############
# Author = @pajenegod
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
to = f(*args, **kwargs)
if stack:
return to
else:
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
return to
to = stack[-1].send(to)
return wrappedfunc
################## Graphs ###################
class Graphs:
def __init__(self):
self.graph = graphDict(list)
def add_edge(self, u, v, w, z):
self.graph[u].append([v, w, z])
self.graph[v].append([u, z, w])
def dfs_utility(self, nodes, visited_nodes, colors, parity, level):
global count
if nodes == 1:
colors[nodes] = -1
else:
if len(self.graph[nodes]) == 1 and parity % 2 == 0:
if q == 1:
colors[nodes] = 1
else:
colors[nodes] = -1
count += 1
else:
if parity % 2 == 0:
colors[nodes] = -1
else:
colors[nodes] = 1
visited_nodes.add(nodes)
for neighbour in self.graph[nodes]:
new_level = level + 1
if neighbour not in visited_nodes:
self.dfs_utility(neighbour, visited_nodes, colors, level - 1, new_level)
def dfs(self, node):
Visited = set()
color = collections.defaultdict()
self.dfs_utility(node, Visited, color, 0, 0)
return color
def bfs(self, node, f_node):
count = float("inf")
visited = set()
level = 0
if node not in visited:
queue.append([node, level])
visited.add(node)
flag = 0
while queue:
parent = queue.popleft()
if parent[0] == f_node:
flag = 1
count = min(count, parent[1])
level = parent[1] + 1
for item in self.graph[parent[0]]:
if item not in visited:
queue.append([item, level])
visited.add(item)
return count if flag else -1
return False
################### Tree Implementaion ##############
class Tree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(node, lis):
if node:
inorder(node.left, lis)
lis.append(node.data)
inorder(node.right, lis)
return lis
def leaf_node_sum(root):
if root is None:
return 0
if root.left is None and root.right is None:
return root.data
return leaf_node_sum(root.left) + leaf_node_sum(root.right)
def hight(root):
if root is None:
return -1
if root.left is None and root.right is None:
return 0
return max(hight(root.left), hight(root.right)) + 1
################## Union Find #######################
class UnionFind():
parents = []
sizes = []
count = 0
def __init__(self, n):
self.count = n
self.parents = [i for i in range(n)]
self.sizes = [1 for i in range(n)]
def find(self, i):
if self.parents[i] == i:
return i
else:
self.parents[i] = self.find(self.parents[i])
return self.parents[i]
def unite(self, i, j):
root_i = self.find(i)
root_j = self.find(j)
if root_i == root_j:
return
elif root_i < root_j:
self.parents[root_j] = root_i
self.sizes[root_i] += self.sizes[root_j]
else:
self.parents[root_i] = root_j
self.sizes[root_j] += self.sizes[root_i]
def same(self, i, j):
return self.find(i) == self.find(j)
def size(self, i):
return self.sizes[self.find(i)]
def group_count(self):
return len(set(self.find(i) for i in range(self.count)))
def answer(self, extra, p, q):
dic = collections.Counter()
for q in range(n):
dic[self.find(q)] = self.size(q)
hq = list(dic.values())
heapq._heapify_max(hq)
ans = -1
for z in range(extra + 1):
if hq:
ans += heapq._heappop_max(hq)
else:
break
return ans
#################################################
def rounding(n):
return int(decimal.Decimal(f'{n}').to_integral_value())
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0), [1]))
def p_sum(array):
return list(itertools.accumulate(array))
def base_change(nn, bb):
if nn == 0:
return [0]
digits = []
while nn:
digits.append(int(nn % bb))
nn //= bb
return digits[::-1]
def diophantine(a: int, b: int, c: int):
d, x, y = extended_gcd(a, b)
r = c // d
return r * x, r * y
@bootstrap
def extended_gcd(a: int, b: int):
if b == 0:
d, x, y = a, 1, 0
else:
(d, p, q) = yield extended_gcd(b, a % b)
x = q
y = p - q * (a // b)
yield d, x, y
######################################################################################
'''
Knowledge and awareness are vague, and perhaps better called illusions.
Everyone lives within their own subjective interpretation.
~Uchiha Itachi
'''
################################ <fast I/O> ###########################################
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, **kwargs):
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)
#############################################<I/O Region >##############################################
def inp():
return sys.stdin.readline().strip()
def map_inp(v_type):
return map(v_type, inp().split())
def list_inp(v_type):
return list(map_inp(v_type))
def interactive():
return sys.stdout.flush()
######################################## Solution ####################################
def primes_sieve1(limit):
limitn = limit + 1
primes = dict()
for i in range(2, limitn): primes[i] = True
for i in primes:
factors = range(i, limitn, i)
for f in factors[1:]:
primes[f] = False
return [i for i in primes if primes[i] == True]
def c_sum(x):
return (x * (x + 1)) // 2
def ans(a):
print(a)
return
for _ in range(int(inp())):
n = int(inp())
if n <= 2:
ans(-1)
continue
if n % 2:
ans(2)
continue
if n % 3 == 0:
ans(3)
continue
if n % 4 == 2:
ans(4)
continue
m = n
while m % 2 == 0:
m //= 2
if m == 1:
ans(-1)
continue
for k in (m, n // m * 2):
a = n - k * (k + 1) // 2
if a >= 0 and a % k == 0:
ans(k)
break
| Python | [
"math",
"number theory"
] | 352 | 9,471 | 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,202 |
0587d281830282418d4120cccbfd813b | After you had helped Fedor to find friends in the «Call of Soldiers 3» game, he stopped studying completely. Today, the English teacher told him to prepare an essay. Fedor didn't want to prepare the essay, so he asked Alex for help. Alex came to help and wrote the essay for Fedor. But Fedor didn't like the essay at all. Now Fedor is going to change the essay using the synonym dictionary of the English language.Fedor does not want to change the meaning of the essay. So the only change he would do: change a word from essay to one of its synonyms, basing on a replacement rule from the dictionary. Fedor may perform this operation any number of times.As a result, Fedor wants to get an essay which contains as little letters «R» (the case doesn't matter) as possible. If there are multiple essays with minimum number of «R»s he wants to get the one with minimum length (length of essay is the sum of the lengths of all the words in it). Help Fedor get the required essay.Please note that in this problem the case of letters doesn't matter. For example, if the synonym dictionary says that word cat can be replaced with word DOG, then it is allowed to replace the word Cat with the word doG. | ['dp', 'hashing', 'graphs', 'dfs and similar', 'strings'] | from collections import defaultdict
input()
index = {}
stat = lambda word: (word.count('r'),
len(word), index.setdefault(word, len(index)))
essay = list(map(stat, input().lower().split()))
queue = essay[:]
syn = defaultdict(list)
for i in range(int(input())):
word, rep = map(stat, input().lower().split())
syn[rep[2]].append(word[2])
queue.append(rep)
queue.sort(reverse=True)
best = {}
while queue:
n_r, length, word = queue.pop()
if word in best:
continue
best[word] = n_r, length
for rep in syn[word]:
if rep not in best:
queue.append((n_r, length, rep))
sum_n_r, sum_len = 0, 0
for n_r, length in map(lambda w: best[w[2]], essay):
sum_n_r += n_r
sum_len += length
print(sum_n_r, sum_len)
| Python | [
"graphs",
"strings"
] | 1,193 | 732 | 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
} | 2,053 |
8c2e0cd780cf9390e933e28e57643cba | This problem is same as the next one, but has smaller constraints.It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system consisting of many chimneys, electric poles, and wires. Since they are cats, they found those things gigantic.At the entrance of the station, there is a map describing the complicated wiring system. Selena is the best at math among three friends. He decided to draw the map on the Cartesian plane. Each pole is now a point at some coordinates (x_i, y_i). Since every pole is different, all of the points representing these poles are distinct. Also, every two poles are connected with each other by wires. A wire is a straight line on the plane infinite in both directions. If there are more than two poles lying on the same line, they are connected by a single common wire.Selena thinks, that whenever two different electric wires intersect, they may interfere with each other and cause damage. So he wonders, how many pairs are intersecting? Could you help him with this problem? | ['geometry', 'brute force'] | from itertools import combinations
from collections import Counter
n = input()
points = [map(float, raw_input().split()) for _ in xrange(n)]
lines = set()
#for p1, p2 in combinations(points, 2):
for i in xrange(n):
for j in xrange(i+1, n):
x1, y1 = points[i]
x2, y2 = points[j]
if x1 == x2:
slope = float('inf')
ysect = x1
else:
slope = (y1 - y2) / (x1 - x2)
ysect = (x1 * y2 - x2 * y1) / (x1 - x2)
lines.add((slope, ysect))
L = [x[0] for x in lines]
C = Counter(L)
total = len(L) * (len(L) - 1) / 2
for x in C:
total -= C[x] * (C[x] - 1) / 2
print total | Python | [
"geometry"
] | 1,200 | 586 | 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
} | 777 |
c4da69789d875853beb4f92147825ebf | You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".Note it is allowed to split the string s to the strings only of length p or to the strings only of length q (see the second sample test). | ['implementation', 'brute force', 'strings'] | def divide(n, k, s, t):
array = []
for j in xrange(k, len(s) - t, n):
mini = s[j:j + n]
#print "mini " + mini + str(len(mini))
if len(mini) == n:
array.append(mini)
return array
def splitter():
n, p, q =[int(x) for x in raw_input().split()]
text = raw_input()
maxi = 0
mini = 0
index = 0
if p > q:
maxi = p
mini = q
else:
maxi = q
mini = p
#print "max" + str(max)
permisionmax = n % maxi == 0
maxnum = (n / maxi) + 1
permisionmin = n % mini == 0
minnum = (n / mini) + 1
mx = 0
mn = 0
suma = 0
while suma < n:
suma = suma + maxi
mx = mx + 1
res = n - suma
if res % mini == 0 and res > 0:
rm = res / mini
suma = suma + (mini * rm)
mn = rm
break
#print suma
if suma != n:
mx = 0
mn = 0
suma = 0
while suma < n:
suma = suma + mini
mn = mn + 1
res = n - suma
if res % mini == 0:
rm = res / maxi
suma = suma + (maxi * rm)
mx = rm
break
maxnum -= 1
permisionboth = True
if suma != n or mx == 0 or mn == 0 or mini == maxi:
permisionboth = False
#permisionboth = n - (minnum * min) - (maxnum * max) == 0
if not permisionmax and not permisionmin and not permisionboth:
return [-1]
elif permisionboth:
#print "ambos"
t = n - (maxi *mx)
maxlist = divide(maxi, index, text, t)
index = maxi * mx
minlist = divide(mini, index, text, 0)
return [len(maxlist) + len(minlist)] + maxlist + minlist
elif permisionmin:
#print "minimo"
return [n / mini] + divide(mini, index, text, 0)
else:
#print "maximo"
return [n / maxi] + divide(maxi, index, text, 0)
ss = splitter()
for i in ss:
print i | Python | [
"strings"
] | 378 | 1,992 | 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,756 |
8aaabe089d2512b76e5de938bac5c3bf | In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.Vova and Lesha are friends. They often meet at Vova's place and compete against each other in a computer game named The Ancient Papyri: Swordsink. Vova always chooses a warrior as his fighter and Leshac chooses an archer. After that they should choose initial positions for their characters and start the fight. A warrior is good at melee combat, so Vova will try to make the distance between fighters as small as possible. An archer prefers to keep the enemy at a distance, so Lesha will try to make the initial distance as large as possible.There are n (n is always even) possible starting positions for characters marked along the Ox axis. The positions are given by their distinct coordinates x1, x2, ..., xn, two characters cannot end up at the same position.Vova and Lesha take turns banning available positions, Vova moves first. During each turn one of the guys bans exactly one of the remaining positions. Banned positions cannot be used by both Vova and Lesha. They continue to make moves until there are only two possible positions remaining (thus, the total number of moves will be n - 2). After that Vova's character takes the position with the lesser coordinate and Lesha's character takes the position with the bigger coordinate and the guys start fighting.Vova and Lesha are already tired by the game of choosing positions, as they need to play it before every fight, so they asked you (the developer of the The Ancient Papyri: Swordsink) to write a module that would automatically determine the distance at which the warrior and the archer will start fighting if both Vova and Lesha play optimally. | ['games'] | n = int(input())
x = sorted(list(map(int, input().split())))
print(min([x[i + n // 2] - x[i] for i in range(n // 2)]))
| Python | [
"games"
] | 1,932 | 120 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,688 |
d7ffedb180378b3ab70e5f05c79545f5 | Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys: Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and only if he is granted all the toys in his lovely set. If a child starts playing, then sooner or later he gives the toys back. No child keeps the toys forever. Children request toys at distinct moments of time. No two children request a toy at the same time. If a child is granted a toy, he never gives it back until he finishes playing with his lovely set. If a child is not granted a toy, he waits until he is granted this toy. He can't request another toy while waiting. If two children are waiting for the same toy, then the child who requested it first will take the toy first.Children don't like to play with each other. That's why they never share toys. When a child requests a toy, then granting the toy to this child depends on whether the toy is free or not. If the toy is free, Sagheer will give it to the child. Otherwise, the child has to wait for it and can't request another toy.Children are smart and can detect if they have to wait forever before they get the toys they want. In such case they start crying. In other words, a crying set is a set of children in which each child is waiting for a toy that is kept by another child in the set.Now, we have reached a scenario where all the children made all the requests for their lovely sets, except for one child x that still has one last request for his lovely set. Some children are playing while others are waiting for a toy, but no child is crying, and no one has yet finished playing. If the child x is currently waiting for some toy, he makes his last request just after getting that toy. Otherwise, he makes the request right away. When child x will make his last request, how many children will start crying?You will be given the scenario and q independent queries. Each query will be of the form x y meaning that the last request of the child x is for the toy y. Your task is to help Sagheer find the size of the maximal crying set when child x makes his last request. | ['implementation', 'dfs and similar', 'trees', 'graphs'] | from sys import stdin
from sys import stdout
n, m, k, q = map(int, stdin.readline().split())
d = [None for i in range(m)]
roots = set(range(n))
matrix = [[] for i in range(n)]
for i in range(k):
x, y = map(int, stdin.readline().split())
if d[y - 1] is None:
d[y - 1] = x - 1
else:
matrix[d[y - 1]].append(x - 1)
roots.discard(x - 1)
d[y - 1] = x - 1
location = [None for i in range(n)]
comp_of_conn = []
graph = [matrix[i][:] for i in range(n)]
for i in roots:
stack = []
time = 1
queue = [[i, time]]
while queue:
j = queue[-1]
time += 1
if len(graph[j[0]]) == 0:
stack.append(queue.pop() + [time])
else:
queue.append([graph[j[0]].pop(), time])
stack.reverse()
if len(stack) > 1:
for j in range(len(stack)):
location[stack[j][0]] = [len(comp_of_conn), j]
for j in range(len(stack) - 1, -1, -1):
app = 0
for u in matrix[stack[j][0]]:
app += stack[location[u][1]][3]
stack[j].append(app + 1)
comp_of_conn.append(stack)
for i in range(q):
x, y = map(int, stdin.readline().split())
x -= 1
y = d[y - 1]
if y is None:
stdout.write('0\n')
elif location[x] is not None and location[y] is not None and location[x][0] == location[y][0]:
c = location[x][0]
ind_x = location[x][1]
ind_y = location[y][1]
if comp_of_conn[c][ind_x][1] < comp_of_conn[c][ind_y][1] and comp_of_conn[c][ind_x][2] > comp_of_conn[c][ind_y][
2]:
stdout.write(str(comp_of_conn[c][ind_x][3]) + '\n')
else:
stdout.write('0\n')
else:
stdout.write('0\n')
| Python | [
"graphs",
"trees"
] | 2,254 | 1,742 | 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,387 |
e6689123fefea251555e0e096f58f6d1 | Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons: Tetrahedron. Tetrahedron has 4 triangular faces. Cube. Cube has 6 square faces. Octahedron. Octahedron has 8 triangular faces. Dodecahedron. Dodecahedron has 12 pentagonal faces. Icosahedron. Icosahedron has 20 triangular faces. All five kinds of polyhedrons are shown on the picture below: Anton has a collection of n polyhedrons. One day he decided to know, how many faces his polyhedrons have in total. Help Anton and find this number! | ['implementation', 'strings'] | n = int(input())
k = 0
i = 0
while i != n:
x = str(input())
if x == 'Tetrahedron':
k += 4
if x == 'Cube':
k += 6
if x == 'Octahedron':
k += 8
if x == 'Dodecahedron':
k += 12
if x == 'Icosahedron':
k += 20
i += 1
print(k)
# 374 ms по слову for
# 390 ms по индексу for
# 467 ms по слову while
# 467 ms по индексу while
| Python | [
"strings"
] | 561 | 387 | 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,106 |
e7517e32caa1b044ebf1d39276560b47 | A permutation p of length n is a sequence of distinct integers p1, p2, ..., pn (1 ≤ pi ≤ n). A permutation is an identity permutation, if for any i the following equation holds pi = i. A swap (i, j) is the operation that swaps elements pi and pj in the permutation. Let's assume that f(p) is the minimum number of swaps that you need to make the permutation p an identity permutation. Valera wonders, how he can transform permutation p into any permutation q, such that f(q) = m, using the minimum number of swaps. Help him do that. | ['graphs', 'constructive algorithms', 'string suffix structures', 'math', 'dsu', 'implementation'] | n = int(raw_input())
a = [0] + map(int, raw_input().split())
g = [0] * (n+1)
l = []
st = [0] * (n+1)
nd = [0] * (n+1)
k = 0
for x in xrange(1, n+1):
if g[x]:
continue
y = a[x]
st[x] = len(l)
while not g[y]:
g[y] = x
l.append(y)
y = a[y]
nd[x] = len(l)
k += nd[x] - st[x] - 1
N = 4096
b = [10000] * N * 2
pb = [0] * N * 2
def update(p, x):
p += N
b[p] = x
pb[p] = p - N
while p > 1:
p, q = p / 2, p / 2 * 2
if b[q] >= b[q+1]:
q += 1
b[p], pb[p] = b[q], pb[q]
def query(left, right, p = 1, L = 0, R = N):
if right <= L or R <= left:
return (10000, -1)
if left <= L and R <= right:
return (b[p], pb[p])
mid = (L + R) / 2
return min(query(left, right, p+p, L, mid), query(left, right, p+p+1, mid, R))
for i, x in enumerate(l):
update(i, x)
m = int(raw_input())
if m == k:
print 0
else:
ans = []
if m > k:
for i in xrange(1, n+1):
if m <= k: break
if g[i] != 1:
for x in l[st[i]:nd[i]]:
g[x] = 1
ans.extend([1, i])
k += 1
else:
for i in xrange(1, n+1):
while m < k and nd[i] - st[i] > 1:
j, pj = query(st[i], nd[i] - 1)
ans.extend([i, j])
st[i], st[j], nd[j] = pj + 1, st[i], pj + 1
k -= 1
print len(ans) / 2
for x in ans:
print x,
print
| Python | [
"graphs",
"strings",
"math"
] | 532 | 1,500 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,557 |
d42405469c82e35361d708a689b54f47 | On the great island of Baltia, there live N people, numbered from 1 to N. There are exactly M pairs of people that are friends with each other. The people of Baltia want to organize a successful party, but they have very strict rules on what a party is and when the party is successful. On the island of Baltia, a party is a gathering of exactly 5 people. The party is considered to be successful if either all the people at the party are friends with each other (so that they can all talk to each other without having to worry about talking to someone they are not friends with) or no two people at the party are friends with each other (so that everyone can just be on their phones without anyone else bothering them). Please help the people of Baltia organize a successful party or tell them that it's impossible to do so. | ['brute force', 'math', 'probabilities'] | import sys
input = sys.stdin.buffer.readline
def process(n, G):
n = min(n, 1000)
M = [[0 for j in range(n+1)] for i in range(n+1)]
for u, v in G:
if max(u, v) <= n:
M[u][v] = 1
M[v][u] = 1
all_connect = []
no_connect = []
if M[1][2] == 1:
all_connect.append([1, 2])
else:
no_connect.append([1, 2])
for i in range(3, n+1):
new_all_connect = []
new_no_connect = []
for i2 in range(1, i):
if M[i][i2]==1:
new_all_connect.append([i2, i])
else:
new_no_connect.append([i2, i])
for x in all_connect:
new_all_connect.append(x)
works = True
for y in x:
if M[i][y]==0:
works = False
break
if works:
if len(x+[i])==5:
return x+[i]
new_all_connect.append(x+[i])
for x in no_connect:
new_no_connect.append(x)
works = True
for y in x:
if M[i][y]==1:
works = False
break
if works:
if len(x+[i])==5:
return x+[i]
new_no_connect.append(x+[i])
all_connect = new_all_connect
no_connect = new_no_connect
return [-1]
n, m = [int(x) for x in input().split()]
G = []
for i in range(m):
u, v = [int(x) for x in input().split()]
G.append([u, v])
answer = process(n, G)
sys.stdout.write(' '.join(map(str, answer))+'\n') | Python | [
"math",
"probabilities"
] | 855 | 1,670 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 0
} | 2,872 |
d062ba289fd9c373a31ca5e099f9306c | Kolya has a string s of length n consisting of lowercase and uppercase Latin letters and digits.He wants to rearrange the symbols in s and cut it into the minimum number of parts so that each part is a palindrome and all parts have the same lengths. A palindrome is a string which reads the same backward as forward, such as madam or racecar.Your task is to help Kolya and determine the minimum number of palindromes of equal lengths to cut s into, if it is allowed to rearrange letters in s before cuttings. | ['implementation', 'brute force', 'strings'] | n = int(raw_input())
import logging
logging.basicConfig(level=logging.ERROR)
s = str(raw_input())
from collections import Counter
c = Counter()
for char in s:
c[char] += 1
even_count = len([char for char in c if c[char] % 2 == 0])
odd_count = len(c) - even_count
def simple_even(c):
s = ""
for char in c:
l = c[char] / 2
s = l*char + s + l*char
return s
def weird_odd(c, n, k):
#print "k = %d" % k
# initialize odds
d = {}
for i in range(k):
d[i] = Counter()
odd_boi = None
for char in c:
if c[char] % 2 == 1 and odd_boi == None:
odd_boi = char
if odd_boi == None:
for char in c:
if c[char] > 0:
odd_boi = char
break
if odd_boi == None:
return None
d[i][odd_boi] = 1
c[odd_boi] -= 1
#print d
#print c
min_length = n // k
#print "min_length %d" % min_length
logging.debug((n, k))
logging.debug(d)
for i in d:
left = min_length - 1
logging.debug("left = %d" % left)
while left > 0:
for char in c:
if left == 0:
break
if c[char] == 0:
continue
if c[char] >= left:
d[i][char] += left
c[char] -= left
left = 0
else:
left -= c[char]
d[i][char] += c[char]
c[char] = 0
#print d[i]
#print d
def make_pal(counts):
odd_boi = [c for c in counts if counts[c] % 2 == 1]
#print odd_boi
if len(odd_boi) > 1:
return None
odd_boi = odd_boi[0]
s = str(odd_boi * counts[odd_boi])
counts[odd_boi] = 0
for c in counts:
l = counts[c] / 2
s = l*c + s + l*c
return s
#print k, d
words = []
for i in d:
w = make_pal(d[i])
if w == None:
return None
words.append(w)
return " ".join(words)
#print "odd count %d" % odd_count
if odd_count == 0:
print 1
print simple_even(c)
else:
k = odd_count
logging.debug("odd count = %d" % k)
solved = False
while k <= n:
if n % k == 0 and (n // k) % 2 == 1:
print k
if k == n:
print " ".join([c for c in s])
else:
print weird_odd(c, n, k)
break
else:
k += 1
| Python | [
"strings"
] | 508 | 2,600 | 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,193 |
60776cefd6c1a2f3c16b3378ebc31a9a | Sergei B., the young coach of Pokemons, has found the big house which consists of n flats ordered in a row from left to right. It is possible to enter each flat from the street. It is possible to go out from each flat. Also, each flat is connected with the flat to the left and the flat to the right. Flat number 1 is only connected with the flat number 2 and the flat number n is only connected with the flat number n - 1.There is exactly one Pokemon of some type in each of these flats. Sergei B. asked residents of the house to let him enter their flats in order to catch Pokemons. After consulting the residents of the house decided to let Sergei B. enter one flat from the street, visit several flats and then go out from some flat. But they won't let him visit the same flat more than once. Sergei B. was very pleased, and now he wants to visit as few flats as possible in order to collect Pokemons of all types that appear in this house. Your task is to help him and determine this minimum number of flats he has to visit. | ['two pointers', 'binary search', 'strings'] | n = int(input())
s = input()
D = dict()
A = set()
for i in range(n):
if s[i] not in A:
A.add(s[i])
l = 100001
for i in A:
D[i] = 0
g = 0
c = '0'
for i in range(n):
D[s[i]] += 1
q = 0
if c == '0':
for k in A:
if D[k] == 0:
break
else:
q = 1
if q == 1 or s[i] == c:
for k in range(g,i+1):
D[s[k]] -= 1
if D[s[k]] == 0:
D[s[k]] += 1
l = min(l,i-k+1)
g = max(k,0)
c = s[k]
break
print(l)
| Python | [
"strings"
] | 1,030 | 589 | 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
} | 396 |
07ac198c1086323517540ecd0669eb4c | A tree is an undirected connected graph in which there are no cycles. This problem is about non-rooted trees. A leaf of a tree is a vertex that is connected to at most one vertex.The gardener Vitaly grew a tree from n vertices. He decided to trim the tree. To do this, he performs a number of operations. In one operation, he removes all leaves of the tree. Example of a tree. For example, consider the tree shown in the figure above. The figure below shows the result of applying exactly one operation to the tree. The result of applying the operation "remove all leaves" to the tree. Note the special cases of the operation: applying an operation to an empty tree (of 0 vertices) does not change it; applying an operation to a tree of one vertex removes this vertex (this vertex is treated as a leaf); applying an operation to a tree of two vertices removes both vertices (both vertices are treated as leaves). Vitaly applied k operations sequentially to the tree. How many vertices remain? | ['brute force', 'data structures', 'dfs and similar', 'greedy', 'implementation', 'trees'] | t = int(input())
from collections import defaultdict, deque
def count_indegrees(graph,n):
indegrees = [0 for i in range(n)]
for node in graph:
for neighbor in graph[node]:
indegrees[neighbor] += 1
return indegrees
for x in range(t):
input()
n,k = [int(x) for x in input().split()]
graph = defaultdict(list)
for aaa in range(n-1):
a,b =[int(x) for x in input().split()]
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
indegrees = count_indegrees(graph, n)
with_1 = deque([])
for x in range(len(indegrees)):
if indegrees[x] <= 1:
with_1.append(x)
pro = 0
for x in range(k):
if len(with_1) == 0:
break
nex = deque([])
while len(with_1) != 0:
node = with_1.popleft()
pro += 1
for neighbor in graph[node]:
indegrees[neighbor] -= 1
if indegrees[neighbor] == 1:
nex.append(neighbor)
with_1 = nex
print(n-pro)
| Python | [
"graphs",
"trees"
] | 1,015 | 1,133 | 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,097 |
6cffd0fa1146b250a2608d53f3f738fa | Alice and Bob are playing a game. Initially, they are given a non-empty string s, consisting of lowercase Latin letters. The length of the string is even. Each player also has a string of their own, initially empty.Alice starts, then they alternate moves. In one move, a player takes either the first or the last letter of the string s, removes it from s and prepends (adds to the beginning) it to their own string.The game ends when the string s becomes empty. The winner is the player with a lexicographically smaller string. If the players' strings are equal, then it's a draw.A string a is lexicographically smaller than a string b if there exists such position i that a_j = b_j for all j < i and a_i < b_i.What is the result of the game if both players play optimally (e. g. both players try to win; if they can't, then try to draw)? | ['constructive algorithms', 'dp', 'games', 'two pointers'] | from functools import lru_cache
t = int(input())
for _ in range(t):
s = input()
l = len(s)
dp = [[True for i in range(l + 1)] for j in range(l + 1)]
for k in range(2, l + 1, 2):
for i in range(l + 1 - k):
j = i + k
dp[i][j] = (s[i] == s[j - 1] and dp[i + 1][j - 1]) or ((s[i] == s[i + 1] and dp[i + 2][j]) & (s[j - 1] == s[j - 2] and dp[i][j - 2]))
if dp[0][-1]:
print("Draw")
else:
print("Alice") | Python | [
"games"
] | 904 | 482 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,638 |
04330cb392bcfd51d1acffd72c8004cb | You are given three integers a, b and c.Find two positive integers x and y (x > 0, y > 0) such that: the decimal representation of x without leading zeroes consists of a digits; the decimal representation of y without leading zeroes consists of b digits; the decimal representation of gcd(x, y) without leading zeroes consists of c digits. gcd(x, y) denotes the greatest common divisor (GCD) of integers x and y.Output x and y. If there are multiple answers, output any of them. | ['constructive algorithms', 'math', 'number theory'] | def func_gcd(a,b):
if b==0:
return a
return func_gcd(b, a%b)
T = int(input())
for t in range(T):
a, b, c = map(int, input().split())
x_arr = ["1"] + ["0"]*(a-1)
y_arr = ["1"]*(b-c+1) + ["0"]*(c-1)
x = ""
y = ""
for elem in x_arr:
x += elem
for elem in y_arr:
y += elem
print(x, y) | Python | [
"math",
"number theory"
] | 596 | 316 | 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,372 |
3b2d0d396649a200a73faf1b930ef611 | Polycarp likes numbers that are divisible by 3.He has a huge number s. Polycarp wants to cut from it the maximum number of numbers that are divisible by 3. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after m such cuts, there will be m+1 parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by 3.For example, if the original number is s=3121, then Polycarp can cut it into three parts with two cuts: 3|1|21. As a result, he will get two numbers that are divisible by 3.Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.What is the maximum number of numbers divisible by 3 that Polycarp can obtain? | ['dp', 'number theory', 'greedy'] | import sys
sys.setrecursionlimit(10000)
# default is 1000 in python
# increase stack size as well (for hackerrank)
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, (resource.RLIM_INFINITY, resource.RLIM_INFINITY))
# t = int(input())
t = 1
for _ in range(t):
s = input()
no = ''
count = 0
for i in s:
if int(i) % 3 == 0:
count += 1
no = ''
else:
no += i
if int(no) % 3 == 0:
count += 1
no = ''
elif int(no[-2:]) % 3 == 0:
count += 1
no = ''
print(count)
# try:
# raise Exception
# except:
# print("-1")
# from itertools import combinations
# all_combs = list(combinations(range(N), r))
# from collections import OrderedDict
# mydict = OrderedDict()
# thenos.sort(key=lambda x: x[2], reverse=True)
# int(math.log(max(numbers)+1,2))
# 2**3 (power)
# a,t = (list(x) for x in zip(*sorted(zip(a, t))))
# to copy lists use:
# import copy
# copy.deepcopy(listname)
# pow(p, si, 1000000007) for modular exponentiation
# my_dict.pop('key', None)
# This will return my_dict[key] if key exists in the dictionary, and None otherwise.
# bin(int('010101', 2))
# Binary Search
# from bisect import bisect_right
# i = bisect_right(a, ins)
| Python | [
"number theory"
] | 1,072 | 1,210 | 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,460 |
965e51168f9945a456610e8b449dd9df | There are n students studying in the 6th grade, in group "B" of a berland secondary school. Every one of them has exactly one friend whom he calls when he has some news. Let us denote the friend of the person number i by g(i). Note that the friendships are not mutual, i.e. g(g(i)) is not necessarily equal to i.On day i the person numbered as ai learns the news with the rating of bi (bi ≥ 1). He phones the friend immediately and tells it. While he is doing it, the news becomes old and its rating falls a little and becomes equal to bi - 1. The friend does the same thing — he also calls his friend and also tells the news. The friend of the friend gets the news already rated as bi - 2. It all continues until the rating of the news reaches zero as nobody wants to tell the news with zero rating. More formally, everybody acts like this: if a person x learns the news with a non-zero rating y, he calls his friend g(i) and his friend learns the news with the rating of y - 1 and, if it is possible, continues the process.Let us note that during a day one and the same person may call his friend and tell him one and the same news with different ratings. Thus, the news with the rating of bi will lead to as much as bi calls.Your task is to count the values of resi — how many students learned their first news on day i.The values of bi are known initially, whereas ai is determined from the following formula: where mod stands for the operation of taking the excess from the cleavage, res0 is considered equal to zero and vi — some given integers. | ['dp', 'dsu'] | import sys
range = xrange
input = raw_input
inp = [int(x) for x in sys.stdin.read().split()]; ii = 0
n = inp[ii]; ii += 1
m = inp[ii]; ii += 1
P0 = [x - 1 for x in inp[ii: ii + n]]; ii += n
V = [x - 1 for x in inp[ii: ii + m]]; ii += m
B = inp[ii: ii + m]; ii += m
P = [P0]
for _ in range(19):
Pprev = P[-1]
P.append([Pprev[Pprev[node]] for node in range(n)])
marked = [[0] * n for _ in range(20)]
# marks [node, node + 2**bit] and returns number of newly marked nodes
def mark(bit, node):
if marked[bit][node]:
return 0
marked[bit][node] = 1
if bit:
return mark(bit - 1, node) + mark(bit - 1, P[bit - 1][node])
else:
return 1
out = [0]
for i in range(m):
v = V[i]
a = (v + out[-1]) % n
b = min(B[i], n)
ans = 0
for bit in range(20):
if b & (1 << bit):
ans += mark(bit, a)
a = P[bit][a]
out.append(ans)
out.pop(0)
print '\n'.join(str(x) for x in out)
| Python | [
"graphs"
] | 1,552 | 964 | 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,775 |
4b512c39e71e34064c820958dde9f4a1 | 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 ancestors b containing n numbers: b_i is an ancestor of the vertex with the number i. The ancestor of a vertex u is a vertex that is the next vertex on a simple 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 ancestor of 5 is 1.The root has no ancestor, so for it, the value of b_i is i (the root is the only vertex for which b_i=i).For example, if n=5 and b=[3, 1, 3, 3, 1], then the tree looks like this. An example of a rooted tree for n=5, the root of the tree is a vertex number 3. You are given an array p — a permutation of the vertices of the tree. If it is possible, assign any positive integer weights on the edges, so that the vertices sorted by distance from the root would form the given permutation p.In other words, for a given permutation of vertices p, it is necessary to choose such edge weights so that the condition dist[p_i]<dist[p_{i+1}] is true for each i from 1 to n-1. dist[u] is a sum of the weights of the edges on the path from the root to u. In particular, dist[u]=0 if the vertex u is the root of the tree.For example, assume that p=[3, 1, 2, 5, 4]. In this case, the following edge weights satisfy this permutation: the edge (3, 4) has a weight of 102; the edge (3, 1) has weight of 1; the edge (1, 2) has a weight of 10; the edge (1, 5) has a weight of 100. The array of distances from the root looks like: dist=[1,11,0,102,101]. The vertices sorted by increasing the distance from the root form the given permutation p.Print the required edge weights or determine that there is no suitable way to assign weights. If there are several solutions, then print any of them. | ['constructive algorithms', 'trees'] | import io, os
import sys
from sys import stdin
from bisect import bisect_left, bisect_right
from collections import defaultdict, deque, namedtuple
from math import gcd, ceil, floor, factorial
from itertools import combinations, permutations
input = sys.stdin.buffer.readline
# input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# input = sys.stdin.readline
def main():
test = int(input())
imp = -1
for _ in range(test):
n = int(input())
# a = list(map(int, input().split()))
# fas = [0] * n
# for i in range(n):
# fas[i] = a[i] - 1
dist = list(range(n))
# a = list(map(int, input().split()))
# for i in range(n):
# dist[a[i] - 1] = i
es = [0] * n
# for i in range(n):
# es[i] = dist[i] - dist[fas[i]]
b = list(map(int, input().split()))
p = list(map(int, input().split()))
for i in range(n):
dist[p[i] - 1] = i
for i in range(n):
fa = b[p[i] - 1]
es[p[i] - 1] = dist[p[i] - 1] - dist[fa - 1]
# print("es", es)
if min(es) < 0:
print(imp)
else:
for i in es:
print(i, end=" ")
print()
return
main() | Python | [
"trees"
] | 2,228 | 1,351 | 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,455 |
afe77e7b2dd6d7940520d9844ab30cfd | One night, having had a hard day at work, Petya saw a nightmare. There was a binary search tree in the dream. But it was not the actual tree that scared Petya. The horrifying thing was that Petya couldn't search for elements in this tree. Petya tried many times to choose key and look for it in the tree, and each time he arrived at a wrong place. Petya has been racking his brains for long, choosing keys many times, but the result was no better. But the moment before Petya would start to despair, he had an epiphany: every time he was looking for keys, the tree didn't have the key, and occured exactly one mistake. "That's not a problem!", thought Petya. "Why not count the expectation value of an element, which is found when I search for the key". The moment he was about to do just that, however, Petya suddenly woke up.Thus, you are given a binary search tree, that is a tree containing some number written in the node. This number is called the node key. The number of children of every node of the tree is equal either to 0 or to 2. The nodes that have 0 children are called leaves and the nodes that have 2 children, are called inner. An inner node has the left child, that is the child whose key is less than the current node's key, and the right child, whose key is more than the current node's key. Also, a key of any node is strictly larger than all the keys of the left subtree of the node and strictly smaller than all the keys of the right subtree of the node.Also you are given a set of search keys, all of which are distinct and differ from the node keys contained in the tree. For each key from the set its search in the tree is realised. The search is arranged like this: initially we are located in the tree root, if the key of the current node is larger that our search key, then we move to the left child of the node, otherwise we go to the right child of the node and the process is repeated. As it is guaranteed that the search key is not contained in the tree, the search will always finish in some leaf. The key lying in the leaf is declared the search result.It is known for sure that during the search we make a mistake in comparing exactly once, that is we go the wrong way, but we won't make any mistakes later. All possible mistakes are equiprobable, that is we should consider all such searches where exactly one mistake occurs. Your task is to find the expectation (the average value) of the search result for every search key, considering that exactly one mistake occurs in the search. That is, for a set of paths containing exactly one mistake in the given key search, you should count the average value of keys containing in the leaves of those paths. | ['probabilities', 'sortings', 'binary search', 'dfs and similar', 'trees'] | from bisect import bisect_left as bl
n = input()
n+=1
k = [0]*n
p = [0]*n
ma = [0]*n
mi = [0]*n
l = [0]*n
r = [0]*n
for i in xrange(1,n):
pp,kk = map(int,raw_input().split())
p[i] = pp
ma[i] = mi[i] = k[i] = kk
kn = input()
for i in xrange(1,n):
if p[i]<0: continue
if k[p[i]]<k[i]: r[p[i]]=i
else: l[p[i]]=i
q = [i for i in xrange(1,n) if not l[i]]
v = [False]*n
for x in q: v[x] = True
for x in q:
if p[x]<0: continue
if v[p[x]]: continue
if l[p[x]] and (not v[l[p[x]]] or not v[r[p[x]]]): continue
v[p[x]] = True
q.append(p[x])
for i in q:
if not l[i]: continue
ma[i]=ma[r[i]]
mi[i]=mi[l[i]]
#ma[p[i]]=max(ma[p[i]],ma[i])
#mi[p[i]]=min(mi[p[i]],mi[i])
en = [0]*n
ex = [0.]*n
for i in reversed(q):
if not l[i]: continue
en[r[i]]=en[l[i]]=en[i]+1
ex[l[i]]=ex[i]+mi[r[i]]
ex[r[i]]=ex[i]+ma[l[i]]
k[0]=-1
kp = [(v,i) for i,v in enumerate(k)]
kp.sort()
kpv = [x for x,y in kp]
kpi = [y for x,y in kp]
for _ in xrange(kn):
x = input()
p = bl(kpv,x)-1
e = kpi[p]
if p<n-1:
if not e or l[e]:
e = kpi[p+1]
if l[e]: raise NotImplemented
print "%.10f"%(1.*ex[e]/en[e])
| Python | [
"graphs",
"probabilities",
"trees"
] | 2,690 | 1,189 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 1,
"strings": 0,
"trees": 1
} | 3,034 |
e54f8aff8ede309bd591cb9fbd565d1f | Tavas is a cheerleader in the new sports competition named "Pashmaks". This competition consists of two part: swimming and then running. People will immediately start running R meters after they finished swimming exactly S meters. A winner is a such person that nobody else finishes running before him/her (there may be more than one winner).Before the match starts, Tavas knows that there are n competitors registered for the match. Also, he knows that i-th person's swimming speed is si meters per second and his/her running speed is ri meters per second. Unfortunately, he doesn't know the values of R and S, but he knows that they are real numbers greater than 0.As a cheerleader, Tavas wants to know who to cheer up. So, he wants to know all people that might win. We consider a competitor might win if and only if there are some values of R and S such that with these values, (s)he will be a winner.Tavas isn't really familiar with programming, so he asked you to help him. | ['geometry', 'math'] | from itertools import imap
import sys
n = input()
def parseints(s, n):
r, i, x = [0] * n, 0, 0
for c in imap(ord, s):
if c == 32:
r[i], i, x = x, i + 1, 0
else:
x = x * 10 + c - 48
return r
z = parseints(sys.stdin.read().replace('\n', ' '), n * 2)
# p = zip(z[::2], z[1::2], range(1, n))
p = zip(z[::2], z[1::2])
def convex_hull(points):
# points = list(set(points))
# points.sort(reverse=True)
if len(points) <= 1:
return points
pindex = range(len(points))
pkey = [x * 10001 + y for x, y in points]
pindex.sort(key=lambda i: pkey[i], reverse=True)
def cross(o, a, b):
ax, ay = a
bx, by = b
ox, oy = o
return (oy * (ox * (ay * bx - ax * by) +
ax * bx * (by - ay)) -
ox * ay * by * (bx - ax))
# def cross(o, a, b):
# return (o[1] * (o[0] * (a[1] * b[0] - a[0] * b[1]) +
# a[0] * b[0] * (b[1] - a[1])) -
# o[0] * a[1] * b[1] * (b[0] - a[0]))
lower = []
for pi in pindex:
p = points[pi]
while len(lower) >= 2 and cross(lower[-2], lower[-1], p) < 0:
lower.pop()
if not lower or lower[-1][1] < p[1]:
lower.append(p)
return lower
pdic = {}
for i, x in enumerate(p, 1):
pdic.setdefault(x, []).append(i)
ch = convex_hull(p)
res = []
for x in ch:
res.extend(pdic[x])
res.sort()
print ' '.join(map(str, res))
| Python | [
"math",
"geometry"
] | 980 | 1,491 | 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,780 |
6a9f683dee69a7be2d06ec6646970f19 | Everybody seems to think that the Martians are green, but it turns out they are metallic pink and fat. Ajs has two bags of distinct nonnegative integers. The bags are disjoint, and the union of the sets of numbers in the bags is \{0,1,…,M-1\}, for some positive integer M. Ajs draws a number from the first bag and a number from the second bag, and then sums them modulo M.What are the residues modulo M that Ajs cannot obtain with this action? | ['number theory', 'hashing'] | import sys
input = sys.stdin.readline
def main():
n, m = map(int, input().split())
a = list(map(int, input().split())) + [0]*500000
ans_S = 0
a[n] = a[0] + m
s = [0]*600600
for i in range(n):
s[i] = a[i + 1] - a[i]
s[n] = -1
for i in range(n):
s[2*n - i] = s[i]
for i in range(2*n + 1, 3*n + 1):
s[i] = s[i - n]
l, r = 0, 0
z = [0]*600600
for i in range(1, 3*n + 1):
if i < r:
z[i] = z[i - l]
while i + z[i] <= 3*n and (s[i + z[i]] == s[z[i]]):
z[i] += 1
if i + z[i] > r:
l = i
r = i + z[i]
ans = []
for i in range(n + 1, 2*n + 1):
if z[i] < n:
continue
ans_S += 1
ans.append((a[0] + a[2*n - i + 1]) % m)
ans.sort()
print(ans_S)
print(*ans)
return
if __name__=="__main__":
main() | Python | [
"number theory"
] | 468 | 889 | 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,558 |
1e6d7ec8023eb0dc482b1f133e5dfe2a | You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i \oplus x (\oplus denotes the operation bitwise XOR).An inversion in the b array is a pair of integers i and j such that 1 \le i < j \le n and b_i > b_j.You should choose x in such a way that the number of inversions in b is minimized. If there are several options for x — output the smallest one. | ['dp', 'greedy', 'bitmasks', 'math', 'divide and conquer', 'sortings', 'data structures', 'trees', 'strings'] | #!/usr/bin/env python
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():
n = int(input())
l = list(map(int, input().split()))
inv = 0
out = 0
mult = 1
for i in range(32):
curr = dict()
opp = 0
same = 0
for v in l:
if v ^ 1 in curr:
if v & 1:
opp += curr[v ^ 1]
else:
same += curr[v ^ 1]
if v not in curr:
curr[v] = 0
curr[v] += 1
for i in range(n):
l[i] >>= 1
if same <= opp:
inv += same
else:
inv += opp
out += mult
mult *= 2
print(inv, out)
# 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")
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 | [
"math",
"strings",
"trees"
] | 617 | 3,153 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 1
} | 2,129 |
080f29d4e2aa5bb9ee26d882362c8cd7 | YouKn0wWho has an integer sequence a_1, a_2, \ldots, a_n. He will perform the following operation until the sequence becomes empty: select an index i such that 1 \le i \le |a| and a_i is not divisible by (i + 1), and erase this element from the sequence. Here |a| is the length of sequence a at the moment of operation. Note that the sequence a changes and the next operation is performed on this changed sequence.For example, if a=[3,5,4,5], then he can select i = 2, because a_2 = 5 is not divisible by i+1 = 3. After this operation the sequence is [3,4,5].Help YouKn0wWho determine if it is possible to erase the whole sequence using the aforementioned operation. | ['brute force', 'greedy', 'math', 'number theory'] | import math
#'YES'
t = int(input())
for _ in range(t):
n = int(input())
arr = [int(i) for i in input().split()]
if arr[0] % 2 == 0:
print('NO')
else:
np = 0
lmp = 0
for i in range(n):
cur = i+1
if arr[i] % 2 != 0:
lmp += 1
else:
if arr[i] % (cur+1) != 0:
lmp += 1
else:
start = 0
temp = lmp
while temp > 0 and arr[i] % (cur+1-start) == 0:
temp -= 1
start += 1
if arr[i] % (cur+1-start) == 0:
np = 1
break
lmp += 1
if np:
print('NO')
else:
print('YES')
| Python | [
"math",
"number theory"
] | 744 | 587 | 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,037 |
a1739619b5ee88e22ae31f4d72bed90a | Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner.Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep up with the neighbours, they decided to call the baby so that the name was lexicographically strictly larger than the neighbour's son's name t.On the other hand, they suspect that a name tax will be introduced shortly. According to it, the Taucetians with lexicographically larger names will pay larger taxes. That's the reason abac and bbad want to call the newborn so that the name was lexicographically strictly larger than name t and lexicographically minimum at that.The lexicographical order of strings is the order we are all used to, the "dictionary" order. Such comparison is used in all modern programming languages to compare strings. Formally, a string p of length n is lexicographically less than string q of length m, if one of the two statements is correct: n < m, and p is the beginning (prefix) of string q (for example, "aba" is less than string "abaa"), p1 = q1, p2 = q2, ..., pk - 1 = qk - 1, pk < qk for some k (1 ≤ k ≤ min(n, m)), here characters in strings are numbered starting from 1. Write a program that, given string s and the heighbours' child's name t determines the string that is the result of permutation of letters in s. The string should be lexicographically strictly more than t and also, lexicographically minimum. | ['greedy', 'strings'] | a = raw_input()
b = raw_input()
c = {}
for i in xrange(26):
c[chr(i + 97)] = 0
for i in xrange(len(a)):
c[a[i]] += 1
pref = ''
ans = chr(255)
for i in xrange(min(len(a), len(b))):
j = chr(ord(b[i]) + 1)
while j <= 'z' and c[j] == 0:
j = chr(ord(j) + 1)
if j <= 'z':
suff = j
c[j] -= 1
for ch, num in sorted(c.iteritems()):
suff += ch * num
c[j] += 1
ans = pref + suff
if c[b[i]] == 0:
break;
pref += b[i]
c[b[i]] -= 1
if pref == b and len(b) < len(a):
ans = pref
for ch, num in sorted(c.iteritems()):
ans += ch * num
if ans == chr(255):
ans = -1
print ans
| Python | [
"strings"
] | 1,578 | 588 | 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,214 |
f32b9d3b5c93e566e16c1de963a159a8 | This is the hard version of the problem. The only difference is that in this version there are remove queries.Initially you have a set containing one element — 0. You need to handle q queries of the following types:+ x — add the integer x to the set. It is guaranteed that this integer is not contained in the set; - x — remove the integer x from the set. It is guaranteed that this integer is contained in the set; ? k — find the k\text{-mex} of the set. In our problem, we define the k\text{-mex} of a set of integers as the smallest non-negative integer x that is divisible by k and which is not contained in the set. | ['brute force', 'data structures', 'number theory'] | from collections import defaultdict
import math
from sys import stdin
input=lambda :stdin.readline()[:-1]
n=int(input())
query=[]
for i in range(n):
x,y=input().split()
y=int(y)
if x=='+':
query.append((0,y))
elif x=='-':
query.append((1,y))
else:
query.append((2,y))
D=max(1,int((n*math.log2(n))**0.5))
L=0
while L<n:
R=min(n,L+D)
s=set()
for x,y in query[:L]:
if x==0:
s.add(y)
if x==1:
s.remove(y)
removed=set()
memo={}
for x,y in query[L:R]:
if x==0:
s.add(y)
if y in removed:
removed.remove(y)
if x==1:
s.remove(y)
removed.add(y)
if x==2:
if y in memo:
tmp=memo[y]
else:
tmp=y
while tmp in s:
tmp+=y
memo[y]=tmp
ans=tmp
for i in removed:
if i%y==0:
ans=min(ans,i)
print(ans)
L=R | Python | [
"number theory"
] | 686 | 929 | 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,763 |
345e76bf67ae4342e850ab248211eb0b | The only difference between easy and hard versions is constraints.There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the p_i-th kid (in case of i = p_i the kid will give his book to himself). It is guaranteed that all values of p_i are distinct integers from 1 to n (i.e. p is a permutation). The sequence p doesn't change from day to day, it is fixed.For example, if n=6 and p=[4, 6, 1, 3, 5, 2] then at the end of the first day the book of the 1-st kid will belong to the 4-th kid, the 2-nd kid will belong to the 6-th kid and so on. At the end of the second day the book of the 1-st kid will belong to the 3-th kid, the 2-nd kid will belong to the 2-th kid and so on.Your task is to determine the number of the day the book of the i-th child is returned back to him for the first time for every i from 1 to n.Consider the following example: p = [5, 1, 2, 4, 3]. The book of the 1-st kid will be passed to the following kids: after the 1-st day it will belong to the 5-th kid, after the 2-nd day it will belong to the 3-rd kid, after the 3-rd day it will belong to the 2-nd kid, after the 4-th day it will belong to the 1-st kid. So after the fourth day, the book of the first kid will return to its owner. The book of the fourth kid will return to him for the first time after exactly one day.You have to answer q independent queries. | ['dsu', 'dfs and similar', 'math'] | from sys import stdin, stdout
t = int(stdin.readline())
def getRoot(i,par):
while i!=par[i]:
i = par[i]
return i
def find(a,b,par):
return getRoot(a,par)==getRoot(b,par)
def doUnion(a,b,par,size):
if find(a,b,par):
return False
r1 = getRoot(a,par)
r2 = getRoot(b,par)
s1 = size[r1]
s2 = size[r2]
if s1 > s2:
par[r2] = r1
size[r1] += s2
else:
par[r1] = r2
size[r2] += s1
return True
while t>0:
n = int(stdin.readline())
a = list( map(int,stdin.readline().split()) )
par,size = [ i for i in range(n+1) ], [ 1 for i in range(n+1) ]
for i in range(n):
x,y = i+1,a[i]
doUnion(x,y,par,size)
ans = []
for i in range(n):
c = size[ getRoot(i+1,par) ]
ans.append(c)
for i in range(len(ans)):
stdout.write("{} ".format(ans[i]))
stdout.write("\n")
t-=1 | Python | [
"graphs",
"math"
] | 1,609 | 920 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,272 |
94501cd676a9214a59943b8ddd1dd31b | As the guys fried the radio station facilities, the school principal gave them tasks as a punishment. Dustin's task was to add comments to nginx configuration for school's website. The school has n servers. Each server has a name and an ip (names aren't necessarily unique, but ips are). Dustin knows the ip and name of each server. For simplicity, we'll assume that an nginx command is of form "command ip;" where command is a string consisting of English lowercase letter only, and ip is the ip of one of school servers. Each ip is of form "a.b.c.d" where a, b, c and d are non-negative integers less than or equal to 255 (with no leading zeros). The nginx configuration file Dustin has to add comments to has m commands. Nobody ever memorizes the ips of servers, so to understand the configuration better, Dustin has to comment the name of server that the ip belongs to at the end of each line (after each command). More formally, if a line is "command ip;" Dustin has to replace it with "command ip; #name" where name is the name of the server with ip equal to ip.Dustin doesn't know anything about nginx, so he panicked again and his friends asked you to do his task for him. | ['implementation', 'strings'] | n,m = [int(x) for x in raw_input().split()]
arr = {}
for i in range(n):
a,b = [x for x in raw_input().split()]
b += ";"
arr[b] = a
for i in range(m):
a,b = [x for x in raw_input().split()]
c = "#"
c += arr[b]
print a,b,c | Python | [
"strings"
] | 1,181 | 227 | 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
} | 772 |
733b36bfc2b72200281477af875f8efa | Innokenty is a president of a new football league in Byteland. The first task he should do is to assign short names to all clubs to be shown on TV next to the score. Of course, the short names should be distinct, and Innokenty wants that all short names consist of three letters.Each club's full name consist of two words: the team's name and the hometown's name, for example, "DINAMO BYTECITY". Innokenty doesn't want to assign strange short names, so he wants to choose such short names for each club that: the short name is the same as three first letters of the team's name, for example, for the mentioned club it is "DIN", or, the first two letters of the short name should be the same as the first two letters of the team's name, while the third letter is the same as the first letter in the hometown's name. For the mentioned club it is "DIB". Apart from this, there is a rule that if for some club x the second option of short name is chosen, then there should be no club, for which the first option is chosen which is the same as the first option for the club x. For example, if the above mentioned club has short name "DIB", then no club for which the first option is chosen can have short name equal to "DIN". However, it is possible that some club have short name "DIN", where "DI" are the first two letters of the team's name, and "N" is the first letter of hometown's name. Of course, no two teams can have the same short name.Help Innokenty to choose a short name for each of the teams. If this is impossible, report that. If there are multiple answer, any of them will suit Innokenty. If for some team the two options of short name are equal, then Innokenty will formally think that only one of these options is chosen. | ['greedy', 'graphs', 'shortest paths', '2-sat', 'implementation', 'strings'] | n = int(input())
d = dict()
ans = []
arr = []
d2 = dict()
for i in range(n):
a, b = input().split()
a1, a2 = a[:3], a[0] + a[1] + b[0]
if a1 in d:
d[a1].append(a2)
else:
d[a1] = [a2]
if a2 in d2:
d2[a2].append((a1, i))
else:
d2[a2] = [(a1, i)]
ans.append(a2)
arr.append(a1)
for i in d:
if len(set(d[i])) != len(d[i]):
print('NO')
exit()
for i in d2:
if len(d2[i]) == 1:
continue
new_d = dict()
for j in d2[i]:
if j[0] in new_d:
new_d[j[0]].append(j[1])
else:
new_d[j[0]] = [j[1]]
for j in new_d:
if len(new_d[j]) > 1:
print('NO')
exit()
change = []
for j in new_d:
if len(d[j]) == 1:
change.append(new_d[j][0])
if len(change) < len(d2[i]) - 1:
print('NO')
exit()
for j in change:
ans[j] = arr[j][::]
if len(set(ans)) != len(ans):
print('NO')
exit()
print('YES')
print(*ans, sep='\n') | Python | [
"graphs",
"strings"
] | 1,739 | 1,031 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 1,
"trees": 0
} | 4,856 |
7c7acf9f91920cb00ed8cfcb0d3539e2 | Jeel and Ashish play a game on an n \times m matrix. The rows are numbered 1 to n from top to bottom and the columns are numbered 1 to m from left to right. They play turn by turn. Ashish goes first.Initially, each cell of the matrix contains a non-negative integer. Each turn, a player must perform all of the following actions in order. Choose a starting cell (r_1, c_1) with non-zero value. Choose a finishing cell (r_2, c_2) such that r_1 \leq r_2 and c_1 \leq c_2. Decrease the value of the starting cell by some positive non-zero integer. Pick any of the shortest paths between the two cells and either increase, decrease or leave the values of cells on this path unchanged. Note that: a shortest path is one that passes through the least number of cells; all cells on this path excluding the starting cell, but the finishing cell may be modified; the resulting value of each cell must be a non-negative integer; the cells are modified independently and not necessarily by the same value. If the starting and ending cells are the same, then as per the rules, the value of the cell is decreased. No other operations are performed.The game ends when all the values become zero. The player who is unable to make a move loses. It can be shown that the game will end in a finite number of moves if both players play optimally.Given the initial matrix, if both players play optimally, can you predict who will win? | ['constructive algorithms', 'games'] | def solve():
n, m = [int(x) for x in input().split()]
a = []
for i in range(n):
v =[int(x) for x in input().split()]
a.append(v)
xorsums = [0] * (n+m-1)
for i in range(n):
for j in range(m):
xorsums[i+j] ^= a[i][j]
f = 0
for i in range(n+m-1):
if xorsums[i] !=0:
f = 1
if f == 1:
print('Ashish')
else:
print('Jeel')
def main():
t = int(input())
for i in range(t):
solve()
main()
| Python | [
"games"
] | 1,479 | 515 | 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
} | 824 |
42b6ada19f6f6276bb2f99049e2b9b76 | Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b.You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, starting from some position. More formally, such numbers 1 ≤ i ≤ n and 1 ≤ j ≤ m - k + 1 should exist that G(i, j + l - 1) = al for all 1 ≤ l ≤ k.Determine if the sequence a occurs in table G. | ['number theory', 'chinese remainder theorem', 'math'] | '''
Created on Aug 28, 2016
@author: Md. Rezwanul Haque
'''
def gcd(a,b):
if b == 0:
return a
return gcd(b, a%b)
def extend_euclid(a,b):
if b == 0:
return 1,0
else:
y,x = extend_euclid(b, a%b)
y = y - (a//b)*x
return x,y
n,m,k = map(int,input().split())
a = list(map(int,input().split()))
lcm = 1
for i in a:
lcm = (lcm*i)//gcd(lcm, i)
if lcm>n:
print('NO')
exit()
j = 0
m1 = 1
s = True
for i in range(k):
x,y = extend_euclid(m1, a[i])
res = m1*x + a[i]*y
if (-i-j)%res != 0:
s = False
break
res = (-i-j)//res
x,y = x*res , y*res
j += m1*x
t = m1*a[i]
if j>t:
j -= (j//t)*t
if j<0:
j += ((-j+t-1)//t)*t
if j == 0:
j = t
m1 = (m1*a[i])//gcd(m1, a[i])
if j+k-1 >m or s == False:
print('NO')
exit()
b = [gcd(lcm, j+i) for i in range(k)]
for i in range(k):
if (a[i] != b[i]):
print('NO')
exit()
print('YES') | Python | [
"math",
"number theory"
] | 509 | 1,014 | 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,165 |
f0a138b9f6ad979c5ca32437e05d6f43 | You can't possibly imagine how cold our friends are this winter in Nvodsk! Two of them play the following game to warm up: initially a piece of paper has an integer q. During a move a player should write any integer number that is a non-trivial divisor of the last written number. Then he should run this number of circles around the hotel. Let us remind you that a number's divisor is called non-trivial if it is different from one and from the divided number itself. The first person who can't make a move wins as he continues to lie in his warm bed under three blankets while the other one keeps running. Determine which player wins considering that both players play optimally. If the first player wins, print any winning first move. | ['greedy', 'number theory', 'games', 'math'] | #!/usr/bin/env python
from sys import stdin as cin
def find_div(q):
d = 0
if q == 1:
return 1
if q % 2 == 0:
return 2
else:
for d in range(3, int(q**0.5) + 3, 2):
if q % d == 0:
return d
return q
def main():
q = int(next(cin))
if q == 1:
return 1,0
d = find_div(q)
if d in (1, q):
return 1,0
q = q // d
e = find_div(q)
if e in (1, q):
return 2,
else:
return 1, e * d
print '\n'.join(map(str, main()))
| Python | [
"number theory",
"math",
"games"
] | 737 | 442 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,810 |
c15bce9c4b9eddf5c8c3421b768da98c | You are given an array a[0 \ldots n - 1] = [a_0, a_1, \ldots, a_{n - 1}] of zeroes and ones only. Note that in this problem, unlike the others, the array indexes are numbered from zero, not from one.In one step, the array a is replaced by another array of length n according to the following rules: First, a new array a^{\rightarrow d} is defined as a cyclic shift of the array a to the right by d cells. The elements of this array can be defined as a^{\rightarrow d}_i = a_{(i + n - d) \bmod n}, where (i + n - d) \bmod n is the remainder of integer division of i + n - d by n. It means that the whole array a^{\rightarrow d} can be represented as a sequence a^{\rightarrow d} = [a_{n - d}, a_{n - d + 1}, \ldots, a_{n - 1}, a_0, a_1, \ldots, a_{n - d - 1}] Then each element of the array a_i is replaced by a_i \,\&\, a^{\rightarrow d}_i, where \& is a logical "AND" operator. For example, if a = [0, 0, 1, 1] and d = 1, then a^{\rightarrow d} = [1, 0, 0, 1] and the value of a after the first step will be [0 \,\&\, 1, 0 \,\&\, 0, 1 \,\&\, 0, 1 \,\&\, 1], that is [0, 0, 0, 1].The process ends when the array stops changing. For a given array a, determine whether it will consist of only zeros at the end of the process. If yes, also find the number of steps the process will take before it finishes. | ['brute force', 'graphs', 'math', 'number theory', 'shortest paths'] | for _ in range(int(input())):
n,d=map(int,input().split())
a = list(map(int, input().split()))
used = [False]*n
fail = False
res = 0
for i in range(n):
if used[i]:
continue
cur = i
pr = last = it = ans = 0
used[cur] = True
if (a[cur] == 0):
ans = max(ans, last)
last = 0
else:
last += 1
if (it == pr): pr+=1
cur = (cur+d)%n
it += 1
while cur != i:
used[cur] = True
if (a[cur] == 0):
ans = max(ans, last)
last = 0
else:
last += 1
if (it == pr): pr+=1
cur = (cur+d)%n
it += 1
if it != pr:
ans = max(ans, pr+last)
else:
fail = True
break
res = max(res, ans)
if fail:
print(-1)
continue
print(res) | Python | [
"graphs",
"number theory",
"math"
] | 1,469 | 1,001 | 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
} | 460 |
f60ea0f2caaec16894e84ba87f90c061 | Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction as a sum of three distinct positive fractions in form .Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that . Because Chloe can't check Vladik's answer if the numbers are large, he asks you to print numbers not exceeding 109.If there is no such answer, print -1. | ['constructive algorithms', 'number theory', 'brute force', 'math'] | n = int(raw_input())
if n==1: print "-1"
elif n==2: print "2 3 6"
else:
isAnswered = False
x = (n+1)/2
while x*2 < 3*n:
c = x*2-n
d = x*n
y = x + 1
while True:
if (2*x*y-n*x-n*y) <= 0:
y += 1
break
if (n*x*y) % (2*x*y-n*x-n*y) == 0:
z = (n*x*y) / (2*x*y-n*x-n*y)
print "%d %d %d" % (x,y,z)
isAnswered = True
break
y += 1
x += 1
if isAnswered: break | Python | [
"number theory",
"math"
] | 452 | 540 | 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,965 |
b3c08abbaeec9ecbcc71fe34336d039a | A wild basilisk just appeared at your doorstep. You are not entirely sure what a basilisk is and you wonder whether it evolved from your favorite animal, the weasel. How can you find out whether basilisks evolved from weasels? Certainly, a good first step is to sequence both of their DNAs. Then you can try to check whether there is a sequence of possible mutations from the DNA of the weasel to the DNA of the basilisk. Your friend Ron is a talented alchemist and has studied DNA sequences in many of his experiments. He has found out that DNA strings consist of the letters A, B and C and that single mutations can only remove or add substrings at any position in the string (a substring is a contiguous sequence of characters). The substrings that can be removed or added by a mutation are AA, BB, CC, ABAB or BCBC. During a sequence of mutations a DNA string may even become empty.Ron has agreed to sequence the DNA of the weasel and the basilisk for you, but finding out whether there is a sequence of possible mutations that leads from one to the other is too difficult for him, so you have to do it on your own. | ['greedy', 'implementation', 'strings'] |
strings = ['AA', 'BB', 'CC', 'ABAB', 'BCBC']
reduction = [['AA', ''], ['BB', ''], ['CC', ''], ['ABAB', ''], ['BCBC', ''],
['CB', 'BC'], ['AB', 'BA']] # move all Bs left
# def simulator():
# s = 'CA'
# # get all possible outcomes from s
# l = len(s)
# vi = set()
# vi.add(s)
# st = [s]
# while st:
# s = st.pop()
# n = len(s)
# for s2 in strings:
# for i in range(n + 1):
# # remove
# if s[i: i + len(s2)] == s2:
# s3 = s[:i] + s[i + len(s2):]
# if s3 not in vi:
# st.append(s3)
# vi.add(s3)
# # add
# s3 = s[: i] + s2 + s[i:]
# # if s3 == 'ABAB':
# # print('s2:{}'.format(s2))
# if len(s3) <= l + 8 and s3 not in vi:
# st.append(s3)
# vi.add(s3)
# for s in vi:
# if len(s) <= l + 2:
# print(s)
# simulator()
def reduce_string(s):
changed = 1
while changed == 1:
changed = 0
for complex_form, reduced_form in reduction:
if complex_form in s:
s = s.replace(complex_form, reduced_form)
changed = 1
return s
def main():
T = int(input())
allans = []
for _ in range(T):
s = input()
t = input()
s2 = reduce_string(s)
t2 = reduce_string(t)
# print('s:{} t:{} s2:{} t2:{}'.format(s, t, s2, t2))
if s2 == t2:
ans = 'YES'
else:
ans = 'NO'
allans.append(ans)
multiLineArrayPrint(allans)
return
import sys
# input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
# def readFloatArr():
# return [float(x) for x in input().split()]
def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m])
dv=defaultValFactory;da=dimensionArr
if len(da)==1:return [dv() for _ in range(da[0])]
else:return [makeArr(dv,da[1:]) for _ in range(da[0])]
def queryInteractive(a, b, c):
print('? {} {} {}'.format(a, b, c))
sys.stdout.flush()
return int(input())
def answerInteractive(x1, x2):
print('! {} {}'.format(x1, x2))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
# MOD=998244353
from math import gcd,floor,ceil
import math
# from math import floor,ceil # for Python2
for _abc in range(1):
main() | Python | [
"strings"
] | 1,120 | 3,033 | 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,304 |
bc3d0d902ef457560e444ec0128f0688 | Oleg the client and Igor the analyst are good friends. However, sometimes they argue over little things. Recently, they started a new company, but they are having trouble finding a name for the company.To settle this problem, they've decided to play a game. The company name will consist of n letters. Oleg and Igor each have a set of n letters (which might contain multiple copies of the same letter, the sets can be different). Initially, the company name is denoted by n question marks. Oleg and Igor takes turns to play the game, Oleg moves first. In each turn, a player can choose one of the letters c in his set and replace any of the question marks with c. Then, a copy of the letter c is removed from his set. The game ends when all the question marks has been replaced by some letter.For example, suppose Oleg has the set of letters {i, o, i} and Igor has the set of letters {i, m, o}. One possible game is as follows :Initially, the company name is ???.Oleg replaces the second question mark with 'i'. The company name becomes ?i?. The set of letters Oleg have now is {i, o}.Igor replaces the third question mark with 'o'. The company name becomes ?io. The set of letters Igor have now is {i, m}.Finally, Oleg replaces the first question mark with 'o'. The company name becomes oio. The set of letters Oleg have now is {i}.In the end, the company name is oio.Oleg wants the company name to be as lexicographically small as possible while Igor wants the company name to be as lexicographically large as possible. What will be the company name if Oleg and Igor always play optimally?A string s = s1s2...sm is called lexicographically smaller than a string t = t1t2...tm (where s ≠ t) if si < ti where i is the smallest index such that si ≠ ti. (so sj = tj for all j < i) | ['greedy', 'sortings', 'games'] | s1 = input()
s2 = input()
n = len(s1)
s1 = sorted(s1)
s2 = sorted(s2)[::-1]
i = 0
j = 0
res = ["?"]*n
rear = n-1
front = 0
Neven = n % 2 == 0
n1 = (n+1)//2 - 1
n2 = n//2 - 1
for k in range(n):
if k % 2 == 0:
if s1[i] < s2[j]:
res[front] = s1[i]
front += 1
i += 1
else:
res[rear] = s1[n1]
rear -= 1
n1 -= 1
else:
if s1[i] < s2[j]:
res[front] = s2[j]
front += 1
j += 1
else:
res[rear] = s2[n2]
rear -= 1
n2 -= 1
print("".join(res)) | Python | [
"games"
] | 1,784 | 621 | 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
} | 694 |
55a83526c10126ac3a6e6e5154b120d0 | On the math lesson a teacher asked each pupil to come up with his own lucky numbers. As a fan of number theory Peter chose prime numbers. Bob was more original. He said that number t is his lucky number, if it can be represented as: t = a2 + b2, where a, b are arbitrary positive integers.Now, the boys decided to find out how many days of the interval [l, r] (l ≤ r) are suitable for pair programming. They decided that the day i (l ≤ i ≤ r) is suitable for pair programming if and only if the number i is lucky for Peter and lucky for Bob at the same time. Help the boys to find the number of such days. | ['number theory', 'brute force', 'math'] | f = lambda x: int(x**.5)+1
h,z = map(bytearray,'1\0')
L,R = map(int,raw_input().split())
n = f(R); b = n/2*h; b[0] = 0
for k in xrange(1,f(n)/2):
if b[k]: p = 2*k+1; s = k*(p+1); b[s::p] = z*len(b[s::p])
g = ((i*(i+1),2*i+1) for i,v in enumerate(b) if v)
r = (R+3)/4*h; r[0] = 0
for s,p in g:
r[s::p] = z*len(r[s::p])
print r.count(h,(L+2)/4)+(L<=2<=R)
| Python | [
"math",
"number theory"
] | 606 | 366 | 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,409 |
d15a758cfdd7a627822fe8be7db4f60b | You are given an array a of n integers.You want to make all elements of a equal to zero by doing the following operation exactly three times: Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different). It can be proven that it is always possible to make all elements of a equal to zero. | ['constructive algorithms', 'number theory', 'greedy', 'math'] | # -*- coding: utf-8 -*-
import sys
# sys.setrecursionlimit(10**6)
# buff_readline = sys.stdin.buffer.readline
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(buff_readline())
def read_int_n():
return list(map(int, buff_readline().split()))
def read_float():
return float(buff_readline())
def read_float_n():
return list(map(float, buff_readline().split()))
def read_str():
return readline().strip()
def read_str_n():
return readline().strip().split()
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
def divisor(n):
for i in range(1, int(n**0.5)+1):
if n % i == 0:
yield i
if i != n // i:
yield n // i
@mt
def slv(N, A):
if N == 1:
print(1, 1)
print(-A[0])
print(1, 1)
print(0)
print(1, 1)
print(0)
return
a = A[:]
na = a[:]
error_print([-na[i] % N for i in range(N)])
for i in range(N-1):
if a[i] > 0:
na[i] = a[i] + (a[i] % N) * (N-1)
else:
na[i] = a[i] - (N - (a[i] % N)) * (N-1)
print(1, N-1)
print(*[na[i] - a[i] for i in range(N-1)])
a = na[:]
for i in range(N-1, N):
if a[i] > 0:
na[i] = a[i] - (a[i] % N)
else:
na[i] = a[i] - (a[i] % N)
print(N, N)
print(*[na[i] - a[i] for i in range(N-1, N)])
print(1, N)
print(*[-na[i] for i in range(N)])
error_print(na)
error_print([-na[i]%N for i in range(N)])
def main():
N = read_int()
A = read_int_n()
slv(N, A)
if __name__ == '__main__':
main()
| Python | [
"number theory",
"math"
] | 424 | 1,898 | 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,795 |
23fc2595e2813d0817e3cc0f1bb22eae | There are n students and m clubs in a college. The clubs are numbered from 1 to m. Each student has a potential p_i and is a member of the club with index c_i. Initially, each student is a member of exactly one club. A technical fest starts in the college, and it will run for the next d days. There is a coding competition every day in the technical fest. Every day, in the morning, exactly one student of the college leaves their club. Once a student leaves their club, they will never join any club again. Every day, in the afternoon, the director of the college will select one student from each club (in case some club has no members, nobody is selected from that club) to form a team for this day's coding competition. The strength of a team is the mex of potentials of the students in the team. The director wants to know the maximum possible strength of the team for each of the coming d days. Thus, every day the director chooses such team, that the team strength is maximized.The mex of the multiset S is the smallest non-negative integer that is not present in S. For example, the mex of the \{0, 1, 1, 2, 4, 5, 9\} is 3, the mex of \{1, 2, 3\} is 0 and the mex of \varnothing (empty set) is 0. | ['graph matchings', 'flows', 'graphs'] | import sys
input = sys.stdin.readline
n, m = map(int, input().split())
p = list(map(int, input().split()))
c = list(map(int, input().split()))
d = int(input())
disable = [False] * n
base = 5001
ds = [int(input())-1 for _ in range(d)]
for ele in ds:
disable[ele] = True
# Create Graph
childs = [[] for i in range(base+m+1)]
for idx, (i, j) in enumerate(zip(p, c)):
if not disable[idx]:
childs[i].append(base+j)
# dfs
# alternative path for finding maximum cardinality
vis = [False]*(base+m+1)
matching = [-1]*(base+m+1)
def dfs(num):
for child in childs[num]:
if not vis[child]:
vis[child] = True
if matching[child] == -1 or dfs(matching[child]):
matching[child] = num
return True
return False
ans = []
mex = 0
for idx in range(d-1, -1, -1):
while True:
vis = [False]*(base+m+1)
if not dfs(mex):
break
mex += 1
# Add edge
ans.append(mex)
childs[p[ds[idx]]].append(base+c[ds[idx]])
print("\n".join([str(a) for a in reversed(ans)])) | Python | [
"graphs"
] | 1,301 | 1,080 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,836 |
460c075df98b4a61786e76c0ecff8311 | Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence P. For example, if n = 3, then P = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence is n \cdot n!.Let 1 \leq i \leq j \leq n \cdot n! be a pair of indices. We call the sequence (P_i, P_{i+1}, \dots, P_{j-1}, P_j) a subarray of P. You are given n. Find the number of distinct subarrays of P. Since this number may be large, output it modulo 998244353 (a prime number). | ['string suffix structures'] | import math
def f(n):
l = math.factorial(n)*n
ans = l * (l-n+2) // 2
for i in range(1,n):
ans -= math.factorial(n)//math.factorial(i+1)*n*(i*(n-i)-1)
return ans
def solve(n):
M = 998244353
p = n
a = 0
for i in range(n,1,-1):
a=(a+p*(i-1)*(n-i+1)-p)%M
p=p*i%M
a = (p*(p-n+2)-2*a)%M
if a&1:a+=M
return a//2
x = int(input())
ans = solve(x)
print(ans)
| Python | [
"strings"
] | 614 | 420 | 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,094 |
10efa17a66af684dbc13c456ddef1b1b | You have written on a piece of paper an array of n positive integers a[1], a[2], ..., a[n] and m good pairs of integers (i1, j1), (i2, j2), ..., (im, jm). Each good pair (ik, jk) meets the following conditions: ik + jk is an odd number and 1 ≤ ik < jk ≤ n.In one operation you can perform a sequence of actions: take one of the good pairs (ik, jk) and some integer v (v > 1), which divides both numbers a[ik] and a[jk]; divide both numbers by v, i. e. perform the assignments: and . Determine the maximum number of operations you can sequentially perform on the given array. Note that one pair may be used several times in the described operations. | ['graph matchings', 'flows', 'number theory'] | def g(i):
u[i] = 0
for j in p[i]:
if v[j] < 0 or u[v[j]] and g(v[j]):
v[j] = i
return 1
return 0
f = lambda: map(int, input().split())
n, m = f()
s = k = 0
d = [[]]
for i in f():
j = 2
t = []
while j * j <= i:
while i % j == 0:
t.append((j, k))
k += 1
i //= j
j += 1
if i > 1:
t.append((i, k))
k += 1
d.append(t)
p = [[] for i in range(k)]
for q in range(m):
a, b = f()
if b % 2: a, b = b, a
for x, i in d[a]:
for y, j in d[b]:
if x == y: p[i].append(j)
v = [-1] * k
for i in range(k):
u = [1] * k
s += g(i)
print(s)
| Python | [
"graphs",
"number theory"
] | 658 | 690 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 1,
"math": 0,
"number theory": 1,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 4,209 |
7e709765bf4fb07b2a4d68bff8a12698 | Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric.The piece of the multicolored fabric consists of n \times m separate square scraps. Since Rarity likes dresses in style, a dress pattern must only include scraps sharing the same color. A dress pattern must be the square, and since Rarity is fond of rhombuses, the sides of a pattern must form a 45^{\circ} angle with sides of a piece of fabric (that way it will be resembling the traditional picture of a rhombus).Examples of proper dress patterns: Examples of improper dress patterns: The first one consists of multi-colored scraps, the second one goes beyond the bounds of the piece of fabric, the third one is not a square with sides forming a 45^{\circ} angle with sides of the piece of fabric.Rarity wonders how many ways to cut out a dress pattern that satisfies all the conditions that do exist. Please help her and satisfy her curiosity so she can continue working on her new masterpiece! | ['dp', 'implementation', 'dfs and similar', 'shortest paths'] | from sys import stdin, stdout
def rarity_and_new_dress(n, m, s_a):
dp = [[1 for j in range(m)] for i in range(n)]
res = 0
for i in range(n):
for j in range(m):
if i > 1 and 0 < j < m - 1 and s_a[i][j] == s_a[i-1][j-1] == s_a[i-1][j] == s_a[i-1][j+1] == s_a[i-2][j]:
dp[i][j] += min(dp[i-1][j-1], dp[i-1][j], dp[i-1][j+1], dp[i-2][j])
res += dp[i][j]
return res
n, m = map(int, stdin.readline().split())
s_a = []
for _ in range(n):
s_a.append(stdin.readline().strip())
ans = rarity_and_new_dress(n, m, s_a)
stdout.write(str(ans) + '\n')
| Python | [
"graphs"
] | 1,227 | 612 | 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,994 |
98e3182f047a7e7b10be7f207b219267 | Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times: A BC B AC C AB AAA empty string Note that a substring is one or more consecutive characters. For given queries, determine whether it is possible to obtain the target string from source. | ['constructive algorithms', 'implementation', 'strings'] | def read():
s = input()
l = len(s)
r = [[0] * (l + 1), [0] * (l + 1)]
for i in range(l):
r[0][i + 1] = (r[0][i] + 1) * (s[i] == 'A')
r[1][i + 1] = r[1][i] + (s[i] != 'A')
return r
s, t = read(), read()
q = int(input())
r = ''
for i in range(q):
a, b, c, d = map(int, input().split())
sb = s[1][b] - s[1][a] + (s[0][a] == 0)
sa = s[0][b] - (s[0][a] - 1) * (sb == 0)
tb = t[1][d] - t[1][c] + (t[0][c] == 0)
ta = t[0][d] - (t[0][c] - 1) * (tb == 0)
if any([sb > tb, sa < ta, tb - sb & 1, sb == tb and (sa - ta) % 3, sa == ta and not sb and tb]):
r += '0'
else:
r += '1'
print(r)
| Python | [
"strings"
] | 359 | 656 | 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,773 |
b4183febe5ae61770368d2e16f273675 | Let's call the string beautiful if it does not contain a substring of length at least 2, which is a palindrome. Recall that a palindrome is a string that reads the same way from the first character to the last and from the last character to the first. For example, the strings a, bab, acca, bcabcbacb are palindromes, but the strings ab, abbbaa, cccb are not.Let's define cost of a string as the minimum number of operations so that the string becomes beautiful, if in one operation it is allowed to change any character of the string to one of the first 3 letters of the Latin alphabet (in lowercase).You are given a string s of length n, each character of the string is one of the first 3 letters of the Latin alphabet (in lowercase).You have to answer m queries — calculate the cost of the substring of the string s from l_i-th to r_i-th position, inclusive. | ['brute force', 'constructive algorithms', 'dp', 'strings'] | a = [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
stt = [3, 5, 1, 4, 0, 2]
stt2 = [[3, 4, 0], [5, 2, 1], [1, 5, 2], [4, 0, 3], [0, 3, 4], [2, 1, 5]]
# def query(l, r):
# minimum = 9999999
# for ii in range(6):
# if r >= n-1:
# minimum = min(minimum, dp[l][ii])
# else:
# pos = ii
# time = (r-l+1)%3
# for k in range(time):
# pos = stt[pos]
# print(ii, pos)
# minimum = min(minimum, dp[l][ii] - dp[r+1][pos])
# return minimum
n, m = [int(x) for x in input().split(' ')]
s = input()
# s = 'c'*200000
ss =[ ord(x)-96 for x in s]
dp = [[0 for i in range(6)] for j in range(n)]
# DP here
for ii in range(6):
if a[ii][0] != ss[n-1]:
dp[n-1][ii] = 1
for ii in range(n-2, -1, -1):
for jj in range(6):
dp[ii][jj] = dp[ii+1][stt[jj]]
if a[jj][0] != ss[ii]:
dp[ii][jj] += 1
res = []
for t in range(m):
l, r = [int(x)-1 for x in input().split(' ')]
# print(query(l, r))
minimum = 9999999
if r >= n-1:
for ii in range(6):
minimum = min(dp[l])
res.append(minimum)
else:
pos = (r-l) % 3
minimum = min([dp[l][ii] - dp[r+1][stt2[ii][pos]] for ii in range(6)])
res.append(minimum)
# print(minimum)
print(*res, sep = "\n")
| Python | [
"strings"
] | 915 | 1,366 | 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
} | 240 |
c01e33f3d0c31f1715d8ff118970f42e | Alice and Bob are playing a game. They are given an array A of length N. The array consists of integers. They are building a sequence together. In the beginning, the sequence is empty. In one turn a player can remove a number from the left or right side of the array and append it to the sequence. The rule is that the sequence they are building must be strictly increasing. The winner is the player that makes the last move. Alice is playing first. Given the starting array, under the assumption that they both play optimally, who wins the game? | ['games', 'greedy', 'two pointers'] | """
E. Array Game
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
Alice and Bob are playing a game. They are given an array A of length N.
The array consists of integers. They are building a sequence together.
In the beginning, the sequence is empty.
In one turn a player can remove a number from the left or right side of the array
and append it to the sequence. The rule is that the sequence they are building must be strictly increasing.
The winner is the player that makes the last move. Alice is playing first.
Given the starting array, under the assumption that they both play optimally, who wins the game?
Input
The first line contains one integer N (1≤N≤2∗105) - the length of the array A.
The second line contains N integers A1, A2,...,AN (0≤Ai≤109)
Output
The first and only line of output consists of one string, the name of the winner.
If Alice won, print "Alice", otherwise, print "Bob".
"""
from collections import deque
def array_game(n, array):
left = 0
right = n - 1
while left < n - 1 and array[left] < array[left + 1]:
left += 1
while right >= 0 and array[right] < array[right - 1]:
right -= 1
if left % 2 == 0 or (n - right) % 2 == 1:
print("Alice")
else:
print("Bob")
if __name__ == '__main__':
N = int(input())
integers = input().split(" ")
integers = [int(el) for el in integers]
array_game(N, integers)
# array_game(1, [5])
# array_game(3, [5, 4, 5])
# array_game(6, [5, 8, 2, 1, 10, 9])
| Python | [
"games"
] | 558 | 1,611 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | {
"games": 1,
"geometry": 0,
"graphs": 0,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,820 |
8f34d2a146ff44ff4ea82fb6481d10e2 | You are given a simple weighted connected undirected graph, consisting of n vertices and m edges.A path in the graph of length k is a sequence of k+1 vertices v_1, v_2, \dots, v_{k+1} such that for each i (1 \le i \le k) the edge (v_i, v_{i+1}) is present in the graph. A path from some vertex v also has vertex v_1=v. Note that edges and vertices are allowed to be included in the path multiple times.The weight of the path is the total weight of edges in it.For each i from 1 to q consider a path from vertex 1 of length i of the maximum weight. What is the sum of weights of these q paths?Answer can be quite large, so print it modulo 10^9+7. | ['dp', 'binary search', 'geometry', 'graphs'] | import sys
range = xrange
input = raw_input
n,m,q = [int(x) for x in input().split()]
V = []
W = []
coupl = [[] for _ in range(n)]
for _ in range(m):
a,b,w = [int(x) - 1 for x in input().split()]
w += 1
W.append(w)
eind = len(V)
V.append(b)
V.append(a)
coupl[a].append(eind)
coupl[b].append(eind ^ 1)
DP = [[-1]*n for _ in range(n)]
DP[0][0] = 0
for j in range(1, n):
prevDP = DP[j - 1]
newDP = DP[j]
for node in range(n):
if prevDP[node] == -1:
continue
for eind in coupl[node]:
nei = V[eind]
newDP[nei] = max(newDP[nei], prevDP[node] + W[eind >> 1])
ans = 0
for dp in DP:
ans += max(dp)
M = DP[-1]
K = []
for node in range(n):
K.append(max(W[eind >> 1] for eind in coupl[node]))
K = [K[i] for i in range(n) if M[i] >= 0]
M = [M[i] for i in range(n) if M[i] >= 0]
def solve(K, M, a, b):
hulli, hullx = convex_hull(K, M)
def sqsum(n):
return n * (n + 1) >> 1
n = len(hulli)
ans = 0
# iterate over all n intervalls
for i in range(n):
j = hulli[i]
k,m = K[j],M[j]
l = max(a, hullx[i - 1] + 1 if i else a)
r = min(b - 1, hullx[i] if i + 1 < n else b - 1)
if l <= r:
ans += m * (r - l + 1)
ans += k * (sqsum(r) - sqsum(l - 1))
return ans
# hulli[0] hulli[1] hulli[-1]
#
# (inf, hullx[0]], (hullx[0], hullx[1]], ..., (hullx[-1], inf)
#
def convex_hull(K, M, integer = True):
# assert len(K) == len(M)
if integer:
intersect = lambda i,j: (M[j] - M[i]) // (K[i] - K[j])
else:
intersect = lambda i,j: (M[j] - M[i]) / (K[i] - K[j])
hulli = []
hullx = []
order = sorted(range(len(K)), key = K.__getitem__)
for i in order:
while True:
if not hulli:
hulli.append(i)
hullx.append(-1)
break
elif K[hulli[-1]] == K[i]:
if M[hulli[-1]] >= M[i]:
break
hulli.pop()
hullx.pop()
else:
x = intersect(i, hulli[-1])
if len(hulli) > 1 and x <= hullx[-1]:
hullx.pop()
hulli.pop()
else:
hullx.append(x)
hulli.append(i)
break
return hulli, hullx[1:]
ans += solve(K, M, 1, q - (n - 1) + 1)
print ans % (10 ** 9 + 7)
| Python | [
"graphs",
"geometry"
] | 747 | 2,502 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 1,
"graphs": 1,
"math": 0,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 3,160 |
38bee9c2b21d2e91fdda931c8cacf204 | In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the stars, so he knew that they are exactly n. This time he wanted a challenge. He imagined a coordinate system: he put the origin of the coordinates at the intersection of the roof and the chimney, directed the OX axis to the left along the roof and the OY axis — up along the chimney (see figure). The Donkey imagined two rays emanating from he origin of axes at angles α1 and α2 to the OX axis. Now he chooses any star that lies strictly between these rays. After that he imagines more rays that emanate from this star at the same angles α1 and α2 to the OX axis and chooses another star that lies strictly between the new rays. He repeats the operation as long as there still are stars he can choose between the rays that emanate from a star. As a result, the Donkey gets a chain of stars. He can consecutively get to each star if he acts by the given rules.Your task is to find the maximum number of stars m that the Donkey's chain can contain.Note that the chain must necessarily start in the point of the origin of the axes, that isn't taken into consideration while counting the number m of stars in the chain. | ['dp', 'geometry', 'math', 'sortings', 'data structures'] | import bisect
def INPUT():
global n, a, b, c, d
n = int(input())
a, b, c, d = [int(j) for i in input().split() for j in i.split("/")]
global y_alpha
y_alpha = []
for _ in range(n):
x, y = [int(x) for x in input().split()]
y_alpha.append((b * y - a * x, c * x - d * y))
if __name__ == '__main__':
INPUT()
y_alpha = sorted([(x, y) for x, y in y_alpha if x > 0 and y > 0], key = lambda x: (x[0], -x[1]))
dp = []
for x, y in y_alpha:
i = bisect.bisect_left(dp, y)
if i == len(dp):
dp.append(y)
else:
dp[i] = y;
print(len(dp));
| Python | [
"math",
"geometry"
] | 1,438 | 556 | 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,070 |
5a146d9d360228313006d54cd5ca56ec | Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges).Let's define dist(v, u) as the sum of the integers written on the edges of the simple path from v to u.The vertex v controls the vertex u (v ≠ u) if and only if u is in the subtree of v and dist(v, u) ≤ au.Alyona wants to settle in some vertex. In order to do this, she wants to know for each vertex v what is the number of vertices u such that v controls u. | ['graphs', 'data structures', 'binary search', 'dfs and similar', 'trees'] | import sys
import threading
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
e = {}
g = [[] for i in range(n)]
d = [0]*(n+5)
ans = [0]*n
p = [0]*(n+5)
for i in range(n-1):
c, w = map(int, input().split())
c-= 1
g[c].append(i+1)
e[i+1] = w
def dfs(i, h):
global ans, a, e, g, d, p
p[h]=0
for j in g[i]:
d[h+1] = d[h]+e[j]
dfs(j, h+1)
x = bisect_left(d, d[h]-a[i], 0, h+1)
#print(x-1, i, h, d[h], d[h], a[i])
if x>=0:
p[x-1]-=1
p[h-1]+=p[h]+1
ans[i]=p[h]
def solve():
global ans
dfs(0, 0)
print(' '.join(map(str, ans)))
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start() | Python | [
"graphs",
"trees"
] | 630 | 872 | 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,000 |
a213bc75245657907c0ae28b067985f2 | You are given a string s of length n consisting of lowercase English letters.For two given strings s and t, say S is the set of distinct characters of s and T is the set of distinct characters of t. The strings s and t are isomorphic if their lengths are equal and there is a one-to-one mapping (bijection) f between S and T for which f(si) = ti. Formally: f(si) = ti for any index i, for any character there is exactly one character that f(x) = y, for any character there is exactly one character that f(x) = y. For example, the strings "aababc" and "bbcbcz" are isomorphic. Also the strings "aaaww" and "wwwaa" are isomorphic. The following pairs of strings are not isomorphic: "aab" and "bbb", "test" and "best".You have to handle m queries characterized by three integers x, y, len (1 ≤ x, y ≤ n - len + 1). For each query check if two substrings s[x... x + len - 1] and s[y... y + len - 1] are isomorphic. | ['hashing', 'strings'] | 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, m = getIntList()
s=input();
orda=ord('a');
a=[ord(s[i])-orda for i in range(n)];
countSame=[1]*n;
upLim=0;
for lowLim in range(n):
if lowLim<upLim:
continue;
for upLim in range(lowLim+1, n):
if a[upLim]!=a[lowLim]:
break;
else:
upLim+=1;
for i in range(lowLim, upLim):
countSame[i]=upLim-i;
def test(x, y, l):
map1=[0]*27;
map2=[0]*27;
count=0;
lowLim=min(countSame[x], countSame[y])-1;
for i in range(lowLim, l):
x1=map1[a[x+i]];
x2=map2[a[y+i]];
if x1!=x2:
return 'NO';
if x1==0:
count+=1;
map1[a[x+i]]=count;
map2[a[y+i]]=count;
return 'YES';
results=[];
for _ in range(m):
x, y, l=getIntList();
results.append(test(x-1, y-1, l));
print('\n'.join(results)); | Python | [
"strings"
] | 917 | 1,188 | 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,983 |
bd6f4859e3c3ce19b8e89c431f2e65fb | Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.Let's represent the city as an area of n \times n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the block with coordinates (f_x,f_y). In one minute Yura can move to any neighboring by side block; in other words, he can move in four directions. Also, there are m instant-movement locations in the city. Their coordinates are known to you and Yura. Yura can move to an instant-movement location in no time if he is located in a block with the same coordinate x or with the same coordinate y as the location.Help Yura to find the smallest time needed to get home. | ['graphs', 'sortings', 'shortest paths'] | import heapq
def main():
n, m = map(int, input().split())
sx, sy, fx, fy = map(int, input().split())
sub = [0]*(m+2)
sub[0] = (sx,sy)
dx = []
dy = []
for i in range(m):
x, y = map(int, input().split())
dx.append((x, i+1))
dy.append((y, i+1))
sub[i+1] = (x, y)
dx.append((sx,0))
dy.append((sy,0))
dx.sort()
dy.sort()
G = [[] for i in range(m+2)]
d = [2*10**9]*(m+2)
for i in range(m):
px, pindex = dx[i]
nx, nindex = dx[i+1]
G[pindex].append((nx-px, nindex))
G[nindex].append((nx-px, pindex))
for i in range(m):
py, pindex = dy[i]
ny, nindex = dy[i+1]
G[pindex].append((ny-py, nindex))
G[nindex].append((ny-py, pindex))
for i in range(m+1):
x, y = sub[i]
min_cost = abs(y-fy)+abs(x-fx)
G[m+1].append((min_cost, i))
G[i].append((min_cost, m+1))
que = []
heapq.heapify(que)
d[0] = 0
heapq.heappush(que, (0, 0))
while que:
cost, v = heapq.heappop(que)
if d[v] < cost:
continue
for cost, node in G[v]:
if d[node] > d[v] + cost:
d[node] = d[v] + cost
heapq.heappush(que, (d[node], node))
ans = d[m+1]
print(ans)
return
if __name__ == "__main__":
main() | Python | [
"graphs"
] | 819 | 1,376 | 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
} | 598 |
ac77e2e6c86b5528b401debe9f68fc8e | Alice guesses the strings that Bob made for her.At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.Bob builds b from a as follows: he writes all the substrings of length 2 of the string a in the order from left to right, and then joins them in the same order into the string b.For example, if Bob came up with the string a="abac", then all the substrings of length 2 of the string a are: "ab", "ba", "ac". Therefore, the string b="abbaac".You are given the string b. Help Alice to guess the string a that Bob came up with. It is guaranteed that b was built according to the algorithm given above. It can be proved that the answer to the problem is unique. | ['implementation', 'strings'] | x = int (input())
z = [0 for i in range(x)]
for y in range(0, x):
z[y] = str (input())
for y in range(0, x):
a = z[y]
u = int (len(a) / 2)
f = [0 for i in range(u + 1)]
f[0] = a[0]
for q in range(0, u):
f[q] = a[q * 2]
f[len(f) - 1] = a[len(a) - 1]
z[y] = f
for y in range(0, x):
delimiter = ''
output = delimiter.join(z[y])
print(output) | Python | [
"strings"
] | 967 | 377 | 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
} | 246 |
7100fa11adfa0c1f5d33f9e3a1c3f352 | Pak Chanek has n two-dimensional slices of cheese. The i-th slice of cheese can be represented as a rectangle of dimensions a_i \times b_i. We want to arrange them on the two-dimensional plane such that: Each edge of each cheese is parallel to either the x-axis or the y-axis. The bottom edge of each cheese is a segment of the x-axis. No two slices of cheese overlap, but their sides can touch. They form one connected shape. Note that we can arrange them in any order (the leftmost slice of cheese is not necessarily the first slice of cheese). Also note that we can rotate each slice of cheese in any way as long as all conditions still hold.Find the minimum possible perimeter of the constructed shape. | ['geometry', 'greedy', 'sortings'] | t = int(input())
while t > 0:
t-=1
n = int(input()) # number of slices
x = n
slicesH = []
slicesW = []
totala = 0
totalb = 0
currw = 0
currh = 0
existingh = []
slicesH2 = []
slicesW2 = []
existingh2 = []
while x>0:
x-=1
a,b = map(int, input().split())
h = 0
w = 0
h = max(a,b)
w = min(a,b)
slicesH.append(h)
slicesW.append(w)
d = {i:ix for ix, i in enumerate(slicesH)}
slicesH = sorted(slicesH)
slicesW = sorted(slicesW, key=lambda x: d.get(x, float('inf')))
slicesH.reverse()
slicesW.reverse()
#print(slicesH)
#print(slicesW)
prevh = 0
top = 0
bottom = 0
sides = 0
for x in range(len(slicesH)):
top += slicesW[x]*2
hdiff = abs(slicesH[x]-prevh)
sides+=hdiff
prevh = slicesH[x]
sides+= prevh
print(top+bottom+sides)
| Python | [
"geometry"
] | 728 | 1,023 | 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,741 |
0fd45a1eb1fc23e579048ed2beac7edd | Monocarp is a tutor of a group of n students. He communicates with them using a conference in a popular messenger.Today was a busy day for Monocarp — he was asked to forward a lot of posts and announcements to his group, that's why he had to write a very large number of messages in the conference. Monocarp knows the students in the group he is tutoring quite well, so he understands which message should each student read: Monocarp wants the student i to read the message m_i.Of course, no one's going to read all the messages in the conference. That's why Monocarp decided to pin some of them. Monocarp can pin any number of messages, and if he wants anyone to read some message, he should pin it — otherwise it will definitely be skipped by everyone.Unfortunately, even if a message is pinned, some students may skip it anyway. For each student i, Monocarp knows that they will read at most k_i messages. Suppose Monocarp pins t messages; if t \le k_i, then the i-th student will read all the pinned messages; but if t > k_i, the i-th student will choose exactly k_i random pinned messages (all possible subsets of pinned messages of size k_i are equiprobable) and read only the chosen messages.Monocarp wants to maximize the expected number of students that read their respective messages (i.e. the number of such indices i that student i reads the message m_i). Help him to choose how many (and which) messages should he pin! | ['brute force', 'dp', 'greedy', 'probabilities', 'sortings'] | import io,os
import heapq
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def calculate_maximum(tot,dic,wmax,wkey):
n = len(dic)
if n<tot: return [-1,[]]
indexes = [i for i in range(n)]
for i,key in enumerate(wkey):
wmax[i] += dic[key][tot]
heap = []
for i in range(n):
heapq.heappush(heap,(wmax[i],wkey[i]))
if len(heap)>tot: heapq.heappop(heap)
tempans = 0
temppick = []
for i in range(tot):
ele = heapq.heappop(heap)
tempans += ele[0]
temppick.append(ele[1])
return [tempans*1.0/tot,temppick]
def main(t):
q = int(input())
dic = {}
store = {}
for i in range(q):
index, hr = map(int,input().split())
if index not in dic: dic[index] = [0]*21
dic[index][hr] += 1
# print(dic)
for key in dic:
for k in range(19,0,-1):
dic[key][k] = dic[key][k+1] + dic[key][k]
# print(dic)
wkey = []
for key in dic: wkey.append(key)
wmax = [0]*(len(wkey))
ans = 0
pick = []
for k in range(1,21):
[tempans,temppick] = calculate_maximum(k,dic,wmax,wkey)
if tempans>ans:
ans = tempans
pick = temppick
# else:
# break
# print(ans,pick)
# if 64217 in dic and dic[64217][12]==1 and 76864 in dic and dic[76864][3]==1:
# print(20)
# print(1523,47986,140077,129374,198572,113642,117770,184883,71059,2094,36452,193203,143563,78520,151265,188108,3411,165350,191396,110974)
print(len(pick))
print(" ".join(map(str,pick)))
T = 1#int(input())
t = 1
while t<=T:
main(t)
t += 1
| Python | [
"probabilities"
] | 1,524 | 1,783 | 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
} | 2,922 |
71ee54d8881f20ae4b1d8bb9783948c0 | You are given two strings s and t of equal length n. In one move, you can swap any two adjacent characters of the string s.You need to find the minimal number of operations you need to make string s lexicographically smaller than string t.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. | ['brute force', 'data structures', 'greedy', 'strings'] | import os,sys
from random import randint
import random
from io import BytesIO, IOBase
from collections import defaultdict,deque,Counter
from bisect import bisect_left,bisect_right
from heapq import heappush,heappop
from functools import lru_cache
from itertools import accumulate
import math
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
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))
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# for _ in range(int(input())):
# n = int(input())
# a = list(map(int, input().split(' ')))
# cnt = [0] * 200
# for i in range(n):
# cnt[abs(a[i])] += 1
# ans = 0
# for i in range(200):
# if i == 0:
# ans += min(1, cnt[i])
# else:
# ans += min(2, cnt[i])
# print(ans)
# for _ in range(int(input())):
# n = int(input())
# s = input()
# ans = [s[0] * 2]
# for i in range(1, n):
# if s[i] > s[i - 1]:
# ans.append(s[:i] + s[:i][::-1])
# break
# if s[i] < s[i - 1]:
# ans.append(s[:i + 1] + s[:i + 1][::-1])
# ans.append(s[:i] + s[:i][::-1])
# ans.append(s + s[::-1])
# ans.sort()
# print(ans[0])
def lowbit(x):
return x & (-x)
class BIT:
def __init__(self, x):
"""transform list into BIT"""
self.bit = x
for i in range(len(x)):
j = i + lowbit(i)
if j < len(x):
x[j] += x[i]
def update(self, idx, x):
"""updates bit[idx] += x"""
idx += 1
while idx < len(self.bit):
self.bit[idx] += x
idx += lowbit(idx)
def query(self, end):
"""calc sum(bit[1:end+1])"""
x = 0
while end:
x += self.bit[end]
end -= lowbit(end)
return x
for _ in range(int(input())):
n = int(input())
s = input()
t = input()
if s < t:
print(0)
continue
if ''.join(sorted(s)) >= t:
print(-1)
continue
p = [n for _ in range(26)]
for i in range(n):
if p[ord(s[i]) - ord('a')] == n:
p[ord(s[i]) - ord('a')] = i
i = j = 0
# vis = SortedList()
vis = set()
fen = BIT([0] * (n + 2))
ans = float('inf')
res = 0
while i < n and j < n:
while i in vis:
vis.remove(i)
fen.update(i, -1)
i += 1
if i >= n: break
for k in range(26):
if p[k] <= i or p[k] in vis:
tmp = max(i, p[k]) + 1
while tmp < n and (s[tmp] != s[p[k]] or tmp in vis):
tmp += 1
p[k] = tmp
if s[i] < t[j]:
ans = min(ans, res)
break
mn = n
for k in range(ord(t[j]) - ord('a')):
mn = min(mn, p[k])
if mn != n:
# ans = min(ans, res + mn - i - (vis.bisect_left(mn) - vis.bisect_right(i)))
ans = min(ans, res + mn - i - (fen.query(mn) - fen.query(i + 1)))
if s[i] == t[j]:
i += 1
j += 1
else:
if i < p[ord(t[j]) - ord('a')] < mn:
idx = p[ord(t[j]) - ord('a')]
# res += idx - i - (vis.bisect_left(idx) - vis.bisect_right(i))
res += idx - i - (fen.query(idx) - fen.query(i + 1))
vis.add(idx)
fen.update(idx, 1)
j += 1
else:
break
print(ans if ans < float('inf') else -1)
| Python | [
"strings"
] | 607 | 13,152 | 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,759 |
116dd636a4f2547aef01a68f98c46ca2 | You are given two integers n and m and an array a of n integers. For each 1 \le i \le n it holds that 1 \le a_i \le m.Your task is to count the number of different arrays b of length n such that: 1 \le b_i \le m for each 1 \le i \le n, and \gcd(b_1,b_2,b_3,...,b_i) = a_i for each 1 \le i \le n. Here \gcd(a_1,a_2,\dots,a_i) denotes the greatest common divisor (GCD) of integers a_1,a_2,\ldots,a_i.Since this number can be too large, print it modulo 998\,244\,353. | ['combinatorics', 'math', 'number theory'] | #from pyrival import *
import math
import sys
import heapq
input = lambda: sys.stdin.readline().rstrip("\r\n")
mod = 998244353
# Count the number of numbers
# up to m which are divisible
# by given prime numbers
def count(a, n, m):
#print(a)
#print(n, m)
total = 0
# Run from i = 000..0 to i = 111..1
# or check all possible
# subsets of the array
for i in range(0, 1 << n):
mult = 1
for j in range(n):
if (i & (1 << j)):
mult *= a[j]
# Take the multiplication
# of all the set bits
# If the number of set bits
# is odd, then add to the
# number of multiples
total += (-1)**(bin(i).count('1') & 1) * (m // mult)
#print(f'subtracting out {m // mult}')
return total
def countRelPrime(n, m):
#print(f'counting rel {n} {m}')
facts = []
for div in range(2, math.ceil(n**0.5) + 2):
if n % div == 0:
facts += [div]
while n % div == 0:
n //= div
if n != 1:
facts += [n]
return count(facts, len(facts), m)
t = int(input())
for _ in range(t):
cache = {}
N, M = map(int, input().split())
A = list(map(int, input().split()))
ways = 1
for pos in range(1, N):
big, small = A[pos - 1 : pos + 1]
if (big, small) not in cache:
if math.gcd(big, small) < small:
ways = 0
break
cache[(big, small)] = countRelPrime(big//small, M//small)
new_ways = cache[(big, small)]
#print(f'found {new_ways}')
ways = (ways * new_ways) % mod
print(f'{ways}')
| Python | [
"math",
"number theory"
] | 557 | 1,664 | 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,452 |
7a51d536d5212023cc226ef1f6201174 | You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it.For example: if l=909, then adding one will result in 910 and 2 digits will be changed; if you add one to l=9, the result will be 10 and 2 digits will also be changed; if you add one to l=489999, the result will be 490000 and 5 digits will be changed. Changed digits always form a suffix of the result written in the decimal system.Output the total number of changed digits, if you want to get r from l, adding 1 each time. | ['binary search', 'dp', 'math', 'number theory'] | import sys
def memoize(f):
st = {}
def _mk_r():
def r(*args):
_k = args
if _k in st:
return st[_k]
c = f(*args)
st[_k] = c
# print(f'{key}{_k} -> {c}')
return c
return r
return _mk_r()
def run():
class _fake_int(object):
def __init__(self):
super().__init__()
self.v = 0
def use(self, c, l) -> slice:
v = self.v
self.v += c
return l[v:v + c]
_stdin, _pos = sys.stdin.read().split(), _fake_int()
def inp(count=1, tp=int):
return map(tp, _pos.use(count, _stdin))
ss = ['9' * i for i in range(20)]
@memoize
def dp(j, i):
a = ss[j]
n = len(a) - i
if n == 1:
return int(a[-1])
elif not n:
return 0
else:
c = int(a[i])
return (dp(n - 1, 0) + n - 1) * c + c + dp(j, i + 1)
def solve(ss=ss):
l, r = inp(2, str)
ss += [l, r]
print(dp(len(ss) - 1, 0) - dp(len(ss) - 2, 0))
t, = inp()
while t != 0:
solve()
t -= 1
run()
| Python | [
"math",
"number theory"
] | 786 | 1,056 | 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
} | 264 |
4e9dfc5e988cebb9a92f0c0b7ec06981 | Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an n by m grid (1 \leq n, m \leq 2000) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: For any two adjacent (sharing a side) cells, the absolute value of the difference of numbers in them is at most 1. If the number in some cell is strictly larger than 0, it should be strictly greater than the number in at least one of the cells adjacent to it. Unfortunately, Ajit is not fully worthy of Omkar's powers yet. He sees each cell as a "0" or a "#". If a cell is labeled as "0", then the number in it must equal 0. Otherwise, the number in it can be any nonnegative integer.Determine how many different assignments of elements exist such that these special conditions are satisfied. Two assignments are considered different if there exists at least one cell such that the numbers written in it in these assignments are different. Since the answer may be enormous, find the answer modulo 10^9+7. | ['combinatorics', 'graphs', 'math', 'shortest paths'] | 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
M = 10 ** 9 + 7
def solve():
n, m = getList()
# we can figure out the solution by fixed the 0's in some certain cells , then for each subset of 0, caculate how many assignments such that the chosen cell is 0 and the other must be non-negative
# It turns out for a particular subset there is EXACTLy one solution for it
# proof
# multi bfs, because all other cells must be nonegtive, any adjacents to 0 must be 1, this is equivalent for the first turn of multi bfs
# can we assign any other cell to 1 ? no, because if that cell is assign 1 then there's must be a cell neighbor to it is 0, but if there is a 0 neighbor to it, then it should be makred before
# from distance 2, 3 4, 5 .. we could prove the same way
# i.e while bfs for distance 2 done , if we assign any other unvisted cell 0 1 then there is no possible solution since ther emust be either cell 0 or 1 next to it, but if there were it should be mared before
a = "".join(getStr() for _ in range(n))
res = a.count("#")
res = pow(2, res, M)
res -= '0' not in a
print(res % M)
for _ in range(t):
solve()
| Python | [
"math",
"graphs"
] | 1,096 | 1,392 | 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
} | 2,025 |
a6c6b2a66ba51249fdc5d4188ca09e3b | Shinju loves permutations very much! Today, she has borrowed a permutation p from Juju to play with.The i-th cyclic shift of a permutation p is a transformation on the permutation such that p = [p_1, p_2, \ldots, p_n] will now become p = [p_{n-i+1}, \ldots, p_n, p_1,p_2, \ldots, p_{n-i}].Let's define the power of permutation p as the number of distinct elements in the prefix maximums array b of the permutation. The prefix maximums array b is the array of length n such that b_i = \max(p_1, p_2, \ldots, p_i). For example, the power of [1, 2, 5, 4, 6, 3] is 4 since b=[1,2,5,5,6,6] and there are 4 distinct elements in b.Unfortunately, Shinju has lost the permutation p! The only information she remembers is an array c, where c_i is the power of the (i-1)-th cyclic shift of the permutation p. She's also not confident that she remembers it correctly, so she wants to know if her memory is good enough.Given the array c, determine if there exists a permutation p that is consistent with c. You do not have to construct the permutation p.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', 'math'] | a,b,c=input,int,range
for _ in c(b(a())):n=b(a());m=list(map(b,a().split()));print("YNEOS"[m.count(1)!= 1 or m[0]>m[-1]+1 or any(m[i+1]-m[i]>1 for i in range(n-1))::2]) | Python | [
"math"
] | 1,513 | 169 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | {
"games": 0,
"geometry": 0,
"graphs": 0,
"math": 1,
"number theory": 0,
"probabilities": 0,
"strings": 0,
"trees": 0
} | 1,615 |
5acd7b95a44dcb8f72623b51fcf85f1b | In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simultaneously for one day. Both brigades repair one road for the whole day and cannot take part in repairing other roads on that day. But the repair brigade can do nothing on that day.Determine the minimum number of days needed to repair all the roads. The brigades cannot change the cities where they initially are. | ['greedy', 'graphs', '*special', 'dfs and similar', 'trees'] | import sys
import threading
from collections import defaultdict
def put():
return map(int, input().split())
def dfs(i, p, m):
cnt = 1
z = 0
for j in tree[i]:
if j==p: continue
if cnt==m: cnt+=1
index = edge_index[(i,j)]
ans[cnt].append(index)
z = max(dfs(j,i,cnt), z)
cnt+=1
return max(z,cnt-1)
def solve():
l = dfs(1,0,0)
print(l)
for i in range(1, l+1):
print(len(ans[i]), *ans[i])
n = int(input())
edge_index = defaultdict()
ans = [[] for i in range(n+1)]
tree = [[] for i in range(n+1)]
for i in range(n-1):
x,y = put()
edge_index[(x,y)]=i+1
edge_index[(y,x)]=i+1
tree[x].append(y)
tree[y].append(x)
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start() | Python | [
"graphs",
"trees"
] | 628 | 919 | 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
} | 484 |
7fe380a1848eae621c734cc9a3e463e0 | An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device. In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue. It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above): main grid is a top tree, whose wires are directed 'from the top to the down', reserve grid is a lower tree, whose wires are directed 'from the down to the top', devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right, wires between nodes do not intersect. Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, \dots, n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid. | ['dp', 'graphs', 'flows', 'data structures', 'dfs and similar', 'trees'] | from __future__ import print_function,division
import sys#log min est tolérable
n=int(input())
def f():
global n
co=[[0]*n for k in range(n)]
a=int(input())
p=[0]+list(map(int,raw_input().split()))
d=[0]*a
s=[1]*a
s[0]=0
mi=[n]*a#plus peit
ma=[-1]*a#le plus tard
for k in p[1:]:
d[k-1]+=1
x=list(map(int,raw_input().split()))
for k in range(n):
mi[x[k]-1]=k
ma[x[k]-1]=k
pi=[k for k in range(a) if d[k]==0]
for k in range(a-1):
v=pi.pop()
p[v]-=1
d[p[v]]-=1
if d[p[v]]==0:
pi.append(p[v])
s[p[v]]+=s[v]
ma[p[v]] =max(ma[p[v]],ma[v])
mi[p[v]] =min(mi[p[v]],mi[v])
for v in range(a):
co[ma[v]][mi[v]]=max(s[v],co[ma[v]][mi[v]])
return co
l1=f()
l2=f()
be=[0]*(n+1)
for k in range(n):
be[k]=max([be[k-1],max(be[i-1]+l1[k][i] for i in range(k+1)),max(be[i-1]+l2[k][i] for i in range(k+1))])
print(be[n-1])
| Python | [
"graphs",
"trees"
] | 2,195 | 970 | 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,840 |
83a665723ca4e40c78fca20057a0dc99 | I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret her expressions! Maybe you can help us understand what this young princess is saying?You are given a string of n lowercase Latin letters, the word that Fischl just spoke. You think that the MEX of this string may help you find the meaning behind this message. The MEX of the string is defined as the shortest string that doesn't appear as a contiguous substring in the input. If multiple strings exist, the lexicographically smallest one is considered the MEX. Note that the empty substring does NOT count as a valid MEX.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. 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 out what the MEX of the string is! | ['brute force', 'constructive algorithms', 'strings'] | t=int(input())
for p in range(t):
n=int(input())
a=input()
o=0
l=1
if len(set(a))==26:
o=1
for i in 'abcdefghijklmnopqrstuvwxyz':
if i not in a:
print(i)
break
elif o==1:
for j in 'abcdefghijklmnopqrstuvwxyz':
if i+j not in a and n<676:
print(i+j)
l=0
break
if n>676:
for x in 'abcdefghijklmnopqrstuvwxyz':
if i+j+x not in a:
print(i+j+x)
l=0
break
if l==0:
break
if l==0:
break | Python | [
"strings"
] | 1,444 | 766 | 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,833 |
ea6f55b3775076fcba6554b743b1a8ae | As Famil Door’s birthday is coming, some of his friends (like Gabi) decided to buy a present for him. His friends are going to buy a string consisted of round brackets since Famil Door loves string of brackets of length n more than any other strings!The sequence of round brackets is called valid if and only if: the total number of opening brackets is equal to the total number of closing brackets; for any prefix of the sequence, the number of opening brackets is greater or equal than the number of closing brackets. Gabi bought a string s of length m (m ≤ n) and want to complete it to obtain a valid sequence of brackets of length n. He is going to pick some strings p and q consisting of round brackets and merge them in a string p + s + q, that is add the string p at the beginning of the string s and string q at the end of the string s.Now he wonders, how many pairs of strings p and q exists, such that the string p + s + q is a valid sequence of round brackets. As this number may be pretty large, he wants to calculate it modulo 109 + 7. | ['dp', 'strings'] | n, m = map(int, input().split())
s = input()
mod = 10 ** 9 + 7
c, b, ans, d, k = 0, 0, 0, [[1]], n - m
for i in s:
c += (i == '(') * 2 - 1
b = min(c, b)
for i in range(n - m):
nd = d[-1][1:] + [0] * 2
for j in range(1, i + 2):
nd[j] = (nd[j] + d[-1][j - 1]) % mod
d.append(nd)
for i in range(k + 1):
for j in range(-b, min(k - i - c, i) + 1):
ans = (ans + d[i][j] * d[k - i][j + c]) % mod
print(ans) | Python | [
"strings"
] | 1,052 | 439 | 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,639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.