name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p01801 Wall Making Game
Example Input 2 2 .. .. Output Second
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): H, W = map(int, readline().split()) f = ".X".index S = [list(map(f, readline().strip())) for i in range(H)] memo = {} def dfs(px, py, qx, qy): key = (px, py, qx, qy) if key in memo: r...
p02216 Array Game
Problem statement There is a positive integer sequence $ a_1, a_2, \ ldots, a_N $ of length $ N $. Consider the following game, which uses this sequence and is played by $ 2 $ players on the play and the play. * Alternately select one of the following operations for the first move and the second move. * Select a pos...
```python # #    ⋀_⋀  #   (・ω・) # ./ U ∽ U\ # │* 合 *│ # │* 格 *│ # │* 祈 *│ # │* 願 *│ # │*   *│ #  ̄ # import sys sys.setrecursionlimit(10**6) input=sys.stdin.readline from math import floor,sqrt,factorial,hypot,log #log2ないyp from heapq import heappop, heappush, heappushpop from collections import Count...
p02369 Cycle Detection for a Directed Graph
Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1...
```python from collections import deque from typing import List, Optional, Tuple def cycle_detectable_topological_sort( graph: List[List[int]], in_degrees: List[int], first_index: int = 0 ) -> Tuple[Optional[List[int]], Optional[List[int]]]: """Topological sort that uses Kahn's algorithm and detects a loop (D...
1000_C. Covered Points Count
You are given n segments on a coordinate line; each endpoint of every segment has integer coordinates. Some segments can degenerate to points. Segments can intersect with each other, be nested in each other or even coincide. Your task is the following: for every k ∈ [1..n], calculate the number of points with integer ...
```python n=int(input()) a=[] for i in range(n): l,r=map(int,input().split()) a.append([l,1]) a.append([r+1,-1]) a.sort() # print(a) ans=[0]*(n+1) idx=0 for i in range(len(a)-1): idx+=a[i][1] ans[idx]+=a[i+1][0]-a[i][0] for i in range(1,n+1): print(ans[i],end=" ") print() ```
1025_D. Recovering BST
Dima the hamster enjoys nibbling different things: cages, sticks, bad problemsetters and even trees! Recently he found a binary search tree and instinctively nibbled all of its edges, hence messing up the vertices. Dima knows that if Andrew, who has been thoroughly assembling the tree for a long time, comes home and s...
```python from math import gcd import random,time,sys input=sys.stdin.buffer.readline def main(): n=int(input()) a=list(map(int,input().split())) #a=[2*random.randint(1,10**9) for i in range(n)] start=time.time() a+=[0] dp=[[False for j in range(n)] for i in range(n)] GCD=[0 for i in rang...
1068_F. Knights
Ivan places knights on infinite chessboard. Initially there are n knights. If there is free cell which is under attack of at least 4 knights then he places new knight in this cell. Ivan repeats this until there are no such free cells. One can prove that this process is finite. One can also prove that position in the en...
```python n = int(input()) anss = [(0, 0)] for i in range(1, n): anss.append((0, i)) anss.append((i, 0)) anss.append((0, -i)) anss.append((-i, 0)) for i in range(n): print(str(anss[i][0]) + ' ' + str(anss[i][1])) ```
110_B. Lucky String
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
```python n=int(input()) x='a'+'bcda'*25002 print(x[:n]) ```
1139_E. Maximize Mex
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 competit...
```python 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...
1157_E. Minimum Array
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1. You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ...
```python class SegmentTree: @classmethod def all_identity(cls, operator, equality, identity, size): return cls(operator, equality, identity, [identity]*(2 << (size-1).bit_length())) @classmethod def from_initial_data(cls, operator, equality, identity, data): size = 1 << (len(data)-1)...
117_B. Very Interesting Game
In a very ancient country the following game was popular. Two people play the game. Initially first player writes a string s1, consisting of exactly nine digits and representing a number that does not exceed a. After that second player looks at s1 and writes a string s2, consisting of exactly nine digits and representi...
```python a, b, m = map(int, input().split()) k = s = 10 ** 9 % m i = 0 while k and i < a: i += 1 if k < m - b: exit(print(1, str(i).zfill(9))) k += s if k >= m: k -= m print(2) ```
1198_C. Matching vs Independent Set
You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line...
```python import sys input = sys.stdin.readline T = int(input()) for _ in range(T): N, M = map(int, input().split()) X = [[] for i in range(3*N)] for i in range(M): x, y = map(int, input().split()) x, y = min(x,y), max(x,y) X[x-1].append((y-1, i+1)) MAT = [] IND = [] ...
1215_B. The Number of Products
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0). You have to calculate two following values: 1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative; 2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a...
```python input() a=list(map(int,input().split())) q,w,e,t,y=0,0,1,0,0 for i in a: if e>0: q+=1 if i>0: e=1 else: e=-1 else: w+=1 if i>0: e=-1 else: e=1 if e>0: t+=q y+=w else: t+=w ...
1238_D. AB-string
The string t_1t_2 ... t_k is good if each letter of this string belongs to at least one palindrome of length greater than 1. A palindrome is a string that reads the same backward as forward. For example, the strings A, BAB, ABBA, BAABBBAAB are palindromes, but the strings AB, ABBBAA, BBBA are not. Here are some examp...
```python from sys import stdin n = int(input()) s = stdin.read(n) ans = n*(n-1)//2 k = 0 m = 0 for i in range(1, n): p = s[i-1] t = s[i] if p == t: k+=1 else: ans -= k*(1<<m)+1 m |= 1 k = 0 else: ans -= k*m print(ans) ```
1256_E. Yet Another Division Into Teams
There are n students at your university. The programming skill of the i-th student is a_i. As a coach, you want to divide them into teams to prepare them for the upcoming ICPC finals. Just imagine how good this university is if it has 2 ⋅ 10^5 students ready for the finals! Each team should consist of at least three s...
```python def main(): n=int(input()) a=readIntArr() a2=[[x,i+1] for i,x in enumerate(a)] # [value, index] a2.sort(key=lambda x:x[0]) # sort by value asc dp=[inf for _ in range(n)] # dp[i] is the min diversity achievable at i #dp[i]=min(ai-aj+dp[j-1])=min(a[i]+(dp[j-1]-a[j]))=a[i]...
127_E. E-reader Display
After years of hard work scientists invented an absolutely new e-reader display. The new display has a larger resolution, consumes less energy and its production is cheaper. And besides, one can bend it. The only inconvenience is highly unusual management. For that very reason the developers decided to leave the e-read...
```python n=int(input()) T=[] for i in range(n): T.append(input()[::-1]) Val=['0','1'] S=0 L1=[0]*n C1=[0]*n for diag in range(n-1): for i in range(diag+1): l,c=L1[i],C1[diag-i] if T[i][diag-i]!=Val[(l+c)%2]: S+=1 L1[i]=1-l C1[diag-i]=1-c L2=[0...
1342_E. Placing Rooks
Calculate the number of ways to place n rooks on n × n chessboard so that both following conditions are met: * each empty cell is under attack; * exactly k pairs of rooks attack each other. An empty cell is under attack if there is at least one rook in the same row or at least one rook in the same column. Two...
```python import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys def solve(n,k): mod=998244353 if k==0: ans=1 for i in range(1,n+1): ans*=i ans%=mod return ans if k>=n: return 0 inv=lambda x: pow(x,mod-2,mod) Fac...
1406_C. Link Cut Centroids
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the sma...
```python from random import choice as _choice import sys as _sys def main(): t = int(input()) for i in range(t): n, = _read_ints() graph = [set() for v in range(n)] for i_edge in range(n-1): v1, v2 = _read_ints() v1 -= 1 v2 -= 1 graph[v1...
1427_D. Unshuffling a Deck
You are given a deck of n cards numbered from 1 to n (not necessarily in this order in the deck). You have to sort the deck by repeating the following operation. * Choose 2 ≤ k ≤ n and split the deck in k nonempty contiguous parts D_1, D_2,..., D_k (D_1 contains the first |D_1| cards of the deck, D_2 contains the f...
```python from sys import stdin, stdout n = int(stdin.readline()) c = [int(x) for x in stdin.readline().split()] ops = [] turn = True for x in range(n-1): newC = [] newC2 = [] op = [] ind = c.index(x+1) if turn: if ind != 0: op.append(ind) op.append(n-x-ind) o...
1450_D. Rating Compression
On the competitive programming platform CodeCook, every person has a rating graph described by an array of integers a of length n. You are now updating the infrastructure, so you've created a program to compress these graphs. The program works as follows. Given an integer parameter k, the program takes the minimum of ...
```python from collections import deque for iii in range(int(input())): d = deque() f = 1 n = int(input()) m = {i+1 : 0 for i in range(n)} s = map(int, input().split()) for i in s: m[i]+=1 if m[i]!=1: f = 0 d.append(i) res = [0 for i in range(n)] if f:...
1474_B. Different Divisors
Positive integer x is called divisor of positive integer y, if y is divisible by x without remainder. For example, 1 is a divisor of 7 and 3 is not divisor of 8. We gave you an integer d and asked you to find the smallest positive integer a, such that * a has at least 4 divisors; * difference between any two di...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not i...
1523_D. Love-Hate
<image> William is hosting a party for n of his trader friends. They started a discussion on various currencies they trade, but there's an issue: not all of his trader friends like every currency. They like some currencies, but not others. For each William's friend i it is known whether he likes currency j. There are...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): def popCount(a): cnt = 0 for i in range(60): if a & (1 << i): cnt += 1 return cnt n,m,p = map(int,input().split()) person = [] for _ in range(n): ...
155_C. Hometask
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about ...
```python s = input() + "#" k = int(input()) arr = [input() for _ in range(k)] res = 0 for t in arr: a, b = 0, 0 for i in range(len(s)): if s[i] == t[0]: a += 1 elif s[i] == t[1]: b += 1 else: if a and b: res += min(a, b) a,...
177_D1. Encrypting Messages
The Smart Beaver from ABBYY invented a new message encryption method and now wants to check its performance. Checking it manually is long and tiresome, so he decided to ask the ABBYY Cup contestants for help. A message is a sequence of n integers a1, a2, ..., an. Encryption uses a key which is a sequence of m integers...
```python n,m,c = map(int,input().split()) a = list(input().split()) b = list(input().split()) sum = 0 for i in range(n): if i<m: sum = sum + int(b[i]) sum = sum%c if i >= n - m + 1: sum = c - int(b[i-n+m-1]) + sum sum = sum%c print((int(a[i])+sum)%c,end = ' ') ```
245_F. Log Stream Analysis
You've got a list of program warning logs. Each record of a log stream is a string in this format: "2012-MM-DD HH:MM:SS:MESSAGE" (without the quotes). String "MESSAGE" consists of spaces, uppercase and lowercase English letters and characters "!", ".", ",", "?". String "2012-MM-DD" determines a correct date in the ...
```python import atexit import io import sys _INPUT_LINES = sys.stdin.read().splitlines() input = iter(_INPUT_LINES).__next__ _OUTPUT_BUFFER = io.StringIO() sys.stdout = _OUTPUT_BUFFER @atexit.register def write(): sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) import bisect from datetime import datetime def...
270_D. Greenhouse Effect
Emuskald is an avid horticulturist and owns the world's longest greenhouse — it is effectively infinite in length. Over the years Emuskald has cultivated n plants in his greenhouse, of m different plant species numbered from 1 to m. His greenhouse is very narrow and can be viewed as an infinite line, with each plant o...
```python n, m = [int(x) for x in input().split()] d = [0 for i in range(m)] for i in range(n): c, x = [x for x in input().split()] c = int(c) d[c-1] = max(d[:c])+1 print(n-max(d)) ```
294_A. Shaass and Oskols
Shaass has decided to hunt some birds. There are n horizontal electricity wires aligned parallel to each other. Wires are numbered 1 to n from top to bottom. On each wire there are some oskols sitting next to each other. Oskol is the name of a delicious kind of birds in Shaass's territory. Supposed there are ai oskols ...
```python n = int(input()) l = list(map(int,input().split())) n1 = int(input()) for i in range(n1): x,y = map(int,input().split()) if len(l)==1: l[0]=0 elif x==1: l[x]+=l[x-1]-y l[x-1]=0 elif x==len(l): l[x-2]+=y-1 l[x-1]=0 else: l[x-2]+=y-1 l[x]+=l[x-1]-y l[x-1]=0 for i in l: print(i) ```
317_D. Game with Powers
Vasya and Petya wrote down all integers from 1 to n to play the "powers" game (n can be quite large; however, Vasya and Petya are not confused by this fact). Players choose numbers in turn (Vasya chooses first). If some number x is chosen at the current turn, it is forbidden to choose x or all of its other positive in...
```python from sys import stdin, stdout import math, collections mod = 10**9+7 def isPower(n): if (n <= 1): return True for x in range(2, (int)(math.sqrt(n)) + 1): p = x while (p <= n): p = p * x if (p == n): return True return False n = int(...
365_A. Good Number
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a). Input The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ...
```python import sys x=input().split() n=int(x[0]) k=int(x[1]) list=[] for i in range(0,n): y=input() list.append(y) l=0 for j in list: flag=1 for z in range(0,k+1): if str(z) not in j: flag=0 break if flag==1: l=l+1 print(l) ```
409_C. Magnum Opus
Salve, mi amice. Et tu quidem de lapis philosophorum. Barba non facit philosophum. Labor omnia vincit. Non potest creatio ex nihilo. Necesse est partibus. Rp: I Aqua Fortis I Aqua Regia II Amalgama VII Minium IV Vitriol Misce in vitro et æstus, et nil admirari. Festina lente, et nulla tenaci invia est via. Fac...
```python b =[1,1,2,7,4] a =list(map(int,input().split())) ans = 100 for i in range(5): ans = min(a[i]//b[i],ans) print(ans) ```
459_E. Pashmak and Graph
Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perh...
```python from sys import * f = list(map(int, stdin.read().split())) n, m = f[0], f[1] d = [[] for i in range(100001)] for j in range(2, len(f), 3): x, y, w = f[j:j + 3] d[w].append((y, x)) s = [0] * (n + 1) for q in d: for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1) print(max(s)) ```
505_D. Mr. Kitayuta's Technology
Shuseki Kingdom is the world's leading nation for innovation and technology. There are n cities in the kingdom, numbered from 1 to n. Thanks to Mr. Kitayuta's research, it has finally become possible to construct teleportation pipes between two cities. A teleportation pipe will connect two cities unidirectionally, tha...
```python def main(): n, m = map(int, input().split()) n += 1 cluster, dest, ab = list(range(n)), [0] * n, [[] for _ in range(n)] def root(x): if x != cluster[x]: cluster[x] = x = root(cluster[x]) return x for _ in range(m): a, b = map(int, input().split()) ...
554_E. Love Triangles
There are many anime that are about "love triangles": Alice loves Bob, and Charlie loves Bob as well, but Alice hates Charlie. You are thinking about an anime which has n characters. The characters are labeled from 1 to n. Every pair of two characters can either mutually love each other or mutually hate each other (the...
```python class DSU(object): def __init__(self, n): self.father = list(range(n)) self.size = n def union(self, x, s): x = self.find(x) s = self.find(s) if x == s: return self.father[s] = x self.size -= 1 def find(self, x): xf = se...
580_D. Kefa and Dishes
When Kefa came to the restaurant and sat at a table, the waiter immediately brought him the menu. There were n dishes. Kefa knows that he needs exactly m dishes. But at that, he doesn't want to order the same dish twice to taste as many dishes as possible. Kefa knows that the i-th dish gives him ai units of satisfact...
```python import os import sys from io import BytesIO,IOBase def main(): n,m,k = map(int,input().split()) a = list(map(float,input().split())) tree = [[0]*n for _ in range(n)] for i in range(k): x,y,z = map(int,input().split()) tree[x-1][y-1] = float(z) po = [1] while len(po) !=...
602_C. The Two Routes
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
```python n, m = map(int, input().split()) dist = [0] * (n + 1) for row in range(n + 1): dist[row] = [1] * (n + 1) for i in range(m): a, b = map(int, input().split()) dist[a][b] = dist[b][a] = 2 x, v, i = 3 - dist[1][n], [0] * (n + 1), 1 d = [n + 1] * (n + 1) res = d[1] = 0 while i != n: v[i] = 1 ...
625_A. Guest From the Past
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas...
```python n=(int)(input()); a=(int)(input()); b=(int)(input()); c=(int)(input()); cnt=a; cnt=0; cnt1=a; cnt1=(int)(n//a); if (n<b): while (n//b>0): cnt+=n//b; n-=(n//b)*b-n//b*c; #print (n," ",cnt); #print(n//a," ",cnt," ",cnt+n//a); cnt+=n//a; print((int)(max(cnt,cnt1))); else: ...
673_C. Bear and Colors
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the bigges...
```python def main(): n = int(input()) a = [int(i) for i in input().strip().split()] res = [0] * n for st in range(n): cnt = [0] * n x = 0 y = 0 for ed in range(st, n): cnt[a[ed] - 1] += 1 if (cnt[a[ed] - 1] > x) or (cnt[a[ed] - 1] == x and a[ed]...
740_B. Alyona and flowers
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative. Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa...
```python I=lambda:map(int,input().split()) R=range ans=0 n,m=I() a=list(I()) for _ in R(m):l,r=I();ans+=max(0,sum(a[i]for i in R(l-1,r))) print(ans) ```
764_A. Taymyr is calling you
Comrade Dujikov is busy choosing artists for Timofey's birthday and is recieving calls from Taymyr from Ilia-alpinist. Ilia-alpinist calls every n minutes, i.e. in minutes n, 2n, 3n and so on. Artists come to the comrade every m minutes, i.e. in minutes m, 2m, 3m and so on. The day is z minutes long, i.e. the day cons...
```python from math import * def lcm(a, b): return a*b//gcd(a, b) n, m, z = map(int, input().split()) print(z//lcm(n, m)) ```
787_C. Berzerk
Rick and Morty are playing their own version of Berzerk (which has nothing in common with the famous Berzerk game). This game needs a huge space, so they play it with a computer. In this game there are n objects numbered from 1 to n arranged in a circle (in clockwise order). Object number 1 is a black hole and the oth...
```python import queue n = int(input()) sR = list(map(int, input().split()[1:])) sM = list(map(int, input().split()[1:])) s = [sR, sM] UNK = -1 WIN = 2 LOSE = 3 A = [[UNK] * n for i in range(2)] CNT = [[0] * n for i in range(2)] V = [[False] * n for i in range(2)] # ricky turn 0 # morty turn 1 A[0][0] = LOSE A[1][0...
808_G. Anthem of Berland
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. H...
```python 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 ...
854_A. Fraction
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive comm...
```python import math n=int(input()) d=n//2 c=n-d while math.gcd(c,d)!=1: c+=1 d-=1 print(d,c) ```
902_A. Visiting a Friend
Pig is visiting a friend. Pig's house is located at point 0, and his friend's house is located at point m on an axis. Pig can use teleports to move along the axis. To use a teleport, Pig should come to a certain point (where the teleport is located) and choose where to move: for each teleport there is the rightmost ...
```python n, m = list( map( int, input().split() ) ) A = [] B = [] CanReach = [] start_idx = 0 end_idx = 0 for i in range( n ): a, b = list( map( int, input().split() ) ) A.append( a ) B.append( b ) memo = {} def best( i ): if A[i] <= m <= B[i]: return ( True ) if i in memo: r...
924_C. Riverside Curio
Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value. Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d...
```python N = int(input()) above = list(map(int, input().split())) if N == 1: print(0) quit() required_mark = [0] * N required_mark[N-2] = above[N-1] for i in reversed(range(N-2)): required_mark[i] = max(above[i+1], required_mark[i+1] - 1) d = 0 mark = 1 for i in range(1, N): if mark == above[i]: ...
952_E. Cheese Board
Not to be confused with [chessboard](https://en.wikipedia.org/wiki/Chessboard). <image> Input The first line of input contains a single integer N (1 ≤ N ≤ 100) — the number of cheeses you have. The next N lines describe the cheeses you have. Each line contains two space-separated strings: the name of the cheese and...
```python a, b = 0, 0 n = int(input()) for i in range(n): x, y = input().split() if y == 'soft': a += 1 else: b += 1 for i in range(1, 1000): n = i*i y = n // 2 x = n - y if (a <= x and b <= y) or (a <= y and b <= x): print(i) break ```
99_B. Help Chef Gerasim
In a far away kingdom young pages help to set the table for the King. As they are terribly mischievous, one needs to keep an eye on the control whether they have set everything correctly. This time the royal chef Gerasim had the impression that the pages have played a prank again: they had poured the juice from one cup...
```python n = int(input()) arr = [int(input()) for _ in range(n)] if len(set(arr)) == 1: print('Exemplary pages.') elif len(set(arr)) > 3: print('Unrecoverable configuration.') else: kek = set(arr) kek = list(kek) kek.sort() val = kek[-1] - kek[0] if val % 2 == 1: print('Unrecoverabl...
p02539 ACL Beginner Contest - Heights and Pairs
There are 2N people numbered 1 through 2N. The height of Person i is h_i. How many ways are there to make N pairs of people such that the following conditions are satisfied? Compute the answer modulo 998,244,353. * Each person is contained in exactly one pair. * For each pair, the heights of the two people in the pai...
```python import sys input = sys.stdin.readline sys.setrecursionlimit(1000000) from collections import defaultdict from collections import deque import heapq MOD = 998244353 def DD(arg): return defaultdict(arg) def inv(n): return pow(n, MOD-2, MOD) kaijo_memo = [] def kaijo(n): if(len(kaijo_memo) > n): return ka...
p02670 AtCoder Grand Contest 044 - Joker
Tonight, in your favourite cinema they are giving the movie Joker and all seats are occupied. In the cinema there are N rows with N seats each, forming an N\times N square. We denote with 1, 2,\dots, N the viewers in the first row (from left to right); with N+1, \dots, 2N the viewers in the second row (from left to rig...
```python import sys input = sys.stdin.readline n = int(input()) l = list(map(int,input().split())) l = [((i-1)//n, (i-1) % n) for i in l] check = [[1]*n for i in range(n)] d = [[min(i, n-i-1, j, n-j-1) for j in range(n)] for i in range(n)] ans = 0 for x,y in l: check[x][y] = 0 ans += d[x][y] q = [(x,y,d[...
p02799 Keyence Programming Contest 2020 - Bichromization
We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each v...
```python """ 明らかに無理→最小が2つ無い or 最小同士がペアになってない (最小から接続する頂点に最小がない) 満たしてる→最小の辺を置いちゃおう 小さい奴からGreedyに置いてく? 自分の周りにendしてるやつ or 大きさが同じやつがあったら繋げちゃう そのとき白黒はどうでも良さそう? """ import sys N,M = map(int,input().split()) D = list(map(int,input().split())) dic2 = [[] for i in range(N)] for i in range(M): U,V = map(int,input()....
p02935 AtCoder Beginner Contest 138 - Alchemist
You have a pot and N ingredients. Each ingredient has a real number parameter called value, and the value of the i-th ingredient (1 \leq i \leq N) is v_i. When you put two ingredients in the pot, they will vanish and result in the formation of a new ingredient. The value of the new ingredient will be (x + y) / 2 where...
```python n=int(input()) v=sorted(list(map(int, input().split()))) avg=v[0] for i in range(1,n): avg=(avg+v[i])/2 print(avg) ```
p03072 AtCoder Beginner Contest 124 - Great Ocean View
There are N mountains ranging from east to west, and an ocean to the west. At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns. The height of the i-th mountain from the west is H_i. You can certainly see the ocean from the inn at the top of the westmost mountain. F...
```python N = int(input()) H = list(map(int,input().split())) ans = 0 maxm = 0 for h in H: if maxm <= h: ans += 1 maxm = h print(ans) ```
p03214 Dwango Programming Contest V - Thumbnail
Niwango-kun is an employee of Dwango Co., Ltd. One day, he is asked to generate a thumbnail from a video a user submitted. To generate a thumbnail, he needs to select a frame of the video according to the following procedure: * Get an integer N and N integers a_0, a_1, ..., a_{N-1} as inputs. N denotes the number of t...
```python n=int(input()) al=list(map(int,input().split())) t=sum(al)/n ta=100 for i in range(n): if abs(t-al[i])<ta: ta=abs(t-al[i]) ans=i print(ans) ```
p03363 AtCoder Grand Contest 023 - Zero-Sum Ranges
We have an integer sequence A, whose length is N. Find the number of the non-empty contiguous subsequences of A whose sums are 0. Note that we are counting the ways to take out subsequences. That is, even if the contents of some two subsequences are the same, they are counted individually if they are taken from differ...
```python from collections import Counter N = int(input()) A = list(map(int, input().split())) B = [0] for i in A: B.append(B[-1] + i) B_C = Counter(B) ans = 0 for key, value in B_C.items(): ans += value * (value-1) // 2 print(ans) ```
p03686 AtCoder Regular Contest 076 - Exhausted?
There are M chairs arranged in a line. The coordinate of the i-th chair (1 ≤ i ≤ M) is i. N people of the Takahashi clan played too much games, and they are all suffering from backaches. They need to sit in chairs and rest, but they are particular about which chairs they sit in. Specifically, the i-th person wishes to...
```python from collections import deque class LazySegtree(): def __init__(self,n,init_val,merge_func,ide_ele): self.n=n self.ide_ele=ide_ele self.merge_func=merge_func self.val=[0 for i in range(1<<n)] self.merge=[0 for i in range(1<<n)] self.parent=[-1 for i in rang...
p03839 AtCoder Grand Contest 008 - Contiguous Repainting
There are N squares aligned in a row. The i-th square from the left contains an integer a_i. Initially, all the squares are white. Snuke will perform the following operation some number of times: * Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares...
```python N,K=map(int,input().split()) a=list(map(int,input().split())) ans=0 tmp=0 sa=[0]*(N+1) A=[0]*(N+1) for i in range(N): sa[i+1]=sa[i]+a[i] if a[i]>0: A[i+1]=A[i]+a[i] else: A[i+1]=A[i] for i in range(N-K+1): tmp=sa[i+K]-sa[i] tmp2=A[i]+(A[-1]-A[i+K]) #print(max(0,tmp),tmp2) if max(0,tmp)+t...
p04006 AtCoder Grand Contest 004 - Colorful Slimes
Snuke lives in another world, where slimes are real creatures and kept by some people. Slimes come in N colors. Those colors are conveniently numbered 1 through N. Snuke currently has no slime. His objective is to have slimes of all the colors together. Snuke can perform the following two actions: * Select a color i ...
```python from collections import Counter def inpl(): return list(map(int, input().split())) N, x = inpl() A = inpl() B = [a for a in A] ans = 1e15 for i in range(N+1): for j in range(N): B[j] = min(B[j], A[(j-i)%N]) tmp = x*i + sum(B) ans = min(ans, tmp) print(ans) ```
p00092 Square Searching
There are a total of n x n squares, n rows vertically and n columns horizontally. Some squares are marked. Create a program that reads the marked state of each square and displays the length of the side of the largest square consisting of only the unmarked squares as an output. For example, each dataset is given the f...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0092 """ import sys def find_square0(data): max_size = 0 dp = [] # dp??¨???2?¬?????????? # '.'????????????1??????'*'????????????0???????????? for row in data: temp = [] for c in row: ...
p00224 Bicycle Diet
Mr. A loves sweets, but recently his wife has told him to go on a diet. One day, when Mr. A went out from his home to the city hall, his wife recommended that he go by bicycle. There, Mr. A reluctantly went out on a bicycle, but Mr. A, who likes sweets, came up with the idea of ​​stopping by a cake shop on the way to e...
```python from itertools import combinations from heapq import heappop, heappush import sys sys.setrecursionlimit(1000000) INF = 10 ** 20 def convert(s, m, n): if s == "H": return 0 if s == "D": return 1 if s[0] == "C": return int(s[1:]) + 1 if s[0] == "L": return int(s[1:]) + m + 1 def get_co...
p00386 Gathering
You are a teacher at Iazu High School is the Zuia Kingdom. There are $N$ cities and $N-1$ roads connecting them that allow you to move from one city to another by way of more than one road. Each of the roads allows bidirectional traffic and has a known length. As a part of class activities, you are planning the follow...
```python import sys sys.setrecursionlimit(1000000) def main(): n, q = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(n - 1): u, v, w = map(int, input().split()) u -= 1 v -= 1 edges[u].append((v, w)) edges[v].append((u, w)) height = [None] * n dist = [None] * n ...
p00602 Fibonacci Sets
Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, e...
```python from collections import deque try: while 1: V, d = map(int, input().split()) F = [0]*V a = b = 1 for v in range(V): a, b = (a+b) % 1001, a F[v] = a G = [[] for i in range(V)] for i in range(V): for j in range(i+1, V): ...
p00738 Roll-A-Big-Ball
ACM University holds its sports day in every July. The "Roll-A-Big-Ball" is the highlight of the day. In the game, players roll a ball on a straight course drawn on the ground. There are rectangular parallelepiped blocks on the ground as obstacles, which are fixed on the ground. During the game, the ball may not collid...
```python def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real def dot(c1, c2): return c1.real * c2.real + c1.imag * c2.imag def ccw(p0, p1, p2): a = p1 - p0 b = p2 - p0 cross_ab = cross(a, b) if cross_ab > 0: return 1 elif cross_ab < 0: return -1 elif dot(a,...
p01009 Room of Time and Spirit
Problem In 20XX, a scientist developed a powerful android with biotechnology. This android is extremely powerful because it is made by a computer by combining the cells of combat masters. At this rate, the earth would be dominated by androids, so the N warriors decided to fight the androids. However, today's warriors...
```python # AOJ 1519: Room of Time and Spirit # Python3 2018.7.13 bal4u # Weighted UNION-FIND library class WeightedUnionSet: def __init__(self, nmax): self.ws = [0]*nmax self.par = [-1]*nmax self.power = [0]*nmax def find(self, x): if self.par[x] < 0: return x p = self.find(self.par[x]) self.ws[x] += se...
p01280 Galaxy Wide Web Service
The volume of access to a web service varies from time to time in a day. Also, the hours with the highest volume of access varies from service to service. For example, a service popular in the United States may receive more access in the daytime in the United States, while another service popular in Japan may receive m...
```python from itertools import cycle while True: n = int(input()) if not n: break qs = {} for i in range(n): d, t, *q = (int(s) for s in input().split()) q = q[t:] + q[:t] if d not in qs: qs[d] = q else: qs[d] = [a + b for a, b in zip(qs[...
p01450 My friends are small
I have a lot of friends. Every friend is very small. I often go out with my friends. Put some friends in your backpack and go out together. Every morning I decide which friends to go out with that day. Put friends one by one in an empty backpack. I'm not very strong. Therefore, there is a limit to the weight of friends...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01756 Longest Match
Given the string S and m queries. The i-th query is given by the two strings xi and yi. For each query, answer the longest substring of the string S, starting with xi and ending with yi. For the string S, | S | represents the length of S. Also, the fact that the character string T is a substring of the character stri...
```python from collections import defaultdict import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): base = 37; MOD = 10**9 + 9 S = readline().strip() L = len(S) H = [0]*(L+1) v = 0 ca = ord('a') for i in range(L): H[i+1] = v = (v * base + (ord(S[i]) - ca)) % ...
p02033 Arrow
D: Arrow / Arrow problem rodea is in a one-dimensional coordinate system and stands at x = 0. From this position, throw an arrow of positive integer length that always moves at speed 1 towards the target at x = N. However, rodea is powerless, so we have decided to put a total of M blowers in the section 0 \ leq x \ l...
```python from bisect import bisect_left def inpl(): return list(map(int, input().split())) N, M = inpl() X = inpl() Q = int(input()) L = inpl() X += [N+1] initcost = X[0] - 1 costs = [X[i+1] - X[i] - 1 for i in range(M) if X[i+1] - X[i] > 1] C = [0]*(N+1) C[0] = - 10**9 for i in range(1, N+1): cost = 0 cost...
p02176 Shortest Crypt
problem Cryptography is all the rage at xryuseix's school. Xryuseix, who lives in a grid of cities, has come up with a new cryptography to decide where to meet. The ciphertext consists of the $ N $ character string $ S $, and the $ S_i $ character determines the direction of movement from the current location. The di...
```python N = int(input()) word = list(input()) X1 = ['A','B','C','D','E','F','G','H','I','J','K','L','M'] X2 = ['N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] Y1 = ['a','b','c','d','e','f','g','h','i','j','k','l','m'] Y2 = ['n','o','p','q','r','s','t','u','v','w','x','y','z'] x = 0 y = 0 answer = "" for i in wor...
p02319 0-1 Knapsack Problem II
You have N items that you want to put them into a knapsack. Item i has value vi and weight wi. You want to find a subset of items to put such that: * The total value of the items is as large as possible. * The items have combined weight at most W, that is capacity of the knapsack. Find the maximum total value of i...
```python n, m = map(int, input().split()) VW = [tuple(map(int, input().split())) for i in range(n)] V = [v for v, w in VW] W = [w for v, w in VW] # n, m = 4, 5 # V = [4, 5, 2, 8] # W = [2, 2, 1, 3] # DP[i][j]=i個の品物で価値j以上で最小の重さ sv = sum(V) inf = 10**10 DP = [[inf for j in range(sv+1)] for i in range(n+1)] DP[0][0] = 0 ...
p02464 Set Intersection
Find the intersection of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$. Constraints * $1 \leq n, m \leq 200,000$ * $0 \leq a_0 < a_1 < ... < a_{n-1} \leq 10^9$ * $0 \leq b_0 < b_1 < ... < b_{m-1} \leq 10^9$ Input The input is given in the following format. $n$ $a_0 \; a_1 \; ....
```python def main(): n = int(input()) a = list(map(int,input().split())) m = int(input()) b = list(map(int,input().split())) s = sorted(set(a)&set(b)) for c in s:print (c) if __name__ == '__main__': main() ```
1000_A. Codehorses T-shirts
Codehorses has just hosted the second Codehorses Cup. This year, the same as the previous one, organizers are giving T-shirts for the winners. The valid sizes of T-shirts are either "M" or from 0 to 3 "X" followed by "S" or "L". For example, sizes "M", "XXS", "L", "XXXL" are valid and "XM", "Z", "XXXXL" are not. Ther...
```python t=int(input()) pre=[] curr=[] for i in range(t): s1=input() pre.append(s1) for i in range(t): s2=input() curr.append(s2) z=0 for i in range(t): if pre[i] in curr: curr.remove(pre[i]) pass else: z+=1 print(z) ```
1025_B. Weakened Common Divisor
During the research on properties of the greatest common divisor (GCD) of a set of numbers, Ildar, a famous mathematician, introduced a brand new concept of the weakened common divisor (WCD) of a list of pairs of integers. For a given list of pairs of integers (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) their WCD is arbit...
```python def gcd(a,b): if a%b==0: return b else: return gcd(b,a%b) import math def pr(n): a=[] while n % 2 == 0: a.append(2) n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: a.append(i) ...
1068_D. Array Without Local Maximums
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≤ a_{2}, a_{n} ≤ a_{n-1} and a_{i} ≤ max(a_{i-1}, ...
```python import os from io import BytesIO from math import trunc if os.name == 'nt': input = BytesIO(os.read(0, os.fstat(0).st_size)).readline MX = 201 MOD = 998244353 MODF = float(MOD) MODF_inv = 1.0 / MODF quickmod1 = lambda x: x - MODF * trunc(x / MODF) def quickmod(a): return a - MODF * trunc(a * MODF...
1139_C. Edgy Trees
You are given a tree (a connected undirected graph without cycles) of n vertices. Each of the n - 1 edges of the tree is colored in either black or red. You are also given an integer k. Consider sequences of k vertices. Let's call a sequence [a_1, a_2, …, a_k] good if it satisfies the following criterion: * We will...
```python kk=lambda:map(int,input().split()) ll=lambda:list(kk()) n, k = kk() dsud = {i:{i} for i in range(n)} dsup = {i:i for i in range(n)} for _ in range(n-1): u, v, xi = kk() u,v = u-1,v-1 if xi == 0: s1, s2 = dsud[dsup[u]], dsud[dsup[v]] if len(s1) > len(s2): s1 |= s2 del dsud[dsup[v]] for el in s2...
1157_C2. Increasing Subsequence (hard version)
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2). You are given a sequence a consisting of n integers. You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the...
```python import sys sys.setrecursionlimit(10**7) N = int(input()) number = list(map(int, input().split())) seq = [] ans = [] l = 0 r = N-1 def correct(ans, l, r, action): for i in range(len(ans)-1, -1, -1): if not ans[i] == 'X': break ans[i] = action if action == 'L': ...
1198_A. MP3
One common way of digitalizing sound is to record sound intensity at particular time moments. For each time moment intensity is recorded as a non-negative integer. Thus we can represent a sound file as an array of n non-negative integers. If there are exactly K distinct values in the array, then we need k = ⌈ log_{2} ...
```python import math n, m = map(int, input().strip().split()) a = list(map(int, input().strip().split())) a.sort() lastval = -1 b = list() for x in a: if x != lastval: b.append(1) lastval = x else: b[-1] += 1 k = len(b) while k > (1 << ((8*m)//n)): k -= 1 ans = 0 for x in range(k): ans += b[x] res = ...
1238_B. Kill 'Em All
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters. The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'...
```python import sys def input(): str = sys.stdin.readline() return str[:-1] def unique(x, first, last): if first == last: return last result = first while first + 1 != last: first += 1 if(x[result] != x[first]): result += 1 x[result] = x[first] re...
1256_C. Platforms Jumping
There is a river of width n. The left bank of the river is cell 0 and the right bank is cell n + 1 (more formally, the river can be represented as a sequence of n + 2 cells numbered from 0 to n + 1). There are also m wooden platforms on a river, the i-th platform has length c_i (so the i-th platform takes c_i consecuti...
```python from collections import defaultdict import sys input=sys.stdin.readline n,m,d=map(int,input().split()) c=[int(i) for i in input().split()] ind=defaultdict(int) suff=n for i in range(m-1,-1,-1): suff-=c[i] ind[i+1]=suff+1 indl=[] for i in ind: indl.append(i) indl.reverse() cur=0 for i in indl: ...
127_C. Hot Bath
Bob is about to take a hot bath. There are two taps to fill the bath: a hot water tap and a cold water tap. The cold water's temperature is t1, and the hot water's temperature is t2. The cold water tap can transmit any integer number of water units per second from 0 to x1, inclusive. Similarly, the hot water tap can ...
```python import math def gcd(a,b): if(b==0): return a return gcd(b,a%b) l=input().split() t1=int(l[0]) t2=int(l[1]) x1=int(l[2]) x2=int(l[3]) t0=int(l[4]) num1=t2-t0 num2=t0-t1 if(t1==t2): print(x1,x2) quit() if(num1==0): print(0,x2) quit() if(num2==0): print(x1,0) quit() z=num2...
12_B. Correct Solution?
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number n to Bob and said: —Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes....
```python def sort(s): return sorted(sorted(s), key=str.upper) s=input() s1=input() l=sort(s) c=l.count('0') res="" if(len(l)>c): res=res+l[c] for i in range(c): res=res+l[i] for i in range(c+1,len(s)): res=res+l[i] if(s1==res): print("OK") else: print("WRONG_ANSWER") ```
1323_D. Present
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realiz...
```python from bisect import bisect_left, bisect_right def go(): n = int(input()) a = list(map(int, input().split())) b = max(a).bit_length() res = 0 vals = a for i in range(b + 1): # print("") b2 = 2 << i b1 = 1 << i a0 = [aa for aa in a if aa & b1==0] ...
1342_C. Yet Another Counting Problem
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i ≤ x ≤ r_i, and ((x mod a) mod b) ≠ ((x mod b) mod a). Calculate the answer for each query. Recall that y mod z is the remainder of the division of y by z...
```python def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) t = int(input()) for i in range(t): a, b, q = map(int, input().split()) mi = min(a, b) ma = max(a, b) for j in range(q): l, r = map(int, input().split()) l = max(l, ma) if a == b or ...
1364_C. Ehab and Prefix MEXs
Given an array a of length n, find another array, b, of length n such that: * for each i (1 ≤ i ≤ n) MEX(\\{b_1, b_2, …, b_i\})=a_i. The MEX of a set of integers is the smallest non-negative integer that doesn't belong to this set. If such array doesn't exist, determine this. Input The first line contains an ...
```python n=int(input()) arr=list(map(int,input().split())) flag=0 vis=[0]*(10**6+1) for i in range(n): if arr[i]>i+1: flag=1 vis[arr[i]]=1 if flag==1: print(-1) quit() b=[-1]*(n) for i in range(1,n): if arr[i-1]!=arr[i]: b[i]=arr[i-1] not_vis=[] for i in range(10**6+1): if vis[i...
1384_D. GameGame
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
```python from math import inf as inf from math import * from collections import * import sys import os input=sys.stdin.readline for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=[0]*31 fl="DRAW" for i in a: z=bin(i)[2:] z=z.zfill(31) for j in r...
1406_A. Subset Mex
Given a set of integers (it can contain equal elements). You have to split it into two subsets A and B (both of them can contain equal elements or be empty). You have to maximize the value of mex(A)+mex(B). Here mex of a set denotes the smallest non-negative integer that doesn't exist in the set. For example: * m...
```python t=int(input()) while t!=0: t-=1 n=int(input()) li=list(map(int,input().split())) dic={} dic2={} a=0 b=0 flag=0 ans=[0]*101 for i in li: if i not in dic and i not in dic2: dic[i]=1 else: ans[i]=1 dic2[i]=1 i...
1427_B. Chess Cheater
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
```python from functools import reduce import os import sys from collections import * #from fractions import * from math import * from bisect import * from heapq import * from io import BytesIO, IOBase input = lambda: sys.stdin.readline().rstrip("\r\n") def value(): return tuple(map(int, input().split())) # multiple va...
1450_B. Balls of Steel
You have n distinct points (x_1, y_1),…,(x_n,y_n) on the plane and a non-negative integer parameter k. Each point is a microscopic steel ball and k is the attract power of a ball when it's charged. The attract power is the same for all balls. In one operation, you can select a ball i to charge it. Once charged, all ba...
```python # cook your dish here remaing_test_cases = int(input()) while remaing_test_cases > 0: points_count,K = map(int,input().split()) points = [] for i in range(points_count): x,y = map(int,input().split()) points.append([x,y]) flag = 0 for i in range(points_count): c...
149_B. Martian Clock
Having stayed home alone, Petya decided to watch forbidden films on the Net in secret. "What ungentlemanly behavior!" — you can say that, of course, but don't be too harsh on the kid. In his country films about the Martians and other extraterrestrial civilizations are forbidden. It was very unfair to Petya as he adored...
```python s = input() a = s[:s.index(":")] b = s[s.index(":")+1:] a2 = '' b2 = '' found = False for i in a: if i!='0': found = True if found: a2+=i found = False for i in b: if i!='0': found = True if found: b2+=i a = a2 b = b2 apos = [] bpos = [] values = ['0'...
1523_B. Lord of the Values
<image> While trading on his favorite exchange trader William realized that he found a vulnerability. Using this vulnerability he could change the values of certain internal variables to his advantage. To play around he decided to change the values of all internal variables from a_1, a_2, …, a_n to -a_1, -a_2, …, -a_n...
```python import os import sys from io import BytesIO, IOBase from collections import Counter import math as mt 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 fil...
155_A. I_love_%username%
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him. One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e...
```python n=int(input()) a=list(map(int,input().split())) c=[] d=0 c.append(a[0]) for i in range(1,n): y=a[i]-a[i-1] if y>0 and a[i]>max(c): c.append(a[i]) d+=1 elif y<0 and a[i]<min(c): c.append(a[i]) d+=1 print(d) #print(c) ```
177_C1. Party
To celebrate the second ABBYY Cup tournament, the Smart Beaver decided to throw a party. The Beaver has a lot of acquaintances, some of them are friends with each other, and some of them dislike each other. To make party successful, the Smart Beaver wants to invite only those of his friends who are connected by friends...
```python # maa chudaaye duniya n = int(input()) parents = [i for i in range(n+1)] ranks = [1 for i in range(n+1)] def find(x): if parents[x] != x: parents[x] = find(parents[x]) return parents[x] def union(x, y): xs = find(x) ys = find(y) if xs == ys: return if ranks[xs] > ranks[ys]: parents[ys] = xs eli...
198_B. Jumping on Walls
Vasya plays a computer game with ninjas. At this stage Vasya's ninja should get out of a deep canyon. The canyon consists of two vertical parallel walls, their height is n meters. Let's imagine that we split these walls into 1 meter-long areas and number them with positive integers from 1 to n from bottom to top. Some...
```python from sys import stdin, stdout from collections import deque n, k = map(int, stdin.readline().split()) maps = [] maps.append(list(stdin.readline() + '-')) maps.append(list(stdin.readline() + '-')) visit = [[0, 0] for i in range(n + 1)] visit[0][0] = 1 queue = deque() label = 0 queue.append((0, -1, 0))#твой...
221_C. Little Elephant and Problem
The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array. The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ...
```python n = int(input()) a = list(map(int, input().split())) b = sorted(a) res = 0 for i in range(n): if a[i] != b[i]: res += 1 print('YES' if res <= 2 else 'NO') ```
245_D. Restoring Table
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation. For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative ...
```python n=int(input()) A=[0]*n ans=[0]*n for i in range(n): A[i]=list(map(int,input().split())) for j in range(n): if(j==i):continue ans[i]|=A[i][j] for i in range(n): print(ans[i],' ',end='') ```
270_B. Multithreading
Emuskald is addicted to Codeforces, and keeps refreshing the main page not to miss any changes in the "recent actions" list. He likes to read thread conversations where each thread consists of multiple messages. Recent actions shows a list of n different threads ordered by the time of the latest message in the thread....
```python n = int(input()) arr = list(map(int,input().split())) ans = n-1 for i in range(-1,-n,-1): if arr[i]>arr[i-1]: ans-=1 else: break print(ans) ```
317_B. Ants
It has been noted that if some ants are put in the junctions of the graphene integer lattice then they will act in the following fashion: every minute at each junction (x, y) containing at least four ants a group of four ants will be formed, and these four ants will scatter to the neighbouring junctions (x + 1, y), (x ...
```python from sys import * f = lambda: map(int, stdin.readline().split()) n, t = f() m = 65 r = range(m) p = [[0] * m for i in r] p[1][0] = n // 4 p[0][0] = n % 4 q = k = 1 while q: k += 1 q = 0 for x in r[1:k]: for y in r[:x + 1]: if p[x][y] < 4: continue q = 1 ...
341_B. Bubble Sort Graph
Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a...
```python from bisect import bisect_left, bisect_right, insort R = lambda: map(int, input().split()) n, arr = int(input()), list(R()) dp = [] for i in range(n): idx = bisect_left(dp, arr[i]) if idx >= len(dp): dp.append(arr[i]) else: dp[idx] = arr[i] print(len(dp)) ```
388_C. Fox and Card Game
Fox Ciel is playing a card game with her friend Fox Jiro. There are n piles of cards on the table. And there is a positive integer on each card. The players take turns and Ciel takes the first turn. In Ciel's turn she takes a card from the top of any non-empty pile, and in Jiro's turn he takes a card from the bottom o...
```python import re def main(): n=eval(input()) a=[] s=[] s.append(0) s.append(0) while n: n-=1 temp=re.split(' ',input()) k=eval(temp[0]) for i in range(k>>1): s[0]+=eval(temp[i+1]) if k&1: a.append(eval(temp[(k+1)>>1])) for i in range((k+1)>>1,k): s[1]+=eval(temp...
409_A. The Great Game
Two teams meet in The Game World Championship. Some scientists consider this game to be the most intellectually challenging game in the world. You are given two strings describing the teams' actions in the final battle. Figure out who became the champion. Input The input contains two strings of equal length (between ...
```python """ Codeforces April Fools Contest 2014 Problem A Author : chaotic_iak Language: Python 3.3.4 """ class InputHandlerObject(object): inputs = [] def getInput(self, n = 0): res = "" inputs = self.inputs if not inputs: inputs.extend(input().split(" ")) if n == 0: ...
436_B. Om Nom and Spiders
Om Nom really likes candies and doesn't like spiders as they frequently steal candies. One day Om Nom fancied a walk in a park. Unfortunately, the park has some spiders and Om Nom doesn't want to see them at all. <image> The park can be represented as a rectangular n × m field. The park has k spiders, each spider at ...
```python #!/usr/bin/python import re import inspect from sys import argv, exit def rstr(): return input() def rint(): return int(input()) def rints(splitchar=' '): return [int(i) for i in input().split(splitchar)] def varnames(obj, namespace=globals()): return [name for name in namespace if namespa...
459_C. Pashmak and Buses
Recently Pashmak has been employed in a transportation company. The company has k buses and has a contract with a school which has n students. The school planned to take the students to d different places for d days (each day in one place). Each day the company provides all the buses for the trip. Pashmak has to arrang...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def base(x,k,d): ans = [] while x: ans.append(x%k+1) x //= k ans.reverse() return [1]*(d-len(ans))+ans def main(): n,k,d = map(int,input().split()) if n == 1: ...
480_B. Long Jumps
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measure...
```python def main(): from bisect import bisect_left n, l, x, y = map(int, input().split()) aa, d = list(map(int, input().split())), {} for z in (x, y, y + x): for a in aa: a += z if a > l: break b = aa[bisect_left(aa, a)] if b <= a...