name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
168_B. Wizards and Minimal Spell
Let's dive into one of the most interesting areas of magic — writing spells. Learning this exciting but challenging science is very troublesome, so now you will not learn the magic words, but only get to know the basic rules of writing spells. Each spell consists of several lines. The line, whose first non-space chara...
```python v = [] c = [] resp = "" while True: try: v.append(input()) except: break i = 0 while i < len(v): k = v[i].replace(" ","") if(k == ""): v[i] = k c.append(False) elif(k[0] == '#'): c.append(True) else: v[i] = k c.append(False) i+=1 n = len(v) i = 0 while i < n - 1: if(not c[i] and not c...
20_C. Dijkstra?
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m l...
```python from collections import defaultdict from heapq import heappush, heapify, heappop INF = 10 ** 18 class Graph: def __init__(self): self.adj_list = defaultdict(list) def add_edge(self, src, dest, cost): self.adj_list[src].append((dest, cost)) self.adj_list[dest].append((src, cost)) def dijkstra(grap...
235_E. Number Challenge
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 2000). Output Print a sing...
```python primes = [] d = {} for i in range(2, 100): if i not in d: primes.append(i) j = 2 while i * j < 100: d[i*j] = 1 j += 1 def solve(x,y,z): d = {} for p in primes: d[p] = 0 for p in primes: if p > x and p > y and p > z: ...
260_C. Balls and Boxes
Little Vasya had n boxes with balls in the room. The boxes stood in a row and were numbered with numbers from 1 to n from left to right. Once Vasya chose one of the boxes, let's assume that its number is i, took all balls out from it (it is guaranteed that this box originally had at least one ball), and began putting ...
```python n, x = map(int,input().split()) a = [int(i) for i in input().split()] j = x - 1 z = min(a) while a[j] != z: if j == 0: j = n - 1 else: j -= 1 m = a[j] k = 0 if x - 1 > j: for i in range(n): if j < i <= x - 1: a[i] -= (m + 1) k += (m + 1) else...
284_C. Cows and Sequence
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: 1. Add the integer xi to the first ai elements of the sequence. 2. Append an integer ki to the end of the sequenc...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
332_A. Down the Hatch!
Everybody knows that the Berland citizens are keen on health, especially students. Berland students are so tough that all they drink is orange juice! Yesterday one student, Vasya and his mates made some barbecue and they drank this healthy drink only. After they ran out of the first barrel of juice, they decided to pl...
```python n = int(input()) moves = input() i = n count = 0 while(i < len(moves)): m = moves[i - 1] if(m == moves[i - 2] and m == moves[i - 3] and m == moves[i - 3]): count += 1 i += n print(count) ```
355_A. Vasya and Digital Root
Vasya has recently found out what a digital root of a number is and he decided to share his knowledge with you. Let's assume that S(n) is the sum of digits of number n, for example, S(4098) = 4 + 0 + 9 + 8 = 21. Then the digital root of number n equals to: 1. dr(n) = S(n), if S(n) < 10; 2. dr(n) = dr( S(n) ), i...
```python k,d=map(int,input().split()) if(k==1 and d==0): print(0) elif(d==0): print("No solution") else: print(str(d)+('0'*(k-1))) ```
379_B. New Year Present
The New Year is coming! That's why many people today are busy preparing New Year presents. Vasily the Programmer is no exception. Vasily knows that the best present is (no, it's not a contest) money. He's put n empty wallets from left to right in a row and decided how much money to put in what wallet. Vasily decided t...
```python n = int(input()) l = [int(x) for x in input().split()] s = '' for x in l[:-1]: if x: s += 'P' for i in range(x - 1): s += 'RLP' s += 'R' if l[-1]: s += 'P' for i in range(l[-1] - 1): s += 'LRP' print(s) ```
44_C. Holidays
School holidays come in Berland. The holidays are going to continue for n days. The students of school №N are having the time of their lives and the IT teacher Marina Sergeyevna, who has spent all the summer busy checking the BSE (Berland State Examination) results, has finally taken a vacation break! Some people are i...
```python n, m = map(int, input().split()) c = [0] * n for i in range(m): a, b = map(int, input().split()) for j in range(a - 1, b): c[j] += 1 for i in range(n): if c[i] != 1: print(i + 1, c[i]) exit() print('OK') # Made By Mostafa_Khaled ```
519_C. A and B and Team Training
A and B are preparing themselves for programming contests. An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solvi...
```python a, b = map(int, input().split()) a, b = min(a, b), max(a, b) if b-a >= a: print(a) else: res = b-a a -= res res += (a//3)*2 if a%3 == 2: res += 1 print(res) ```
545_D. Queue
Little girl Susie went shopping with her mom and she wondered how to improve service quality. There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh...
```python n=int(input()) l=list(map(int,input().split())) l.sort() s=0 c=0 for i in l: if(i>=s): c=c+1 s=s+i print(c) ```
572_A. Arrays
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains t...
```python na,nb=map(int,input().split()) k,m=map(int,input().split()) a=[int(z)for z in input().split()] b=[int(z)for z in input().split()] print("YNEOS"[a[k-1]>=b[-m]::2]) # Interesting. --YKF ```
615_B. Longtail Hedgehog
This Christmas Santa gave Masha a magic picture and a pencil. The picture consists of n points connected by m segments (they might cross in any way, that doesn't matter). No two segments connect the same pair of points, and no segment connects the point to itself. Masha wants to color some segments in order paint a hed...
```python from sys import stdin,stdout,setrecursionlimit setrecursionlimit(10**5) from collections import defaultdict nmbr = lambda: int(stdin.readline()) lst = lambda: list(map(int,stdin.readline().split())) PI=float('inf') def dfs(src): vis[src]=1 for neigh in g[src]: if neigh<src: if not ...
634_D. Package Delivery
Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d. Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ...
```python destination, max_gas_tank_volume, gas_prices_number = map(int, input().split()) start_point = 0 gas_prices = {start_point:0} for i in range(gas_prices_number): coordinate, price = map(int, input().split()) gas_prices[coordinate] = price points = sorted(gas_prices.keys(), reverse = True) current_point ...
663_B. International Olympiad
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo...
```python tn=[0]*10000 ts=[0]*10000 a=1989 tn[1]=1989 ts[1]=9 for i in range(1,12): a=a+(10**i) tn[i+1]=a ts[i+1]=int(str(a)[-i-1:]) noc=int(input()) for fk in range(noc): a=input()[4:] temp=len(a) a=int(a) print((a-ts[temp])%(10**temp)+tn[temp]) ```
755_A. PolandBall and Hypothesis
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number n·m + 1 is a prime number". Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co...
```python import sys n = int(input()) for m in range(1, 1001): for j in range(2, 1001): if j < (n * m + 1) and (n * m + 1) % j == 0: print(m) sys.exit(0) ```
776_B. Sherlock and his girlfriend
Sherlock has a new girlfriend (so unlike him!). Valentine's day is coming and he wants to gift her some jewelry. He bought n pieces of jewelry. The i-th piece has price equal to i + 1, that is, the prices of the jewelry are 2, 3, 4, ... n + 1. Watson gave Sherlock a challenge to color these jewelry pieces such that t...
```python def sieve(n): mark = [True]*(n+1) p = 2 while p*p<=n: if mark[p]: for i in range(p*p,n+1,p): mark[i] = False p+=1 for i in range(2,n+1): if mark[i]: print(1,end=" ") else: print(2,end=" ") n = int(input()) if n==1 or n==2: print(1) else: print(2) sieve(n+1) ```
7_C. Line
A line on the plane is described by an equation Ax + By + C = 0. You are to find any point on this line, whose coordinates are integer numbers from - 5·1018 to 5·1018 inclusive, or to find out that such points do not exist. Input The first line contains three integers A, B and C ( - 2·109 ≤ A, B, C ≤ 2·109) — corres...
```python def gcd(x,y): if x % y == 0: return y else: return gcd(y,x%y) def bezout(x,y): if x % y == 0: return (0,1) else: t,s = bezout (y,x%y) return (s,t-(x//y)*s) a,b,c = map(int,input().split()) if a == 0: if c % b == 0: print("%d %d" % (...
846_F. Random Query
You are given an array a consisting of n positive integers. You pick two integer numbers l and r from 1 to n, inclusive (numbers are picked randomly, equiprobably and independently). If l > r, then you swap values of l and r. You have to calculate the expected value of the number of unique elements in segment of the ar...
```python n=int(input()) a=list(map(int,input().split())) lastocc=[0]*1000006 ans=[0]*n ans[0]=1 lastocc[a[0]]=1 for i in range(1,n): ans[i]=ans[i-1]+(i+1-lastocc[a[i]]) lastocc[a[i]]=i+1 print((2*sum(ans)-n)/(n*n)) ```
868_B. Race Against Time
Have you ever tried to explain to the coordinator, why it is eight hours to the contest and not a single problem has been prepared yet? Misha had. And this time he has a really strong excuse: he faced a space-time paradox! Space and time replaced each other. The entire universe turned into an enormous clock face with ...
```python ##a = list(map(int, input().split())) ##print(' '.join(map(str, res))) [h, m, s, t1, t2] = list(map(int, input().split())) if h == 12: h = 0 if t1 == 12: t1 = 0 if t2 == 12: t2 = 0 if t1 > t2: t1, t2 = t2, t1 #sa = s*360/60 #ma = m*360/60+s*360/(60*60) #ha = h*360/12+m*360/(12*60)+s*360/...
893_E. Counting Arrays
You are given two positive integer numbers x and y. An array F is called an y-factorization of x iff the following conditions are met: * There are y elements in F, and all of them are integer numbers; * <image>. You have to count the number of pairwise distinct arrays that are y-factorizations of x. Two array...
```python #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase import io from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import ...
915_B. Browser
Luba is surfing the Internet. She currently has n opened tabs in her browser, indexed from 1 to n from left to right. The mouse cursor is currently located at the pos-th tab. Luba needs to use the tabs with indices from l to r (inclusive) for her studies, and she wants to close all the tabs that don't belong to this se...
```python n,pos,l,r = [int(i) for i in input().split()] time_l = 0; if l != 1: time_l += abs(pos - l) + 1 # move to l and delete pos1 = l else: pos1 = pos if r != n: time_l += abs(r-pos1) + 1 # move to r and delete time_r = 0; if r != n: time_r += abs(pos - r) + 1 # move to l and delete pos1 = r ...
938_C. Constructing Tests
Let's denote a m-free matrix as a binary (that is, consisting of only 1's and 0's) matrix such that every square submatrix of size m × m of this matrix contains at least one zero. Consider the following problem: You are given two integers n and m. You have to construct an m-free square matrix of size n × n such that...
```python import math def div(k): res = [] for i in range(1,int(math.sqrt(k))+2): if k % i == 0: res.append(i) return res t = int(input()) for i in range(t): x = int(input()) if x == 0: print("1 1") elif x == 1: print(-1) else: ...
963_C. Cutting Rectangle
A rectangle with sides A and B is cut into rectangles with cuts parallel to its sides. For example, if p horizontal and q vertical cuts were made, (p + 1) ⋅ (q + 1) rectangles were left after the cutting. After the cutting, rectangles were of n different types. Two rectangles are different if at least one side of one r...
```python n =int(input()) w=[] h=[] c=[] cntw={} cnth={} gcdC=0 cntC=0 def insert1(a,b,c): if not a in b : b[a]=c else : b[a]=b[a]+c def gcd(a,b): if a % b == 0 : return b else : return gcd(b,a%b) for i in range(0, n): a,b,d = map(int,input().split()) w.append(a) h.append(b) c.append(d) insert1(a,cn...
990_F. Flow Control
You have to handle a very complex water distribution system. The system consists of n junctions and m pipes, i-th pipe connects junctions x_i and y_i. The only thing you can do is adjusting the pipes. You have to choose m integer numbers f_1, f_2, ..., f_m and use them as pipe settings. i-th pipe will distribute f_i u...
```python import sys from time import time t1 = time() #sys.setrecursionlimit(300000) def i_ints(): return list(map(int, sys.stdin.readline().split())) def main(): limit =10**10 n, = i_ints() s = [0] + i_ints() if sum(s): print("Impossible") return print("Possible") ...
p02614 AtCoder Beginner Contest 173 - H and V
We have a grid of H rows and W columns of squares. The color of the square at the i-th row from the top and the j-th column from the left (1 \leq i \leq H, 1 \leq j \leq W) is given to you as a character c_{i,j}: the square is white if c_{i,j} is `.`, and black if c_{i,j} is `#`. Consider doing the following operation...
```python from itertools import groupby, accumulate, product, permutations, combinations H, W, K = map(int, input().split()) S = [input() for _ in range(H)] ans = 0 for p in product([0,1],repeat=H+W): cnt = 0 for i in range(H): for j in range(W): if S[i][j]=='#' and p[i]==0 and p[H+j]==0: cnt += 1...
p02745 Panasonic Programming Contest 2020 - Three Substrings
Snuke has a string s. From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows: * Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with `?`s. For example, if s is `mississippi`, we can choose the su...
```python R=range def F(a,b):A=len(a);r=[all([len(set([a[i+j],b[j],'?']))<3for j in R(min(A-i,len(b)))])for i in R(A)];return r+[1] def Z(X): i,j,k=X;U,V,W=M[i][j],M[j][k],M[i][k];A,B,C=map(len,[S[i]for i in X]);q=A+B+C for l in R(A+1): if U[l]: for r in R(l,A+B+1): if(B<r-l or V[r-l])*W[min(A,r)]:q=min(q,ma...
p02880 AtCoder Beginner Contest 144 - 81
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. Given an integer N, determine whether N can be represented as the product of two integers between 1 and 9. If it can, print `Yes`; if it cannot, print `No`. Constraints * 1 \leq N \leq 100 * N is an int...
```python n=int(input()) li=[i*j for i in range(1,10) for j in range(1,10)] print("Yes" if n in li else "No") ```
p03014 AtCoder Beginner Contest 129 - Lamp
There is a grid with H horizontal rows and W vertical columns, and there are obstacles on some of the squares. Snuke is going to choose one of the squares not occupied by an obstacle and place a lamp on it. The lamp placed on the square will emit straight beams of light in four cardinal directions: up, down, left, and...
```python H, W = map(int, input().split()) S = [] for i in range(H): S.append(list(input())) U = [[0]*(W+1) for h in range(H+1)] L = [[0]*(W+1) for h in range(H+1)] for h in range(H): for w in range(W): if S[h][w] == '#': continue U[h+1][w+1] = U[h][w+1] + 1 L[h+1][w+1] = L[h+1][w] + 1 a...
p03155 AISing Programming Contest 2019 - Bulletin Board
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board. The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns. How many ways are there to choose where ...
```python N = int(input()) H = int(input()) W = int(input()) if H > N or W > N: print(0) else: print((N-W+1)*(N-H+1)) ```
p03298 AtCoder Grand Contest 026 - String Coloring
You are given a string S of length 2N consisting of lowercase English letters. There are 2^{2N} ways to color each character in S red or blue. Among these ways, how many satisfy the following condition? * The string obtained by reading the characters painted red from left to right is equal to the string obtained by r...
```python def f(): n=int(input()) s=list(input()) a,b=s[n-1::-1],s[n:] from collections import defaultdict ad=defaultdict(int) bd=defaultdict(int) for i in range(2**n): sa,ta,sb,tb="","","","" for j in range(n): if i%2: sa+=a[j] sb...
p03456 AtCoder Beginner Contest 086 - 1 21
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number. Constraints * 1 ≤ a,b ≤ 100 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the concatenation of a and b in this o...
```python a,b = input().split() c = int(a+b)**0.5 print("Yes" if c.is_integer() else "No") ```
p03617 AtCoder Grand Contest 019 - Ice Tea Store
You've come to your favorite store Infinitesco to buy some ice tea. The store sells ice tea in bottles of different volumes at different costs. Specifically, a 0.25-liter bottle costs Q yen, a 0.5-liter bottle costs H yen, a 1-liter bottle costs S yen, and a 2-liter bottle costs D yen. The store has an infinite supply...
```python Q, H, S, D = map(int, input().split()) N = int(input()) H = min(H, 2 * Q) S = min(S, 2 * H) D = min(D, 2 * S) print((N // 2) * D + (N % 2) * S) ```
p03775 AtCoder Beginner Contest 057 - Digits in Multiplication
You are given an integer N. For two positive integers A and B, we will define F(A,B) as the larger of the following: the number of digits in the decimal notation of A, and the number of digits in the decimal notation of B. For example, F(3,11) = 2 since 3 has one digit and 11 has two digits. Find the minimum value of F...
```python n=int(input()) ans=len(str(n)) for i in range(1,int(n**0.5)+2): if n%i==0: ans=min(ans,max(len(str(i)),len(str(n//i)))) print(ans) ```
p03944 AtCoder Beginner Contest 047 - Snuke's Coloring 2 (ABC Edit)
There is a rectangle in the xy-plane, with its lower left corner at (0, 0) and its upper right corner at (W, H). Each of its sides is parallel to the x-axis or y-axis. Initially, the whole region within the rectangle is painted white. Snuke plotted N points into the rectangle. The coordinate of the i-th (1 ≦ i ≦ N) po...
```python w,h,n=map(int,input().split()) x1=0 y1=0 for i in range(n): x,y,a=map(int,input().split()) if a==1: x1=max(x1,x) elif a==2: w=min(w,x) elif a==3: y1=max(y,y1) elif a==4: h=min(h,y) print((w-x1)*(h-y1) if w > x1 and h > y1 else 0) ```
p00036 A Figure on Surface
There is a plane like Figure 1 with 8 vertical and 8 horizontal squares. □ | □ | □ | □ | □ | □ | □ | □ --- | --- | --- | --- | --- | --- | --- | --- □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □ | □ | □ □ | □ | □ | □ | □ | □...
```python import sys readline = sys.stdin.readline write = sys.stdout.write B = [771, 16843009, 15, 66306, 1539, 131841, 774] C = "ABCDEFG" def solve(): N = 8 su = 0 for i in range(N): s = readline().strip() for j in range(N): if s[j] == '1': su |= 1 << (i*N + j) ...
p00168 Kannondou
There is Kannon-do in the mountain behind Ichiro's house. There are 30 steps from the foot to this Kannon-do, and Ichiro goes to Kannon-do almost every day. Ichiro can go up the stairs up to 3 steps with one foot. While playing, I noticed that there are so many types of stair climbing (the number of steps to skip). So...
```python import sys n=30 f=[1,1,2,4] while len(f)<=n: f.append(f[-1]+f[-2]+f[-3]) while True: n=int(input()) if n==0: sys.exit() day=f[n] if day%3650==0: print(int(day/3650)) else: print(int(day/3650)+1) ```
p00324 Bilateral Trade
Aiz, which is located in cyberspace, trades information with Wakamatsu. The two countries are developing their economies by exchanging useful data with each other. The two countries, whose national policy is philanthropy and equality, and above all, the old word of the Aizu region, "what must be done", conducts regular...
```python n = int(input()) D = [int(input()) for i in range(n)] S = {} s = ans = 0 S[0] = -1 for i in range(n): s += D[i] if s in S: ans = max(i - S[s], ans) else: S[s] = i print(ans) ```
p00496 Night Market
Taro decided to go to the summer festival held at JOI Shrine. N night shops are open along the way to JOI Shrine. Each night shop is numbered from 1 to N in order, and the fun of playing and the time it takes to play are determined by integers. The fun of playing at night shop i is Ai, and the time it takes to play at...
```python def solve(): N, T, S = map(int, input().split()) a = [tuple(map(int, input().split())) for _ in [0]*N] dp = [float("-inf")]*(T+1) dp[0] = 0 for fun, mise_time in a: for prev_time, from_fun, to_fun in zip(range(T-mise_time, -1, -1), dp[T-mise_time::-1], dp[::-1]): new_t...
p00823 Molecular Formula
Your mission in this problem is to write a computer program that manipulates molecular for- mulae in virtual chemistry. As in real chemistry, each molecular formula represents a molecule consisting of one or more atoms. However, it may not have chemical reality. The following are the definitions of atomic symbols and ...
```python # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1244 from typing import List, Dict atomic_table: Dict[str, int] = {} class NoAppearAtomicSymbol(Exception): pass class Token: s: str index = 0 def __init__(self, s: str): self.s = s @property def c(self) -> str: ...
p01087 ICPC Calculator
ICPC Calculator In mathematics, we usually specify the order of operations by using parentheses. For example, 7 × (3 + 2) always means multiplying 7 by the result of 3 + 2 and never means adding 2 to the result of 7 × 3. However, there are people who do not like parentheses. International Counter of Parentheses Counci...
```python def inp(): global n n = int(input()) return n def strinp(): l = 0 s = list(input()) for i in s: if i == '.': l += 1 else: c = i return [l,c] def calc(p): global f l = f[p][0] c = f[p][1] p += 1 if c == '+': ans = 0 for i in range(p,n): if f[i][0] == l: break elif f[i][0] ==...
p01223 Saizo
A TV program called "Saizo" is popular in a certain country. In this program, participants challenge field athletics and get a prize if they successfully capture it. Field athletics are made by arranging blocks of different heights in a row, and how to climb up and down the steps is important for capture (Fig. 1). You...
```python t = int(input()) for _ in range(t): n = int(input()) h = list(map(int, input().split())) maxv = minv = 0 for i in range(len(h)-1): maxv = max(maxv, h[i+1]-h[i]) minv = max(minv, h[i]-h[i+1]) print(maxv, minv) ```
p01539 A Holiday of Miss Brute Force
The full exploration sister is a very talented woman. Your sister can easily count the number of routes in a grid pattern if it is in the thousands. You and your exploration sister are now in a room lined with hexagonal tiles. The older sister seems to be very excited about the hexagon she sees for the first time. The ...
```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 ...
p01695 JAG-channel
JAG-channel Nathan O. Davis operates an electronic bulletin board called JAG-channel. He is currently working on adding a new feature called Thread View. Like many other electronic bulletin boards, JAG-channel is thread-based. Here, a thread refers to a group of conversations consisting of a series of posts. There ar...
```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 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split...
p01839 A-un Breathing
A-Aun's breathing Problem Statement Maeda-san and Goto-san, who will both turn 70 years old in 2060, are long-time friends and friends who fought together at the ACM-ICPC in college. The two are still excited about competitive programming, drinking tea together. When the two of us drank tea together, Mr. Maeda said...
```python n = int(input()) A_cou = 0 Un_cou = 0 ans = "YES" for i in range(n): sen = input() if sen == "A": A_cou += 1 else: Un_cou += 1 if A_cou < Un_cou: ans = "NO" break if A_cou != Un_cou: ans = "NO" print(ans) ```
p01975 Mapping
problem AOR Ika made a set $ S = \\ {a_1, ..., a_N \\} $ and a map $ f: S → S $. $ f (a_i) = b_i $. For any element $ x $ in the set $ S $, all maps $ g, h: S → S $ satisfying $ g (f (x)) = h (f (x)) $ are $ g (x). ) = Determine if h (x) $ is satisfied, and if not, configure one counterexample. Example Input 5 ...
```python # -*- coding: utf-8 -*- from collections import Counter def inpl(): return list(map(int, input().split())) N = int(input()) A = inpl() Ai = range(N) Ad = {a:i for i, a in enumerate(A)} F = inpl() C = [0]*N for f in F: C[Ad[f]] += 1 if not 0 in C: print("Yes") else: print("No") print(*list(ma...
p02261 Stable Sort
Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1. Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubbl...
```python N = int(input()) A = [] for card in input().split(): A.append([card[0], int(card[1])]) B = A[:] for i in range(N): for j in range(N-1, i, -1): if A[j][1] < A[j-1][1]: A[j-1], A[j] = A[j], A[j-1] A = " ".join([i + str(j) for i, j in A]) print(A) print("Stable") for i in range(N-1...
p02409 Official House
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room. For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth fl...
```python a= [[[0]*10 for i in range(3)] for j in range(4)] n = int(input()) for i in range(n): b,f,r,v = map(int,input().split()) a[b-1][f-1][r-1] += v for i in range(4): for j in range(3): for k in range(10): print(" " + str(a[i][j][k]),end='') print() if i != 3: ...
1015_E1. Stars Drawing (Easy Edition)
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider...
```python n, m = map(int, input().split()) arr = [input() for i in range(n)] s1 = set() s2 = set() res = list() for i in range(n): for j in range(m): if arr[i][j] == '*': s1.add((i, j)) l = 1 while True: if i - l >= 0 and i + l < n and j - l >= 0 and j + l...
1039_C. Network Safety
The Metropolis computer network consists of n servers, each has an encryption key in the range from 0 to 2^k - 1 assigned to it. Let c_i be the encryption key assigned to the i-th server. Additionally, m pairs of servers are directly connected via a data communication channel. Because of the encryption algorithms speci...
```python import sys input = sys.stdin.readline def getp(p, x): if p[x] == x: return x else: p[x] = getp(p,p[x]) return p[x] def solve(): n, m, k = map(int, input().split()) c = list(map(int, input().split())) d = dict() for i in range(m): u, v = map(int,input().split()) z = c[u-1]^c[v-1] if z in d...
1102_F. Elongated Matrix
You are given a matrix a, consisting of n rows and m columns. Each cell contains an integer in it. You can change the order of rows arbitrarily (including leaving the initial order), but you can't change the order of cells in a row. After you pick some order of rows, you traverse the whole matrix the following way: fi...
```python import sys def read(): return int(input()) def reads(): return [int(x) for x in input().split()] N,M=reads() table=[reads() for i in range(N)] A=[[0]*N for i in range(N)] B=[[0]*N for i in range(N)] for i in range(N): for j in range(N): res=10**9+7 for k in range(M): re...
1130_E. Wrong Answer
Consider the following problem: given an array a containing n integers (indexed from 0 to n-1), find max_{0 ≤ l ≤ r ≤ n-1} ∑_{l ≤ i ≤ r} (r-l+1) ⋅ a_i. In this problem, 1 ≤ n ≤ 2 000 and |a_i| ≤ 10^6. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it....
```python k = int(input()) cSum = 0 res = [-1,1] while True: if cSum + 1_000_000 < k + len(res): cSum += 1_000_000 res.append(1_000_000) else: res.append(k + len(res) - cSum) break print(len(res)) for i in res: print(i, end = ' ') ```
1151_B. Dima and a Bad XOR
Student Dima from Kremland has a matrix a of size n × m filled with non-negative integers. He wants to select exactly one integer from each row of the matrix so that the bitwise exclusive OR of the selected integers is strictly greater than zero. Help him! Formally, he wants to choose an integers sequence c_1, c_2, …...
```python n, m = map(int, input().split()) a = [[int(i) for i in input().split()] for _ in range(n)] t = a[0][0] for i in range(1, n): t ^= a[i][0] if t != 0: print("TAK") print(' '.join('1' for i in range(n))) else: for i in range(n): for j in range(1, m): if a[i][j] != a[i][0]: ...
1173_A. Nauuo and Votes
Nauuo is a girl who loves writing comments. One day, she posted a comment on Codeforces, wondering whether she would get upvotes or downvotes. It's known that there were x persons who would upvote, y persons who would downvote, and there were also another z persons who would vote, but you don't know whether they woul...
```python x, y, z = [int(x) for x in input().split()] if x == y and z == 0: print(0) elif x > y + z: print("+") elif y > x + z: print("-") else: print("?") ```
1190_D. Tokitsukaze and Strange Rectangle
There are n points on the plane, the i-th of which is at (x_i, y_i). Tokitsukaze wants to draw a strange rectangular area and pick all the points in the area. The strange area is enclosed by three lines, x = l, y = a and x = r, as its left side, its bottom side and its right side respectively, where l, r and a can be ...
```python import sys import copy input = sys.stdin.readline n=int(input()) P=[list(map(int,input().split())) for i in range(n)] SET_X=set() SET_Y=set() for x,y in P: SET_X.add(x) SET_Y.add(y) CX=sorted(SET_X) CY=sorted(SET_Y) LEN=len(CX) MAX=len(CX)-1 DICT_X={x:i for i,x in enumerate(CX)} DICT_Y={x:i for ...
1209_G1. Into Blocks (easy version)
This is an easier version of the next problem. In this version, q = 0. A sequence of integers is called nice if its elements are arranged in blocks like in [3, 3, 3, 4, 1, 1]. Formally, if two elements are equal, everything in between must also be equal. Let's define difficulty of a sequence as a minimum possible num...
```python n, q = map(int, input().split()) a = list(map(int, input().split())) d = {} def max_frequent(s, e, a): d = {} for x in a[s: e+1]: if x not in d: d[x] = 0 d[x] += 1 return e - s + 1 - max(list(d.values())) for i, x in enumerate(a): if x not...
122_A. Lucky Division
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
```python lucky_numbers = [4, 7, 44, 77, 47, 74, 444, 447, 474, 744, 777, 774, 747, 477] n = input() lucky = True for i in range(0, len(n)): if n[i] != '4' and n[i] != '7' : lucky = False break if lucky: print("YES") else: lucky = False for i in lucky_numbers: if int(n) % i == 0...
1270_G. Subset with Zero Sum
You are given n integers a_1, a_2, ..., a_n, such that for each 1≤ i ≤ n holds i-n≤ a_i≤ i-1. Find some nonempty subset of these integers, whose sum is equal to 0. It can be shown that such a subset exists under given constraints. If there are several possible subsets with zero-sum, you can find any of them. Input E...
```python import sys input = sys.stdin.readline t=int(input()) for test in range(t): n=int(input()) A=list(map(int,input().split())) ANS=[] SET=set() NOW=1 while not (NOW in SET): ANS.append(NOW) SET.add(NOW) NOW=NOW-A[NOW-1] x=ANS.index(NOW) print(len(ANS[x:...
1336_B. Xenia and Colorful Gems
Xenia is a girl being born a noble. Due to the inflexibility and harshness of her family, Xenia has to find some ways to amuse herself. <image> Recently Xenia has bought n_r red gems, n_g green gems and n_b blue gems. Each of the gems has a weight. Now, she is going to pick three gems. Xenia loves colorful things, ...
```python from bisect import bisect_left def fun(arr, val): pos = bisect_left(arr, val) if(pos == 0): return arr[0] elif(pos == len(arr)): return arr[-1] else: left = arr[pos - 1] if((val - left) < (arr[pos] - val)): return left else: ret...
1358_E. Are You Fired?
Levian works as an accountant in a large company. Levian knows how much the company has earned in each of the n consecutive months — in the i-th month the company had income equal to a_i (positive income means profit, negative income means loss, zero income means no change). Because of the general self-isolation, the f...
```python import sys input = sys.stdin.readline n = int(input()) a = list(map(int, input().split())) x = int(input()) chg = [0] for i in range(n//2): chg.append(x-a[i]) for i in range(1, n//2+1): chg[i] += chg[i-1] for i in range(1, n//2+1): chg[i] = min(chg[i], chg[i-1]) pref = sum(a) for k in range(...
1379_A. Acacius and String
Acacius is studying strings theory. Today he came with the following problem. You are given a string s of length n consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulti...
```python import sys import os from io import BytesIO, IOBase # credits of fastio to PyRival project in Github(https://github.com/cheran-senthil/PyRival) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesI...
1399_E2. Weights Division (hard version)
Easy and hard versions are actually different problems, so we advise you to read both statements carefully. You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost. A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A paren...
```python import sys,bisect from collections import deque input=sys.stdin.buffer.readline t=1 t=int(input()) for _ in range(t): n,S=map(int,input().split()) edge=[[] for i in range(n)] for i in range(n-1): u,v,w,c=map(int,input().split()) edge[u-1].append((v-1,w,float(c))) edge[v-1...
1442_B. Identify the Operations
We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the r...
```python mxn=998244353 for _ in range(int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) pre=[i-1 for i in range(n)] next=[i+1 for i in range(n)] vis=[0]*(n+1) dct=[0]*(n+1) for i in range(n): dct[a[i]]= i for num in...
1468_D. Firecrackers
Consider a long corridor which can be divided into n square cells of size 1 × 1. These cells are numbered from 1 to n from left to right. There are two people in this corridor, a hooligan and a security guard. Initially, the hooligan is in the a-th cell, the guard is in the b-th cell (a ≠ b). <image> One of the poss...
```python from sys import stdin,stdout from math import gcd,sqrt,factorial,pi,inf from collections import deque,defaultdict from bisect import bisect,bisect_left from time import time from itertools import permutations as per input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input()....
1492_C. Maximum width
Your classmate, whom you do not like because he is boring, but whom you respect for his intellect, has two strings: s of length n and t of length m. A sequence p_1, p_2, …, p_m, where 1 ≤ p_1 < p_2 < … < p_m ≤ n, is called beautiful, if s_{p_i} = t_i for all i from 1 to m. The width of a sequence is defined as max_{1 ...
```python n,m=map(int,input().split()) s=input() t=input() l=[0]*m r=[0]*m i,j=0,0 while j<m: if s[i]==t[j]: l[j]=i j+=1 i+=1 i=n-1 j=m-1 while j>0: if s[i]==t[j]: r[j]=i j-=1 i-=1 print(max(r[i+1]-l[i] for i in range(m-1))) ```
1515_D. Phoenix and Socks
To satisfy his love of matching socks, Phoenix has brought his n socks (n is even) to the sock store. Each of his socks has a color c_i and is either a left sock or right sock. Phoenix can pay one dollar to the sock store to either: * recolor a sock to any color c' (1 ≤ c' ≤ n) * turn a left sock into a right ...
```python from collections import defaultdict t = int(input()) while t!=0: t=t-1 n,l,r = map(int,input().split()) list1 = list(map(int,input().split())) d1 = defaultdict(int) d2 = defaultdict(int) for i in range(l): d1[list1[i]]+=1 for i in range(l,n): d2[list1[i]]+=1 ...
1542_C. Strange Function
Let f(i) denote the minimum positive integer x such that x is not a divisor of i. Compute ∑_{i=1}^n f(i) modulo 10^9+7. In other words, compute f(1)+f(2)+...+f(n) modulo 10^9+7. Input The first line contains a single integer t (1≤ t≤ 10^4), the number of test cases. Then t cases follow. The only line of each test c...
```python def gcd(a,b): """Compute the greatest common divisor of a and b""" while b > 0: a, b = b, a % b return a def lcm(a, b): """Compute the lowest common multiple of a and b""" return a * b // gcd(a, b) t=int(input()) for _ in range(t): n=int(input()) mod=10**9+7 l=1 ...
16_C. Monitor
Reca company makes monitors, the most popular of their models is AB999 with the screen size a × b centimeters. Because of some production peculiarities a screen parameters are integer numbers. Recently the screen sides ratio x: y became popular with users. That's why the company wants to reduce monitor AB999 size so th...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * # from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output....
190_A. Vasya and the Bus
One day Vasya heard a story: "In the city of High Bertown a bus number 62 left from the bus station. It had n grown-ups and m kids..." The latter events happen to be of no importance to us. Vasya is an accountant and he loves counting money. So he wondered what maximum and minimum sum of money these passengers could h...
```python class CodeforcesTask190ASolution: def __init__(self): self.result = '' self.passengers = [] def read_input(self): self.passengers = [int(x) for x in input().split(" ")] def process_task(self): if self.passengers[0]: if self.passengers[0] >= self.passen...
214_A. System of Equations
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
```python n,m = map(int,input().split()) a = 0 for i in range(0, 1000): for j in range(0, 1000): if i * i + j == n and j * j + i == m: a = a + 1 print(a) ```
238_A. Not Wool Sequences
A sequence of non-negative integers a1, a2, ..., an of length n is called a wool sequence if and only if there exists two integers l and r (1 ≤ l ≤ r ≤ n) such that <image>. In other words each wool sequence contains a subsequence of consecutive elements with xor equal to 0. The expression <image> means applying the o...
```python n, m = map(int, input().split()) MOD = 10 ** 9 + 9 ans = pow(2, m, MOD) - 1 step = pow(2, m, MOD) - 2 for i in range(n - 1): ans = (ans * step) % MOD step -= 1 while ans < 0: ans += MOD while ans >= MOD: ans -= MOD print(ans) ```
262_D. Maxim and Restaurant
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters. Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (...
```python n=int(input()) arr=list(map(int,input().split())) p=int(input()) dp=[[[0 for k in range(n+1)] for i in range(p+1)] for i in range(n+1)] for j in range(p+1): for k in range(n+1): dp[0][j][k]=1 for i in range(1,n+1): for j in range(p+1): for k in range(1,n+1): if j>=arr[k-1]:...
334_B. Eight Point Sets
Gerald is very particular to eight point sets. He thinks that any decent eight point set must consist of all pairwise intersections of three distinct integer vertical straight lines and three distinct integer horizontal straight lines, except for the average of these nine points. In other words, there must be three int...
```python a = [] for i in range(8): x, y = map(int, input().split()) a.append((x, y)) a.sort() if a[0][1] != a[1][1] and a[1][1] != a[2][1] and a[2][1] != a[0][1]: if a[0][0] != a[3][0] and a[3][0] != a[5][0] and a[5][0] != a[0][0]: if a[0][0] == a[1][0] == a[2][0]: if a[3][0] == a[4][0]...
357_B. Flag Day
In Berland, there is the national holiday coming — the Flag Day. In the honor of this event the president of the country decided to make a big dance party and asked your agency to organize it. He has several conditions: * overall, there must be m dances; * exactly three people must take part in each dance; * eac...
```python #! /usr/bin/env python n, m = [int(x) for x in input().split()] dancers = {} for i in range(m): dance = [int (x) for x in input().split()] for j in range(3): if dance[j] not in dancers: dancers[dance[j]] = j else: dancers[dance[(j + 1) % 3]] = (dancers[dance[j]...
380_A. Sereja and Prefixes
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current seq...
```python from bisect import bisect_left m = int(input()) t, s = [input().split() for i in range(m)], [0] * m l, n = 0, int(input()) for j, i in enumerate(t): l += 1 if i[0] == '1' else int(i[1]) * int(i[2]) t[j], s[j] = l, i[1] if i[0] == '1' else int(i[1]) F = {} def f(i): if not i in F: k = bisec...
429_A. Xor-tree
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees. The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which ...
```python n = int(input()) p = [[] for i in range(n + 1)] for i in range(n - 1): a, b = map(int, input().split()) p[a].append(b) p[b].append(a) u, v = ' ' + input()[:: 2], ' ' + input()[:: 2] s, q = [(1, 0, 0, 0)], [] while s: a, k, i, j = s.pop() if k: if i != (u[a] != v[a]): q....
450_D. Jzzhu and Cities
Jzzhu is the president of country A. There are n cities numbered from 1 to n in his country. City 1 is the capital of A. Also there are m roads connecting the cities. One can go from city ui to vi (and vise versa) using the i-th road, the length of this road is xi. Finally, there are k train routes in the country. One ...
```python import sys input = sys.stdin.readline import heapq n, m, k = map(int, input().split()) adj = [[] for _ in range(n+5)] for _ in range(m): u, v, w = map(int, input().split()) adj[u].append((v,w)) adj[v].append((u,w)) train = [-1 for _ in range(n+5)] ans = 0 dist = [int(1e15) for _ in range(n+5...
472_E. Design Tutorial: Learn from a Game
One way to create task is to learn from game. You should pick a game and focus on part of the mechanic of that game, then it might be a good task. Let's have a try. Puzzle and Dragon was a popular game in Japan, we focus on the puzzle part of that game, it is a tile-matching puzzle. <image>(Picture from Wikipedia pag...
```python """ Codeforces Contest 270 Problem E Author : chaotic_iak Language: Python 3.3.4 """ class Board(object): def __init__(self, init): self.grid = init moves = [] def current(self): return self.moves[-1] def print_moves(self): print(len(self.moves)-1) ...
497_A. Removing Columns
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table abcd edfg hijk ...
```python from math import * from collections import * from random import * from bisect import * import sys input=sys.stdin.readline def lis(): return list(map(int,input().split())) def ma(): return map(int,input().split()) def inp(): return int(input()) def fk(a,s,k): b=[] for i in range(len(a)): ...
520_C. DNA Alignment
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences. Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic...
```python import sys # sys.stdin = open('in.txt') R = lambda: map(int, input().split()) n = int(input()) s = input() ca = s.count('A') cg = s.count('G') cc = s.count('C') ct = s.count('T') mx = max(ca, cg, cc, ct) sum = (ca==mx)+(cg==mx)+(cc==mx)+(ct==mx) ans = 1 for i in range(n): ans = (ans*sum)%1000000007 ...
574_B. Bear and Three Musketeers
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are n warriors. Richelimakieu wants to choose three ...
```python n, m = map(int, input().split()) amatr = [[0] * n for i in range(n)] alist = [[] for i in range(n)] for i in range(m): a, b = map(int, input().split()) amatr[a - 1][b - 1] = 1 amatr[b - 1][a - 1] = 1 alist[a - 1].append(b - 1) alist[b - 1].append(a - 1) known = [len(alist[i]) for i in ran...
595_E. Edo and Magnets
Edo has got a collection of n refrigerator magnets! He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be posit...
```python from sys import* # def check(u, d, l, r): used = [pointsx[i][1] for i in range(l)] used += [pointsx[-1 - i][1] for i in range(r)] used += [pointsy[i][1] for i in range(u)] used += [pointsy[-1 - i][1] for i in range(d)] if len(set(used)) > k: return DOHERA dx = pointsx[-1 - r][0...
617_B. Chocolate
Bob loves everything sweet. His favorite chocolate bar consists of pieces, each piece may contain a nut. Bob wants to break the bar of chocolate into multiple pieces so that each part would contain exactly one nut and any break line goes between two adjacent pieces. You are asked to calculate the number of ways he can...
```python n = int(input()) a = list(map(int, input().split())) k = sum(a) if k == 0: print(0) exit() oneMet = False d = 1 p = 0 for i in range(n): if a[i] == 1: p += 1 if oneMet: d *= p oneMet = True p = 0 k -= 1 if k == 0: break if a[i] ==...
637_C. Promocodes with Mistakes
During a New Year special offer the "Sudislavl Bars" offered n promo codes. Each promo code consists of exactly six digits and gives right to one free cocktail at the bar "Mosquito Shelter". Of course, all the promocodes differ. As the "Mosquito Shelter" opens only at 9, and partying in Sudislavl usually begins at as ...
```python n = int(input()) codes = [] max_matches = 0 for i in range(n): codes.append(input()) for i in range(n - 1): for j in range(i + 1, n): matches = 0 for num in range(6): if codes[i][num] == codes[j][num]: matches += 1 max_matches = max(max_matches, matc...
665_C. Simple Strings
zscoder loves simple strings! A string t is called simple if every pair of adjacent characters are distinct. For example ab, aba, zscoder are simple whereas aa, add are not simple. zscoder is given a string s. He wants to change a minimum number of characters so that the string s becomes simple. Help him with this tas...
```python s=list(input()) n=len(s) def call(a,b): str="anfrozeyuibiu" for i in str: if i!=a and i!=b: return i def call1(a): str="urweifbn" for i in str: if i!=a: return i for i in range(1,n): if s[i]==s[i-1]: if i==n-1: s[i]=call1(s[i]) ...
68_A. Irrational problem
Little Petya was given this problem for homework: You are given function <image> (here <image> represents the operation of taking the remainder). His task is to count the number of integers x in range [a;b] with property f(x) = x. It is a pity that Petya forgot the order in which the remainders should be taken and wr...
```python import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from itertools import ( accumulate, combinations, combinations_with_replacement, groupby, permutations, product) fr...
711_D. Directed Roads
ZS the Coder and Chris the Baboon has explored Udayland for quite some time. They realize that it consists of n towns numbered from 1 to n. There are n directed roads in the Udayland. i-th of them goes from town i to some other town ai (ai ≠ i). ZS the Coder can flip the direction of any road in Udayland, i.e. if it ...
```python class Solution(): def __init__(self): self.n = int(input()) self.G = [ int(x) for x in input().strip().split(' ') ] self.G.insert(0,0) self.used = [0 for i in range(self.n+1)] self.dis = [0 for i in range(self.n+1)] self.circle = [] self.mod = 10**...
732_D. Exams
Vasiliy has an exam period which will continue for n days. He has to pass exams on m subjects. Subjects are numbered from 1 to m. About every day we know exam for which one of m subjects can be passed on that day. Perhaps, some day you can't pass any exam. It is not allowed to pass more than one exam on any day. On ...
```python import math global n,m,d,a d=[] a=[] def intdec(x): return int(x)-1 def check(x): global n,m,d,a vis=[0]*m seq=[] h=0; cnt=0 for i in range(x,-1,-1): if d[i]<0 or vis[d[i]]: if len(seq)<=h: pass else: cnt+=1 ...
778_A. String Game
Little Nastya has a hobby, she likes to remove some letters from word, to obtain another word. But it turns out to be pretty hard for her, because she is too young. Therefore, her brother Sergey always helps her. Sergey gives Nastya the word t and wants to get the word p out of it. Nastya removes letters in a certain ...
```python import math as mt import sys,string input=sys.stdin.readline import random from collections import deque,defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) def isSubseq(s,b,v): i=0 j=0 while(i<len(s) a...
847_K. Travel Cards
In the evening Polycarp decided to analyze his today's travel expenses on public transport. The bus system in the capital of Berland is arranged in such a way that each bus runs along the route between two stops. Each bus has no intermediate stops. So each of the buses continuously runs along the route from one stop t...
```python import heapq import sys num_trips, a, b, k, f = sys.stdin.readline().strip().split(" ") a, b, k, f = int(a), int(b), int(k), int(f) #print(a, b, k, f) trips = [] for line in sys.stdin: trips.append(line.strip().split(" ")) """ a = 5 b = 3 k = 1 f = 8 trips = [["BerBank", "University"], ["University", "...
86_A. Reflection
For each positive integer n consider the integer ψ(n) which is obtained from n by replacing every digit a in the decimal notation of n with the digit (9 - a). We say that ψ(n) is the reflection of n. For example, reflection of 192 equals 807. Note that leading zeros (if any) should be omitted. So reflection of 9 equals...
```python def ref(n): return int(''.join([str(9-int(x)) for x in str(n)])) l,r=map(int,input().split()) ans=0 ans=max(ans,ref(l)*l) ans=max(ans,ref(r)*r) cur=5 for i in range(20): if(l<=cur<=r): ans=max(ans,ref(cur)*cur) cur*=10 print(ans) ```
917_A. The Monster
As Will is stuck in the Upside Down, he can still communicate with his mom, Joyce, through the Christmas lights (he can turn them on and off with his mind). He can't directly tell his mom where he is, because the monster that took him to the Upside Down will know and relocate him. <image> Thus, he came up with a puz...
```python import sys import math input = sys.stdin.readline from functools import cmp_to_key; def pi(): return(int(input())) def pl(): return(int(input(), 16)) def ti(): return(list(map(int,input().split()))) def ts(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input()....
93_A. Frames
Throughout Igor K.'s life he has had many situations worthy of attention. We remember the story with the virus, the story of his mathematical career and of course, his famous programming achievements. However, one does not always adopt new hobbies, one can quit something as well. This time Igor K. got disappointed in ...
```python n, m, a, b = map(int, input().split()) a -= 1 x, y = a % m, b % m d = b // m - a // m if b == n and y: d += 1 u, v = x == 0, y == 0 or b == n print(1 if u and v or d <= v else 2 if x == y or u or v or d == 1 else 3) ```
965_D. Single-use Stones
A lot of frogs want to cross a river. A river is w units width, but frogs can only jump l units long, where l < w. Frogs can also jump on lengths shorter than l. but can't jump longer. Hopefully, there are some stones in the river to help them. The stones are located at integer distances from the banks. There are a_i ...
```python w, l = [int(x) for x in input().split()] a = [int(x) for x in input().split()] s = res = sum(a[:l]) for i in range(l, w - 1): s += a[i] - a[i - l] res = min(res, s) print(res) ```
992_D. Nastya and a Game
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant fo...
```python from sys import stdin import math # stdin = open('in') n, k = map(int, stdin.readline().split()) a = [int(x) for x in stdin.readline().split()] nxt = [-1]*n pref = [] f, s = -1, 0 for i in range(n): s += a[i] pref.append(s) nxt[n-1-i] = f if a[n-1-i] != 1: f = n-1-i ans = 0 for i in range(n): pos, cur...
p02625 AtCoder Beginner Contest 172 - NEQ
Count the pairs of length-N sequences consisting of integers between 1 and M (inclusive), A_1, A_2, \cdots, A_{N} and B_1, B_2, \cdots, B_{N}, that satisfy all of the following conditions: * A_i \neq B_i, for every i such that 1\leq i\leq N. * A_i \neq A_j and B_i \neq B_j, for every (i, j) such that 1\leq i < j\leq N...
```python ''' 完全順列(derangement) モンモール数(Montmort number) ''' MOD = 10**9+7 N, M = map(int, input().split()) # 片方の順列の総数を求める ans = 1 for i in range(N): ans *= M-i ans %= MOD # M枚からN枚選ぶ完全順列を計算 d = [1, M-N] for i in range(2, N+1): # 1がk番目にある # 1番目にkがある t = (i-1)*d[-2] % MOD # 1番目にkがない t += (M-...
p02756 AtCoder Beginner Contest 158 - String Formation
Takahashi has a string S consisting of lowercase English letters. Starting with this string, he will produce a new one in the procedure given as follows. The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following: * If T_i = 1: reverse the string S...
```python s = input() q = int(input()) t = 0 f = -1 x = ["",""] for i in range(q): que = input().split() if que[0] == "1": t += 1 else: x[(int(que[1])-1+t)%2] += que[2] s = x[0][::-1] + s + x[1] if t%2 == 1: s = s[::-1] print(s) ```
p02891 AtCoder Grand Contest 039 - Connection and Disconnection
Given is a string S. Let T be the concatenation of K copies of S. We can repeatedly perform the following operation: choose a character in T and replace it with a different character. Find the minimum number of operations required to satisfy the following condition: any two adjacent characters in T are different. Cons...
```python s = input() k = int(input()) m = 0 j = 0 if len(set(list(s))) == 1: print((len(s) * k) // 2) exit() for i in range(len(s)): if len(s) <= j + 1: a = m * k if s[0] == s[-1] == s[len(s) // 3]: print(a + k - 1) else: print(a) break if s[j] ==...
p03026 M-SOLUTIONS Programming Contest - Maximum Sum of Minimum
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i. We will write a positive integer on each vertex in T and calculate our score as follows: * On each edge, write the smaller of the integers writ...
```python from collections import defaultdict N = int(input()) dic = defaultdict(list) for n in range(N - 1): a, b = map(int, input().split()) dic[a].append(b) dic[b].append(a) c_list = sorted(map(int, input().split())) M = sum(c_list[:-1]) d_list = [False] * N for i in range(1, N + 1): if len(dic[i]) =...
p03167 Educational DP Contest - Grid 1
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. For each i and j (1 \leq i \leq H, 1 \leq j \leq W), Square (i, j) is described by a character a_{i, j}. If a_{i, j} is `.`, Square (i, j) is an empty square; if a...
```python H,W=map(int,input().split()) l=[[0 if i=="." else 1 for i in input()] for _ in range(H)] dp=[[0 for _ in range(W)] for _ in range(H)] dp[0][0]=1 mod=1000000007 for i in range(H): for j in range(W): if l[i][j]:continue if i>0:dp[i][j]+=(dp[i-1][j]%mod) if j>0:dp[i][j]+=(dp[i][j-1]%...