name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p02886 AtCoder Beginner Contest 143 - TAKOYAKI FESTIVAL 2019
It's now the season of TAKOYAKI FESTIVAL! This year, N takoyaki (a ball-shaped food with a piece of octopus inside) will be served. The deliciousness of the i-th takoyaki is d_i. As is commonly known, when you eat two takoyaki of deliciousness x and y together, you restore x \times y health points. There are \frac{N...
```python n = int(input()) l = list(map(int, input().split())) print(sum(l[i]*sum(l[i+1:]) for i in range(len(l)-1))) ```
p03021 AtCoder Grand Contest 034 - Complete Compress
You are given a tree with N vertices numbered 1, 2, ..., N. The i-th edge connects Vertex a_i and Vertex b_i. You are also given a string S of length N consisting of `0` and `1`. The i-th character of S represents the number of pieces placed on Vertex i. Snuke will perform the following operation some number of times:...
```python import sys input = sys.stdin.readline n = int(input()) s = "Q"+input() ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0 for i in range(n+1)] for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 leaf = set() for i in range(1,n+1...
p03161 Educational DP Contest - Frog 2
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i. There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N: * If the frog is currently on Stone i, jump to one of the following: Stone i + 1, i + 2, \ld...
```python N,K=map(int,input().split()) h=list(map(int,input().split())) dp=[10**10]*(N)#dp[i]→i+1番目の柱にくる最小コスト dp[0]=0 for i in range(N-1): dp[i+1]=min(dp[i+1-j]+abs(h[i+1]-h[i+1-j]) for j in range(1,min(i+1,K)+1)) print(dp[N-1]) ```
p03304 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - Ordinary Beauty
Let us define the beauty of a sequence (a_1,... ,a_n) as the number of pairs of two adjacent elements in it whose absolute differences are d. For example, when d=1, the beauty of the sequence (3, 2, 3, 10, 9) is 3. There are a total of n^m sequences of length m where each element is an integer between 1 and n (inclusi...
```python n,m,d=map(int,input().split()) if d!=0: print((2*(n-d)*(m-1))/(n**2)) else: print(((n-d)*(m-1))/(n**2)) ```
p03464 AtCoder Grand Contest 020 - Ice Rink Game
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces: * Form groups consisting of A_i children each! Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m...
```python from math import ceil def solve(rounds): mx, mn = 3, 2 if rounds[-1] != 2: return (-1,) for r in reversed(rounds[:-1]): if mx < r: return (-1,) mn = ceil(mn / r) * r mx = mx // r * r + r - 1 if mn > mx: return (-1,) return mn, mx k = ...
p03623 AtCoder Beginner Contest 071 - Meal Delivery
Snuke lives at position x on a number line. On this line, there are two stores A and B, respectively at position a and b, that offer food for delivery. Snuke decided to get food delivery from the closer of stores A and B. Find out which store is closer to Snuke's residence. Here, the distance between two points s and...
```python a,b,c=map(int,input().split()) print('A' if abs(a-b)<abs(c-a) else 'B') ```
p03783 AtCoder Regular Contest 070 - NarrowRectangles
AtCoDeer the deer found N rectangle lying on the table, each with height 1. If we consider the surface of the desk as a two-dimensional plane, the i-th rectangle i(1≤i≤N) covers the vertical range of [i-1,i] and the horizontal range of [l_i,r_i], as shown in the following figure: <image> AtCoDeer will move these rect...
```python N = int(input()) P = [list(map(int, input().split())) for i in range(N)] INF = 10**18 from heapq import heappush, heappop l0, r0 = P[0] L = [-l0+1] R = [l0-1] s = t = 0 res = 0 for i in range(N-1): l0, r0 = P[i] l1, r1 = P[i+1] s += (r1 - l1); t += (r0 - l0) if -s-L[0] <= l1-1 <= t+R...
p03952 AtCoder Grand Contest 006 - Median Pyramid Easy
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically. <image> A pyramid with N=4 steps Snuke wrote a per...
```python import sys sys.setrecursionlimit(10 ** 8) ini = lambda: int(sys.stdin.readline()) inm = lambda: map(int, sys.stdin.readline().split()) inl = lambda: list(inm()) ins = lambda: sys.stdin.readline().rstrip() debug = lambda *a, **kw: print("\033[33m", *a, "\033[0m", **dict(file=sys.stderr, **kw)) n, x = inm() ...
p00042 A Thief
A thief sneaked into a museum with a lot of treasures with only one large furoshiki. There are many things I want to steal, but the weight that the furoshiki can withstand is limited, and if it exceeds this, the furoshiki will tear. Therefore, the thief must consider a combination of treasures that will not break the p...
```python """ 0-1ナップザック wi...i個目の重さ vi...i個目の価値 2次元 dp[i][j]...i個目までの宝で重さjの時の価値の最大 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - wi] + vi) (wi <= j) dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) (wi > j) 1次元 dp[j]...重さjの時の価値の最大 dp[j] = max(dp[j], dp[j - wi] + vi) (wi <= j <= w) ...
p00174 Badminton
It's been a while since I played with A, B, and C. Mr. A and Mr. B became players, and Mr. C became a referee and played a badminton singles game. The rules decided by the three people are as follows. * 3 Play the game. * The person who gets 11 points first wins the game. * The first serve of the first game starts wit...
```python import sys while True: a=[] for i in range(3): z=str(input()) if z=="0": sys.exit() a.append(z) A,B,C=a[0],a[1],a[2] A=A[1:]+B[0] B=B[1:]+C[0] C=C[1:] print(A.count("A"), A.count("B")) print(B.count("A"), B.count("B")) d,e=C.count("A"),C....
p00330 Word
The smallest unit of data handled by a computer is called a bit, and the amount of information that represents multiple bits together is called a word. Currently, many computers process one word as 32 bits. For a computer that represents one word in 32 bits, create a program that outputs the amount of data W given in ...
```python # coding: utf-8 # Your code here! W = int(input()) print(W*32) ```
p00503 Fish
problem To the west of the Australian continent is the wide Indian Ocean. Marine researcher JOI is studying the properties of N species of fish in the Indian Ocean. For each type of fish, a rectangular parallelepiped habitat range is determined in the sea. Fish can move anywhere in their habitat, including boundaries...
```python # copy n, k = map(int, input().split()) plst = [] xlst = [] ylst = [] dlst = [] for _ in range(n): x1, y1, d1, x2, y2, d2 = map(int, input().split()) plst.append((x1, y1, d1, x2, y2, d2)) xlst.append(x1) xlst.append(x2) ylst.append(y1) ylst.append(y2) dlst.append(d1) dlst.appe...
p00687 Unable Count
> I would, if I could, > If I couldn't how could I? > I couldn't, without I could, could I? > Could you, without you could, could ye? > Could ye? could ye? > Could you, without you could, could ye? It is true, as this old rhyme says, that we can only DO what we can DO and we cannot DO what we cannot DO. Changing ...
```python while True: n,a,b = map(int, input().split()) if n==0: break ok = [1]*(n+1) for i in range(b): for j in range(0,n-i*a+1,b): ok[i*a+j] = 0 print(sum(ok)) ```
p00829 Leaky Cryptography
The ACM ICPC judges are very careful about not leaking their problems, and all communications are encrypted. However, one does sometimes make mistakes, like using too weak an encryption scheme. Here is an example of that. The encryption chosen was very simple: encrypt each chunk of the input by flipping some bits acco...
```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**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x i...
p01093 Selection of Participants of an Experiment
Selection of Participants of an Experiment Dr. Tsukuba has devised a new method of programming training. In order to evaluate the effectiveness of this method, he plans to carry out a control experiment. Having two students as the participants of the experiment, one of them will be trained under the conventional metho...
```python while True: n = int(input()) if n == 0: break score = list(map(int,input().split())) score.sort() ans = max(score) for i in range(1,n): aa = abs(score[i] - score[i-1]) if ans > aa: ans = aa print(ans) ```
p01545 House Moving
Taro has decided to move. Taro has a lot of luggage, so I decided to ask a moving company to carry the luggage. Since there are various weights of luggage, I asked them to arrange them in order from the lightest one for easy understanding, but the mover left the luggage in a different order. So Taro tried to sort the l...
```python import math class FenwickTree: def __init__(self, a_list, f, default): # 0-indexed self.N = len(a_list) self.bit = a_list[:] self.f = f self.default = default for _ in range(self.N, 1 << (math.ceil(math.log(self.N, 2)))): self.bit.append(self.d...
p01701 North North West
Problem Statement We can describe detailed direction by repeating the directional names: north, south, east and west. For example, northwest is the direction halfway between north and west, and northnorthwest is between north and northwest. In this problem, we describe more detailed direction between north and west a...
```python import re while 1: s=input() if s=='#':break s=re.split('[w|n]',s)[1:];c=1 d=90 if s[-1]=='est' else 0 for x in s[:-1][::-1]: d*=2 d+=90if x=='est'else-90 c*=2 while d&1==0 and c&1==0:d//=2;c//=2 if c==1:print(d) else:print(d,c,sep='/') ```
p01845 Curry Making
Curry making As the ACM-ICPC domestic qualifying is approaching, you who wanted to put more effort into practice decided to participate in a competitive programming camp held at a friend's house. Participants decided to prepare their own meals. On the first night of the training camp, the participants finished the da...
```python Q=[] while True: A=list(map(int,input().split())) if A==[0,0,0,0]: break else: Q.append(A) for k in range(len(Q)): for i in range(100000): P=(Q[k][0]+i*Q[k][3])/Q[k][2]-Q[k][1] if P>=0: print(i) break ```
p01981 Change of the Era Name
Revised The current era, Heisei, will end on April 30, 2019, and a new era will begin the next day. The day after the last day of Heisei will be May 1, the first year of the new era. In the system developed by the ACM-ICPC OB / OG Association (Japanese Alumni Group; JAG), the date uses the Japanese calendar (the Japa...
```python import sys def solve(g, y, m, d): y = int(y) m = int(m) d = int(d) if y == 31 and m >= 5: print('?', y-30, m, d) elif y >= 32: print('?', y-30, m, d) else: print(g, y, m, d) while True: s = input() if s == "#": break solve(*map(str, ...
p02127 AABABCAC
Problem Given the strings $ s $, $ t $. First, let the string set $ A = $ {$ s $}, $ B = \ phi $. At this time, I want to perform the following operations as much as possible. operation step1 Perform the following processing for all $ u ∊ A $. 1. From all subsequences of $ u $ (not necessarily contiguous), choose ...
```python s = input() t = " " + input() line = [1] next = 1 t_size = len(t) flag = False for i in s: if t[next] == i: line[0] += 1 next = line[0] line += [0] j = 0 while line[j] == t_size: line[j] = 0 next = line[j + 1] = line[j + 1] + 1 j ...
p02268 Binary Search
You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S. Notes Constraints * Elements in S is sorted in ascending order * n ≤ 100000 * q ≤ 50000 * 0 ≤ an element in S ≤ 109 * 0 ≤ an element in T ≤ 109 ...
```python import bisect n=int(input()) S=list(map(int,input().split())) q=int(input()) T=list(map(int,input().split())) ans=0 for t in T: x=bisect.bisect_left(S,t) if S[x]==t: ans+=1 print(ans) ```
p02415 Toggling Cases
Write a program which converts uppercase/lowercase letters to lowercase/uppercase for a given string. Constraints * The length of the input string < 1200 Input A string is given in a line. Output Print the converted string in a line. Note that you do not need to convert any characters other than alphabetical lett...
```python t = input() t = t.swapcase() print(t) ```
1000_D. Yet Another Problem On a Subsequence
The sequence of integers a_1, a_2, ..., a_k is called a good array if a_1 = k - 1 and a_1 > 0. For example, the sequences [3, -1, 44, 0], [1, -99] are good arrays, and the sequences [3, 7, 8], [2, 5, 4, 1], [0] — are not. A sequence of integers is called good if it can be divided into a positive number of good arrays....
```python import sys input=sys.stdin.readline N=10**4+10 mod=998244353 g1=[1,1] g2=[1,1] inv=[0,1] for i in range(2,N+1): g1.append((g1[-1]*i)%mod) inv.append((-inv[mod%i]*(mod//i))%mod) g2.append((g2[-1]*inv[-1])%mod) def comb(m,r,mod): if r<0 or r>m: return 0 return (g1[m]*g2[r]*g2[m-r])%m...
106_A. Card Game
There is a card game called "Durak", which means "Fool" in Russian. The game is quite popular in the countries that used to form USSR. The problem does not state all the game's rules explicitly — you can find them later yourselves if you want. To play durak you need a pack of 36 cards. Each card has a suit ("S", "H", ...
```python a = input() b,c = input().split() lst = ["6", "7", "8", "9", "T", "J", "Q", "K" , "A"] if b[1] ==c[1]: print('YES' if lst.index(b[0]) > lst.index(c[0]) else 'NO') elif b[1] == a: print('YES') else: print('NO') ```
1090_M. The Pleasant Walk
There are n houses along the road where Anya lives, each one is painted in one of k possible colors. Anya likes walking along this road, but she doesn't like when two adjacent houses at the road have the same color. She wants to select a long segment of the road such that no two adjacent houses have the same color. H...
```python # n, k = map(int, input().split()) l = list(map(int, input().split())) m = [] f = [] s=set(l) if len(s)== 1: print("1") else: for i in range(len(l) - 1): if l[i] == l[i + 1]: f.append(m) # print(len(f)) # print(m) m = [] else: ...
110_C. Lucky Sum of Digits
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 wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with...
```python n=int(input()) from collections import Counter c=Counter([]) c[1]=[-1,2] c[2]=[-2,4] c[3]=[-3,6] c[4]=[0,1] c[5]=[-1,3] c[6]=[-2,5] a=n%7 s=n//7 f=0 if a==0: print ('7'*s) else: s+=c[a][0] f+=c[a][1] if s<0: if n%4==0: print ('4'*(n//4)) else: print (-1)...
1157_F. Maximum Balanced Circle
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle. A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen peop...
```python import sys from collections import namedtuple from itertools import groupby input = sys.stdin.readline def main(): Data = namedtuple('Data', ['arr', 'l', 'r']) _ = int(input()) a = list(map(int, input().split())) f = [ [0, 0] for i in range(max(a) + 2) ] for x in a: f[x][0] = x...
1215_C. Swap Letters
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string...
```python a=int(input()) s=input() r=input() cmap=[] tmap=[] for i in range(len(s)): if(s[i]=='a' and r[i]=='b'): cmap.append(i) elif(s[i]=='b' and r[i]=='a'): tmap.append(i) r=len(cmap) t=len(tmap) if(((r%2==1 and t%2==0) or (r%2==0 and t%2==1))): print(-1) else: total=r//2+t//...
1238_E. Keyboard Purchase
You have a password which you often type — a string s of length n. Every character of this string is one of the first m lowercase Latin letters. Since you spend a lot of time typing it, you want to buy a new keyboard. A keyboard is a permutation of the first m Latin letters. For example, if m = 3, then there are six ...
```python import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline INF = 10**9 n, m = [int(item) for item in input().split()] s = input().rstrip() count = [[0] * m for _ in range(m)] ord_a = ord("a") for c1, c2 in zip(s, s[1:]): c1 = ord(c1) - ord_a c2 = ord(c2) - ord_a if c1 != c2: cou...
1256_F. Equalizing Two Strings
You are given two strings s and t both of length n and both consisting of lowercase Latin letters. In one move, you can choose any length len from 1 to n and perform the following operation: * Choose any contiguous substring of the string s of length len and reverse it; * at the same time choose any contiguous ...
```python import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations d...
1280_A. Cut and Paste
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning: * If ℓ = 0, then the cursor...
```python for _ in range(int(input())): x = int(input()) s = input() l = 0 while(len(s)<x): s += s[l+1:]*(int(s[l])-1) l+=1 count=len(s) for k in range(l,x): count+=((count-k-1)*(int(s[k])-1)) count%= 1000000007 print(count) ```
12_E. Start of the season
Before the start of the football season in Berland a strange magic ritual is held. The most experienced magicians have to find a magic matrix of the size n × n (n is even number). Gods will never allow to start the championship without it. Matrix should contain integers from 0 to n - 1, main diagonal should contain onl...
```python n=int(input()) a=[[0 for j in range(n)] for i in range(n)] for i in range(n-1): for j in range(n-1): if i!=j: a[i][j]=(i+j)%n+int(i+j>=n) a[i][n-1]=((n-1+2*i)%n+int(n-1+2*i>=n))%n+int(n-1+2*i>2*(n-1)) for i in range(n-1): a[n-1][i]=((n-1+2*i)%n+int(n-1+2*i>=n))%n+int(n-1+2*i>2*...
1324_A. Yet Another Tetris Problem
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures. Yo...
```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 in...
1365_A. Matrix Game
Ashish and Vivek play a game on a matrix consisting of n rows and m columns, where they take turns claiming cells. Unclaimed cells are represented by 0, while claimed cells are represented by 1. The initial state of the matrix is given. There can be some claimed cells in the initial state. In each turn, a player must ...
```python t = int(input()) for _ in range(t): n,m = map(int,input().split()) l = [] s = 0 t1,t2 = 0,0 for i in range(n): l1 = list(map(int,input().split())) l.append(l1) for i in range(n): f = 1 for j in range(m): if l[i][j] == 1: f = 0 if f: t1 += 1 for i in range(m): f = 1 for j in ran...
1385_A. Three Pairwise Maximums
You are given three positive (i.e. strictly greater than zero) integers x, y and z. Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c. You have to answer t independent test cases. Print required a, b a...
```python t = int(input()) input_list = [[0,0,0] for i in range(t)] for i in range(t): x,y,z = input().split() input_list[i][0] = int(x) input_list[i][1] = int(y) input_list[i][2] = int(z) ans_list = ["NO" for i in range(t)] output_list = [[0,0,0] for i in range(t)] for i in range(t): x,y,z = inpu...
1406_D. Three Sequences
You are given a sequence of n integers a_1, a_2, …, a_n. You have to construct two sequences of integers b and c with length n that satisfy: * for every i (1≤ i≤ n) b_i+c_i=a_i * b is non-decreasing, which means that for every 1<i≤ n, b_i≥ b_{i-1} must hold * c is non-increasing, which means that for every 1<...
```python import sys import atexit class Fastio: def __init__(self): self.ibuf = bytes() self.obuf = bytearray() self.pil = 0 self.pir = 0 def load(self): self.ibuf = self.ibuf[self.pil:] self.ibuf += sys.stdin.buffer.read(131072) self.pil = 0 se...
1427_E. Xum
You have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard. You may write new numbers on the blackboard with the following two operations. * You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the ...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): print("500") cnt = 500 x = int(input()) if x % 4 == 3: print(str(x) + " + " + str(x)) print(str(2 * x) + " + " + str(x)) cnt -= 2 x *= 3 xCpy = x bigX = x while x...
1450_E. Capitalism
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j. In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more...
```python n,m = map(int,input().split());edge = [[] for i in range(n)];cost = [[10**18*(i!=j) for j in range(n)] for i in range(n)] for _ in range(m):u,v,b = map(int,input().split());edge[u-1].append(v-1);edge[v-1].append(u-1);cost[u-1][v-1] = 1;cost[v-1][u-1] = (1 if not b else -1) used = [False]*n;cond = [0]*n;used[0...
1474_C. Array Destruction
You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a. It could have been an easy task, but it turned out that you should follow some rules: 1. In the beginning, you select any positive integer x. 2. Then you ...
```python from sys import stdin #import math input = stdin.readline q = int(input()) for _ in range(q): n = int(input()) a = list(map(int, input().split())) a.sort() l = a[-1] a.pop() for i in range(2*n-1): d = {} for ii in range(2*n - 1): if ii == i: ...
1523_E. Crypto Lights
<image> To monitor cryptocurrency exchange rates trader William invented a wonderful device consisting of n lights arranged in a row. The device functions in the following way: Initially, all lights on William's device are turned off. At the beginning of a new iteration the device randomly, with a uniform distributio...
```python def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0...
155_D. Colliders
By 2312 there were n Large Hadron Colliders in the inhabited part of the universe. Each of them corresponded to a single natural number from 1 to n. However, scientists did not know what activating several colliders simultaneously could cause, so the colliders were deactivated. In 2312 there was a startling discovery:...
```python n, m = map(int, input().split()) n += 1 s = [[] for i in range(n)] for j in range(2, n, 2): s[j] = [2] for i in range(3, n, 2): if s[i]: continue for j in range(i, n, i): s[j].append(i) p, d, r = {}, set(), [''] * m for j in range(m): t = input() i = int(t[2: ]) if t[0] == '...
177_D2. 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(map(int, input().split())) b = list(map(int, input().split())) s, k = 0, n - m for i in range(n): if i < m: s += b[i] a[i] = (a[i] + s) % c if i >= k: s -= b[i - k] print(' '.join(str(i) for i in a)) ```
222_A. Shooshuns and Sequence
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps: 1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence; 2. Delete the first number of the current s...
```python n,k=map(int,input().split()) l=list(map(int,input().split())) f=l[k-1] if l[k-1:].count(f) == n-k+1: r = 0 for i in range(k-2,-1,-1): if l[k-1] != l[i]: break r+=1 print(len(l[:k-1-r])) else: print(-1) ```
270_E. Flawed Flow
Emuskald considers himself a master of flow algorithms. Now he has completed his most ingenious program yet — it calculates the maximum flow in an undirected graph. The graph consists of n vertices and m edges. Vertices are numbered from 1 to n. Vertices 1 and n being the source and the sink respectively. However, his...
```python import sys from collections import deque DST_VERTEX = 0 EDGE_CAP = 1 EDGE_ID = 2 EDGE_DIR = 3 def bfs(flow, graph, n, m): dirs = [-1 for _ in range(m)] q = deque() q.append(0) q_size = 1 while q_size > 0: cur_node = q.popleft() q_size -= 1 for i in range(len(graph...
294_B. Shaass and Bookshelf
Shaass has n books. He wants to make a bookshelf for all his books. He wants the bookshelf's dimensions to be as small as possible. The thickness of the i-th book is ti and its pages' width is equal to wi. The thickness of each book is either 1 or 2. All books have the same page heights. <image> Shaass puts the books...
```python n = int(input()) t = [] for i in range(n): e = list(map(int,input().split())) t.append(e) size = 0 size2 = 0 for i in t: size += i[0] size2 += i[1] matrix = [[-1000]*(size+1) for i in range(n)] for i in range(n): matrix[i][0] = 0 for i in range(n): for j in range(1,size+1): ...
365_B. The Fibonacci Segment
You have array a1, a2, ..., an. Segment [l, r] (1 ≤ l ≤ r ≤ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 ≤ i ≤ r). Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]). Your task is to find a ...
```python import sys n = int(input()) a = list(map(int, input().split())) if n <= 2: print(n) sys.exit() best = 0 mem = a[:2] cur = 0 for i in a[2:]: if mem[0] + mem[1] == i: cur += 1 else: if cur > best: best = cur cur = 0 mem = mem[1:] + [i] if cur > best: best = cur print(...
389_A. Fox and Number Game
Fox Ciel is playing a game with numbers now. Ciel has n positive integers: x1, x2, ..., xn. She can do the following operation as many times as needed: select two different indexes i and j such that xi > xj hold, and then apply assignment xi = xi - xj. The goal is to make the sum of all numbers as small as possible. ...
```python from sys import stdin, stdout, stderr, setrecursionlimit setrecursionlimit(100000) def debug (*e): if not __debug__: print(*e, file=stderr) def dd(*vals): import inspect, re frame = inspect.getframeinfo(inspect.stack()[1][0]) vs = re.search("dd\((.+)\)", frame.code_context[0]).group(...
409_D. Big Data
Little Petya wanted to give an April Fools Day present to some scientists. After some hesitation he decided to give them the array that he got as a present in Codeforces Round #153 (Div.2). The scientists rejoiced at the gift and decided to put some important facts to this array. Here are the first few of the facts: ...
```python x = int(input()) v = [1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0] print(v[x-1]) ```
45_A. Codecraft III
Today Vasya visited a widely known site and learned that the continuation of his favourite game Codecraft II will appear after exactly k months. He looked at the calendar and learned that at the moment is the month number s. Vasya immediately got interested in what month Codecraft III will appear. Help him understand t...
```python month = str(input()) k = int(input()) m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] j = m.index(month) while k != 0: if j == 11: j = 0 k -= 1 else: j += 1 k -= 1 print(m[j]) ```
529_D. Social Network
Polycarpus got an internship in one well-known social network. His test task is to count the number of unique users who have visited a social network during the day. Polycarpus was provided with information on all user requests for this time period. For each query, we know its time... and nothing else, because Polycarp...
```python def main(): mode="filee" if mode=="file":f=open("test.txt","r") get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()] gets = lambda :[str(x) for x in (f.readline()[:-1] if mode=="file" else input()).split(":")] [n,m,t]=get() a=[0]*20002 b=[0]*20002 ...
555_A. Case of Matryoshkas
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ...
```python n,k = map(int,input().split(" ")) i=0 res=k sh=0 while i<k: i+=1 mas=list(map(int,input().split(" ")))[1:] if mas[0]==1: j=0 while j<(len(mas)-1): if(mas[j]+1!=mas[j+1]): break else: j+=1 sh+=len(mas)-j-1 ...
625_B. War of the Corporations
A long time ago, in a galaxy far far away two giant IT-corporations Pineapple and Gogol continue their fierce competition. Crucial moment is just around the corner: Gogol is ready to release it's new tablet Lastus 3000. This new device is equipped with specially designed artificial intelligence (AI). Employees of Pine...
```python a, b = input(), input() ans = 0 index = a.find (b, 0) while index != -1: ans = ans + 1 index = a.find (b, index + len (b)) print (ans) ```
673_D. Bear and Two Paths
Bearland has n cities, numbered 1 through n. Cities are connected via bidirectional roads. Each road connects two distinct cities. No two roads connect the same pair of cities. Bear Limak was once in a city a and he wanted to go to a city b. There was no direct connection so he decided to take a long walk, visiting ea...
```python n,k=map(int,input().split()) a,b,c,d=input().split() if n<5 or k<n+1: print(-1) else: l=list(set(map(str,range(1,n+1)))-{a,b,c,d}) print(' '.join([a,c]+l+[d,b]+['\n']+[c,a]+l+[b,d])) ```
71_A. Way Too Long Words
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
```python n = int(input()) if 1 <= n <= 100: for i in range(n): word = input() if len(word) > 10: numWord = str(len(word[1:-1])) print(word[0] + numWord + word[-1]) else: print(word) ```
740_C. Alyona and mex
Alyona's mother wants to present an array of n non-negative integers to Alyona. The array should be special. Alyona is a capricious girl so after she gets the array, she inspects m of its subarrays. Subarray is a set of some subsequent elements of the array. The i-th subarray is described with two integers li and ri,...
```python n,m=map(int,input().split()) min_val=9999999 for _ in range(m): y,x=map(int,input().split()) if min_val>x-y: x1=x y1=y min_val=x-y print(min_val+1) L=[0]*n tp=0 listNum=[] for i in range(n): listNum.append(tp) tp+=1 if tp>min_val: tp=0 for i in listNum[:-1]:...
764_B. Timofey and cubes
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents. In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose t...
```python n=int(input()) a=list(map(int,input().split())) i=0 temp=0 for i in range(n//2): if i%2==0: temp=a[i] a[i]=a[n-i-1] a[n-i-1]=temp for r in a: print(r,end=' ') ```
809_A. Do you want a date?
Leha decided to move to a quiet town Vičkopolis, because he was tired by living in Bankopolis. Upon arrival he immediately began to expand his network of hacked computers. During the week Leha managed to get access to n computers throughout the town. Incidentally all the computers, which were hacked by Leha, lie on the...
```python def main(): largemodulus = 1000000007 maxofn = 300001 n = 0 answer = 0 powersoftwo = [] multiplier = 1 for _ in range(maxofn): powersoftwo.append(multiplier) if multiplier >= largemodulus: multiplier = multiplier % largemodulus multiplier *= 2 n = int(input()) ...
854_B. Maxim Buys an Apartment
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale. Maxim often visits h...
```python n,k=map(int,input().split()) mi=1 if k==0: print(0,0) exit() if k==n: print(0,0) exit() if 3*k <=n: ma=2*k else: ma=n-k print(mi,ma) ```
902_B. Coloring a Tree
You are given a rooted tree with n vertices. The vertices are numbered from 1 to n, the root is the vertex number 1. Each vertex has a color, let's denote the color of vertex v by cv. Initially cv = 0. You have to color the tree into the given colors using the smallest possible number of steps. On each step you can c...
```python from queue import * n=int(input()) parent={} child={} for i in range(1,n+1): parent[i]=0 child[i]=[] l=list(map(int,input().split())) for i in range(2,n+1): parent[i]=l[i-2] child[l[i-2]].append(i) l=list(map(int,input().split())) color={} for i in range(1,n+1): color[i]=l[i-1] q=Que...
952_F. 2 + 2 != 4
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution... Input The only line of input data contains the arith...
```python import re;s=input();print(eval(s)+eval(re.sub("-|\+|\d",lambda m:"+-035"[2-"+--".count(m[0])::3],s))) ```
99_C. Help Victoria the Wise
Vasilisa the Wise from a far away kingdom got a present from her friend Helga the Wise from a farther away kingdom. The present is a surprise box, yet Vasilisa the Wise doesn't know yet what the surprise actually is because she cannot open the box. She hopes that you can help her in that. The box's lock is constructed...
```python from functools import reduce def factorial(n): return reduce(lambda x, y: x*y, range(1,n+1)) colors = { 'R' : 0, 'O' : 0, 'Y' : 0, 'G' : 0, 'B' : 0, 'V' : 0 } for c in list(input()): colors[c] += 1 amount = list(reversed(sorted([(colors[key], key) for key in colors]))) amo...
p02540 ACL Contest 1 - Reachable Towns
There are N cities on a 2D plane. The coordinate of the i-th city is (x_i, y_i). Here (x_1, x_2, \dots, x_N) and (y_1, y_2, \dots, y_N) are both permuations of (1, 2, \dots, N). For each k = 1,2,\dots,N, find the answer to the following question: Rng is in City k. Rng can perform the following move arbitrarily many t...
```python n = int(input()) xy = [] idx = [None]*n ys = [None]*n ans = [None]*n accumx = [None]*n accumn = [None]*n for i in range(n): x, y = map(int, input().split()) idx[x-1] = i ys[x-1] = y-1 accumx[-1] = ys[-1] for i in range(n-2, -1, -1): accumx[i] = max(accumx[i+1], ys[i]) accumn[0] = ys[0] for i i...
p02671 AtCoder Grand Contest 044 - Strange Dance
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person. The people are going to dance on two kinds of songs: salsa and rumba. * When a salsa i...
```python n = int(input()) t = input() new_pos = [0] new_w = [0]*len(t) for i in range(1, n+1): ith_bit = [0]*(3**i) # ith_bit[p] : 位置 (p mod 3**i) のi番目bit for k in range(3): for l in range(3**(i-1)): ith_bit[k*3**(i-1)+l] = k pos = new_pos w = new_w # 繰り上がりが起きても ith_bit を正確に捉える...
p02800 Keyence Programming Contest 2020 - Monochromization
We have an H \times W grid, where each square is painted white or black in the initial state. Given are strings A_1, A_2, ..., A_H representing the colors of the squares in the initial state. For each pair (i, j) (1 \leq i \leq H, 1 \leq j \leq W), if the j-th character of A_i is `.`, the square at the i-th row and j-t...
```python import sys input = sys.stdin.readline H,W=map(int,input().split()) A=[input().strip() for i in range(H)] mod=998244353 # factorial,facotiralの逆数を事前計算. FACT=[1] for i in range(1,21): FACT.append(FACT[-1]*i%mod) FACT_INV=[pow(FACT[-1],mod-2,mod)] for i in range(20,0,-1): FACT_INV.append(FACT_INV[-1]*...
p02936 AtCoder Beginner Contest 138 - Ki
Given is a rooted tree with N vertices numbered 1 to N. The root is Vertex 1, and the i-th edge (1 \leq i \leq N - 1) connects Vertex a_i and b_i. Each of the vertices has a counter installed. Initially, the counters on all the vertices have the value 0. Now, the following Q operations will be performed: * Operation...
```python import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline n,q=map(int,input().split()) c=[[] for _ in range(n)] for _ in range(n-1): a,b=map(int,input().split()) a,b=a-1,b-1 c[a].append(b) c[b].append(a) px=[0]*n for I in range(q): p,x=map(int,input().split()) px[p-1]+=x ans=[0]*n de...
p03073 AtCoder Beginner Contest 124 - Coloring Colorfully
N tiles are arranged in a row from left to right. The initial color of each tile is represented by a string S of length N. The i-th tile from the left is painted black if the i-th character of S is `0`, and painted white if that character is `1`. You want to repaint some of the tiles black or white, so that any two a...
```python s=input();z=sum([int(s[i])==i%2 for i in range(len(s))]);print(min(z,len(s)-z)) ```
p03215 Dwango Programming Contest V - Sum AND Subarrays
One day, Niwango-kun, an employee of Dwango Co., Ltd., found an integer sequence (a_1, ..., a_N) of length N. He is interested in properties of the sequence a. For a nonempty contiguous subsequence a_l, ..., a_r (1 \leq l \leq r \leq N) of the sequence a, its beauty is defined as a_l + ... + a_r. Niwango-kun wants to ...
```python import sys input = sys.stdin.readline n, k = map(int,input().split()) A = list(map(int,input().split())) S = [0] for i in range(n): S.append(A[i] + S[-1]) B = [] for i in range(len(S)): for j in range(i+1, len(S)): B.append(S[j] - S[i]) # B.sort() # print(B) ans = 0 for i in range(50, -1, -1)...
p03364 AtCoder Grand Contest 023 - Find Symmetries
Snuke has two boards, each divided into a grid with N rows and N columns. For both of these boards, the square at the i-th row from the top and the j-th column from the left is called Square (i,j). There is a lowercase English letter written in each square on the first board. The letter written in Square (i,j) is S_{i...
```python #023_B n = int(input()) s = [input() * 2 for _ in range(n)] ans = 0 for b in range(0, n): flg = True for i in range(n): for j in range(n): if s[i][b+j] != s[j][b+i]: flg = False break if flg: ans += 1 print(ans * n) ```
p03687 AtCoder Grand Contest 016 - Shrinking
Snuke can change a string t of length N into a string t' of length N - 1 under the following rule: * For each i (1 ≤ i ≤ N - 1), the i-th character of t' must be either the i-th or (i + 1)-th character of t. There is a string s consisting of lowercase English letters. Snuke's objective is to apply the above operati...
```python s = input().strip() l = len(s) d, a = {}, {} for i, c in enumerate(s): if c in d: d[c] = max(d[c], i - a[c]) else: d[c] = i a[c] = i + 1 for c, v in d.items(): d[c] = max(v, l - a[c]) print(min(d.values())) ```
p03840 AtCoder Grand Contest 008 - Tetromino Tiling
A tetromino is a figure formed by joining four squares edge to edge. We will refer to the following seven kinds of tetromino as I-, O-, T-, J-, L-, S- and Z-tetrominos, respectively: a60bcb8e9e8f22e3af51049eda063392.png Snuke has many tetrominos. The number of I-, O-, T-, J-, L-, S- and Z-tetrominos in his possession...
```python a = list(map(int, input().split())) if a[0] % 2 == 1 and a[3] % 2 == 1 and a[4] % 2 == 1: ans = ((a[0] // 2) * 4 + a[1] * 2 + (a[3] // 2) * 4 + (a[4] // 2) * 4) // 2 print(ans + 3) elif a[0] % 2 == 1 and a[3] % 2 == 1 and a[4] % 2 == 0 and a[4] > 0: ans = ((a[0] // 2) * 4 + a[1] * 2 + (a[3] // 2)...
p04007 AtCoder Grand Contest 004 - AND Grid
Snuke and Ciel went to a strange stationery store. Each of them got a transparent graph paper with H rows and W columns. Snuke painted some of the cells red in his paper. Here, the cells painted red were 4-connected, that is, it was possible to traverse from any red cell to any other red cell, by moving to vertically ...
```python h, w = map(int, input().split()) ans1 = [['.'] * w for _ in range(h)] ans2 = [['.'] * w for _ in range(h)] for i in range(h): ans1[i][0] = '#' ans2[i][-1] = '#' if i % 2: for j in range(w - 1): ans1[i][j] = '#' else: for j in range(1, w): ans2[i][j] = '#...
p00093 Leap Year
Create a program that outputs all leap years between the year a and year b. The leap year conditions are as follows. However, 0 <a ≤ b <3,000. If there is no leap year in the given period, output "NA". * The year is divisible by 4. * However, a year divisible by 100 is not a leap year. * However, a year divisible by ...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0093 ???????????´ """ import sys def is_leap(year): ''' ?????????????????´??? ???????????´ ???????????????True/False??§?????? ''' if year % 400 == 0: return True elif year % 100 == 0: return False...
p00225 Kobutanukitsuneko
Relative B man came to A child's house. He is 3 years old and loves singing. He is singing the song "Kobutanuki Tsuneko" (written and composed by Naozumi Yamamoto), which he learned from kindergarten. In this song, the four words "kobuta," "raccoon dog," "fox," and "cat" are arranged in order, and the last and first so...
```python from collections import* def searchnode(i,u,path): #つなげるものの個数の確認 r = 1 u[i] = 1 # print(u) for j in range(26): if path[(i,j)] and (not u[j]): r += searchnode(j,u,path) return r def chrtoint(a): return ord(a)-ord('a') while 1: n = int(input()) if n==0: ...
p00387 Party Dress
Yae joins a journey plan, in which parties will be held several times during the itinerary. She wants to participate in all of them and will carry several dresses with her. But the number of dresses she can carry with her may be smaller than that of the party opportunities. In that case, she has to wear some of her dre...
```python n,m = list(map(int,input().split())) print(max(m//n+(m%n != 0),1)) ```
p00603 Riffle Shuffle
There are a number of ways to shuffle a deck of cards. Riffle shuffle is one such example. The following is how to perform riffle shuffle. There is a deck of n cards. First, we divide it into two decks; deck A which consists of the top half of it and deck B of the bottom half. Deck A will have one more card when n is ...
```python from collections import deque import sys def suffle(deck, c): l = len(deck) if l % 2 == 0: mid = l//2 else: mid = (l-1)//2 deckA = deck[mid:] deckB = deck[:mid] deckC = [] while(len(deckA) != 0 or len(deckB) != 0): deckC.extend(deckA[:c]) deckA = deckA[c:] ...
p00740 Next Mayor
One of the oddest traditions of the town of Gameston may be that even the town mayor of the next term is chosen according to the result of a game. When the expiration of the term of the mayor approaches, at least three candidates, including the mayor of the time, play a game of pebbles, and the winner will be the next ...
```python while True: n, p = map(int, input().split()) if n == 0: break lst = [0] * n ind = 0 rest = p while True: if rest == 0: rest = lst[ind] lst[ind] = 0 else: lst[ind] += 1 rest -= 1 if lst[ind] == p: print(ind) break ind = (ind + 1) % n `...
p01142 Karakuri Doll
Karakuri Doll Karakuri doll English text is not available in this practice contest. After many years of research, Karakuri puppeteer JAG has succeeded in developing a wonderful tea-drawing doll that combines traditional and latest techniques. This tea-drawing doll is placed in a teacup with tea in the kitchen (K) in...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): W, H = map(int, readline().split()) if W == H == 0: return False S = [readline().strip() for i in range(H)] dd = ((-1, 0), (0, -1), (1, 0), (0, 1)) sx = sy = gx = gy = 0 ...
p01281 Tatami
A tatami mat, a Japanese traditional floor cover, has a rectangular form with aspect ratio 1:2. When spreading tatami mats on a floor, it is prohibited to make a cross with the border of the tatami mats, because it is believed to bring bad luck. Your task is to write a program that reports how many possible ways to sp...
```python def solve(): H, W = map(int, input().split()) if H == 0: return False if H*W % 2 == 1: print(0) return True state = [[-1]*W for i in range(H)] def dfs(k): if k == H*W: return 1 i, j = divmod(k, W) if state[i][j] != -1: ...
p01451 Roads on Towns
The Kingdom of Neva is home to two ethnic groups, the Totata and the Tutete. The biggest feature of the Totata tribe is that they eat sweet and sour pork with pineapple. However, the Tutete tribe eats vinegared pork in pineapple. These two peoples couldn't get along with each other, and the Totata and Tutete have been ...
```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 ...
p01601 Palindromic Number
Palindrome Problem Statement Find the number of palindromes closest to the integer n. Note that the non-negative integer x is the number of palindromes, which means that the character string in which x is expressed in decimal notation and the character string in which it is inverted are equal. For example, 0,7,33,10...
```python n = int(input()) s = list(range(10)) for i in range(1, 100): t = str(i) s.append(t+t[::-1]) for j in range(10): s.append(t+str(j)+t[::-1]) s = list(map(int, s)) s.sort() if n in s: print(n) else: if n < s[0]: print(s[0]) elif n > s[-1]: print(s[-1]) else: ...
p01757 Tournament
This year too, the time has come for the National Programming Championships. In the district tournament where the right to participate in the national tournament is bet, 2n teams will face each other in a one-on-one winning tournament system. Team numbers 0, .. .2n − 1 are assigned to the tournament table, and the con...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M = map(int, readline().split()) *A, = map(int, readline().split()) *B, = map(int, readline().split()) C = [] prv = 0 for i in range(M): C.append((A[i+1] - prv, 1 << B[i])) prv = A[i+1] ...
p02177 iff
problem There are $ N $ propositions, named $ 1, 2, \ cdots, N $, respectively. Also, $ M $ information about the propositions is given. The $ i $ th information is "$ a_i $$". Given in the form "b_i $", which means that $ a_i $ is $ b_i $. ("If" is a logical conditional and the transition law holds.) $ For each propo...
```python # -*- coding: utf-8 -*- import sys input = sys.stdin.readline def inpl(): return list(map(int, input().split())) N, M = inpl() G = [[] for _ in range(N)] rG = [[] for _ in range(N)] for i in range(M): a, b = inpl() G[a-1].append(b-1) rG[b-1].append(a-1) def SCC(G, rG): N = len(G) def d...
p02320 Knapsack Problem with Limitations
You have N items that you want to put them into a knapsack. Item i has value vi, weight wi and limitation mi. 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. * You can select at m...
```python def main(): import sys from collections import deque input = sys.stdin.readline N, W = map(int, input().split()) dp = [0]*(W+1) for _ in [0]*N: v, w, m = map(int, input().split()) for ofs in range(w): q = deque() for j in range(W+1): ...
p02465 Set Difference
Find the difference of two sets $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and $B = \\{b_0, b_1, ..., b_{m-1}\\}$, $A - B$. 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...
```python input() a = set(map(int, input().split())) input() b = set(map(int, input().split())) [print(s) for s in map(str, sorted(list(a-b)))] ```
1055_E. Segments on the Line
You are a given a list of integers a_1, a_2, …, a_n and s of its segments [l_j; r_j] (where 1 ≤ l_j ≤ r_j ≤ n). You need to select exactly m segments in such a way that the k-th order statistic of the multiset of a_i, where i is contained in at least one segment, is the smallest possible. If it's impossible to select ...
```python n, s, m, k = map(int, input().split()) a = list(map(int, input().split())) nt = [-1 for i in range(n+1)] for i in range(s): l, r = map(int, input().split()) l-=1 for j in range(l, r): nt[j] = max(nt[j], r) dp = [[0 for i in range(m+1)] for i in range(n+1)] sum = [0 for i in range(n+1)] def solve(mid): ...
1077_F1. Pictures with Kittens (easy version)
The only difference between easy and hard versions is the constraints. Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th p...
```python import sys S = sys.stdin.read() S = list(map(lambda x: list(map(int, x)), list(map(lambda x: x.split(), [x for x in S.split('\n') if len(x) > 1])))) n, k, x, B = S[0][0], S[0][1], S[0][2], S[1] X = [[-1 for i in range(x+1)] for i in range(n+1)] X[0][0] = 0 for i in range(1, n+1): for j in range(1, x+1):...
1146_C. Tree Diameter
There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum ...
```python # AC import sys class Main: def __init__(self): self.buff = None self.index = 0 def next(self): if self.buff is None or self.index == len(self.buff): self.buff = sys.stdin.readline().split() self.index = 0 val = self.buff[self.index] s...
1167_C. News Distribution
In some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users. Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least o...
```python import sys n, m = map(int, input().split()) par = [0] * (n + 1) cnt = [0] * (n + 1) for i in range(n + 1): par[i] = i def find(a): if par[a] == a: return a par[a] = find(par[a]) return par[a] for i in sys.stdin.readlines(): x = list(map(int, i[:-1].split())) if x[0]: ta = find(x[1]) ...
1185_F. Two Pizzas
A company of n friends wants to order exactly two pizzas. It is known that in total there are 9 pizza ingredients in nature, which are denoted by integers from 1 to 9. Each of the n friends has one or more favorite ingredients: the i-th of friends has the number of favorite ingredients equal to f_i (1 ≤ f_i ≤ 9) and y...
```python import sys import math input=sys.stdin.readline #sys.setrecursionlimit(1000000) I=lambda : list(map(int,input().split())) ma =int(10000000000000000) n,m=map(int,input().split()) a=[ma]*(515);a1=[ma]*(515);fr=[0]*(515);pos=[0]*(515) for i in range(n): b=I() x=int(0) for j in range(1,b[0]+1): ...
1204_D1. Kirk and a Binary String (easy version)
The only difference between easy and hard versions is the length of the string. You can hack this problem only if you solve both problems. Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary string t of the same length which satisfies the following ...
```python s = str(input().strip()) t = list(s[::-1]) cnt = 0 for i,v in enumerate(t): if v == '0': cnt += 1 else: if cnt: cnt -= 1 else: t[i] = '0' print("".join(t[::-1])) ```
1221_B. Knights
You are given a chess board with n rows and n columns. Initially all cells of the board are empty, and you have to put a white or a black knight into each cell of the board. A knight is a chess piece that can attack a piece in cell (x_2, y_2) from the cell (x_1, y_1) if one of the following conditions is met: * |x_...
```python n = int(input()) i = 0 s = ''.join(['W' if (i + j) % 2 == 0 else 'B' for i in range(n) for j in range(n)]) while(i<n*n): print(s[i:i+n]) i+=n ```
1266_C. Diverse Matrix
Let a be a matrix of size r × c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i ∈ [1, r], let b_i be the greatest common divisor of integers in the i-th ...
```python import sys, os, io def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]...
1287_E1. Madhouse (Easy version)
This problem is different with hard version only by constraints on total answers length It is an interactive problem Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask tw...
```python from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in rang...
1307_E. Cow and Treats
After a successful year of milk production, Farmer John is rewarding his cows with their favorite treat: tasty grass! On the field, there is a row of n units of grass, each with a sweetness s_i. Farmer John has m cows, each with a favorite sweetness f_i and a hunger value h_i. He would like to pick two disjoint subset...
```python import sys input = sys.stdin.readline from itertools import accumulate mod=10**9+7 n,m=map(int,input().split()) G=list(map(int,input().split())) CP=[[0]*(n+1) for i in range(n+1)] for i in range(m): f,e=map(int,input().split()) CP[f][e]+=1 SUMCP=[] for i in range(n+1): SUMCP.append(list(ac...
1330_E. Drazil Likes Heap
Drazil likes heap very much. So he created a problem with heap: There is a max heap with a height h implemented on the array. The details of this heap are the following: This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed f...
```python import io import os import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') fileno = sys.stdin.fileno() input = io.BytesIO( os.read(fileno, os.fstat(fileno).st_size) ).readline T = int(input()) def trim(A, h, g): N = len(A) ans = [] initial_root = 0 items_to_leave = ...
1350_E. Orac and Game of Life
Please notice the unusual memory limit of this problem. Orac likes games. Recently he came up with the new game, "Game of Life". You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white. For each iteration of the game (the initial iteration is 0), the color of...
```python import sys input = sys.stdin.readline n, m, t = map(int, input().split()) cell = [list(input().rstrip()) for _ in range(n)] cnt = [[False] * m for _ in range(n)] for i in range(n): for j in range(m): if i - 1 >= 0 and cell[i - 1][j] == cell[i][j]: cnt[i][j] = True if i + 1 < ...
1371_A. Magical Sticks
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
```python for _ in range(int(input())): n=int(input()) print(max(1,n//2 + int(n%2))) ```
1393_D. Rarity and New Dress
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 piec...
```python r,c=map(int,input().split()) rama=[] for i in range(r): rama.append(list((input()))) visit=[[1 for i in range(c)] for j in range(r)] for i in range(2,r): for j in range(1,c-1): if(rama[i][j]==rama[i-1][j-1]==rama[i-1][j+1]==rama[i-2][j]==rama[i-1][j]): visit[i][j]=min(visit[i-1][j...
1418_C. Mortal Kombat Tower
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, eith...
```python t = int(input()) for w in range(t): n = int(input()) a = list(map(int, input().split())) p = 0 if a[0] == 0 else 1 a = a[1:] n1 = 0 for x in a: if x == 0: n1 = 0 else: n1 += 1 if n1 % 3 == 0: p += 1 print(p) ``...
1436_B. Prime Square
Sasha likes investigating different math objects, for example, magic squares. But Sasha understands that magic squares have already been studied by hundreds of people, so he sees no sense of studying them further. Instead, he invented his own type of square — a prime square. A square of size n × n is called prime if ...
```python t = int(input()) for _ in range(t): n = int(input()) for j in range(n): b = [0] * n b[j] = 1 b[-j-1] = 1 if j != (n-1) and j != (n//2): print(*b) else: if n % 2 == 0: print(*b) else: if j == (n-...