name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1245_B. Restricted RPS
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at lea...
```python from math import ceil t = int(input()) slow = {"S": "R", "R": "P", "P": "S"} for _ in range(t): n = int(input()) a, b, c = map(int, input().split()) s = input() slow2 = {"S": a, "R": b, "P": c} res = 0 ans = [''] * n for i in range(n): if slow2[s[i]] > 0: res ...
1264_F. Beautiful Fibonacci Problem
The well-known Fibonacci sequence F_0, F_1, F_2,… is defined as follows: * F_0 = 0, F_1 = 1. * For each i ≥ 2: F_i = F_{i - 1} + F_{i - 2}. Given an increasing arithmetic sequence of positive integers with n elements: (a, a + d, a + 2⋅ d,…, a + (n - 1)⋅ d). You need to find another increasing arithmetic se...
```python o,m,k=map(int,input().split()) print(368131125*m%10**9*12*10**9+1,368131125*k%10**9*12*10**9) ```
1286_C1. 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...
132_A. Turing Tape
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one ...
```python ans=0 for i in input(): t=bin(ord(i))[2::][::-1] k=int(t+"0"*(8-len(t)),2) print((ans-k)%256) ans=k ```
136_D. Rectangle and Square
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the ...
```python import itertools import math import os import sys eps = 1e-8 coord = [[]] + [list(map(int, input().split())) for _ in range(8)] idx = list(range(1, 9)) def perpendicular(v1, v2): return sum([x * y for (x, y) in zip(v1, v2)]) < eps def all_perpendicular(vs): return all([perpendicular(vs[i], vs[(i+...
1392_D. Omkar and Bed Wars
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 ≤ j ≤ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the...
```python def find_cost_of_reordering(directions): assert len(directions) >= 3 directions_n = len(directions) get_direction = lambda index: directions[index % directions_n] if len(set(directions)) == 1: return 1 + (directions_n - 1) // 3 i = 0 while get_direction(i) == get...
1433_E. Two Round Dances
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round da...
```python def fact(n): ft=1 while n>0: ft=ft*n n=n-1 return ft n=int(input()) q=2*fact(n)//(n*n) print(q) ```
1458_D. Flip and Reverse
You are given a string s of 0's and 1's. You are allowed to perform the following operation: * choose a non-empty contiguous substring of s that contains an equal number of 0's and 1's; * flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; * reverse the substring. For exa...
```python # test Arpa code import io,os, sys input = sys.stdin.readline print = sys.stdout.write t = int(input()) START = 500001 seen = [0] * (2 * START) while t > 0: t -= 1 s = input().strip("\n") cur = START for c in s: if c == '0': seen[cur] += 1 cur -= 1 els...
1481_D. AB Graph
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. <image> You ...
```python import sys input=sys.stdin.readline for t in range(int(input())): N,M=map(int,input().split()) S=[input() for i in range(N)] F=0 for i in range(N): for j in range(N): if i!=j and S[i][j]==S[j][i]: F=1 P=[i+1] for k in range(M): if k&1: P.append...
1534_F1. Falling Sand (Easy Version)
This is the easy version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved. Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows a...
```python import sys input = lambda: sys.stdin.readline().rstrip() def scc(E): n = len(E) iE = [[] for _ in range(n)] for i, e in enumerate(E): for v in e: iE[v].append(i) T = [] done = [0] * n # 0 -> 1 -> 2 ct = 0 for i0 in range(n): if done[i0]: continue ...
181_D. Word Cut
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation...
```python MOD = int(1e9) + 7 if __name__ == "__main__": a = input() b = input() k = int(input()) if(len(a) != len(b)): print(0) exit() a = a + a x = 0 y = 0 for i in range(len(a) // 2): flag = 1 for j in range(len(b)): if(a[j + i] != b[j]): ...
205_A. Little Elephant and Rozdil
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum ti...
```python n = int(input()) string = input() times = list(map(int, string.split())) a = min(times) if times.count(a) == 1: print(times.index(a) + 1) else: print("Still Rozdil") ```
278_D. Set of Points
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line. Input The single line contains two integers n and m...
```python def f(x): return int(x * x + 1e7) def g(x): return -f(x) n, m = map(int, input().split()) if(m == 3): if(n == 3): print('0 0') print('1 0') print('0 1') elif(n == 4): print('0 0') print('1 1') print('10000 0') print('0 10000') ...
300_C. Beautiful Numbers
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number. For example, let's say that Vitaly's favourite digits are ...
```python MOD=10**9+7 a,b,n=list(map(int,input().strip().split(' '))) #there are i a's. n-i b's def check(a,b,x): temp=x%10 if temp!=a and temp!=b: return 0 while(x>0): temp=x%10 if temp!=a and temp!=b: return 0 x=x//10 return 1 fact=[1] infact=[1] temp=...
327_A. Flipping Game
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≤ i ≤ j ≤ n) and flips all values ak for which their positions are in range [i, j] (that is i ≤ k ≤ j)...
```python n=int(input()) a = list(map(int, input().split())) mas=[0]*n if a[0]==0: mas[0]=1 else: mas[0]=-1 m=mas[0] for i in range(1,n): mas[i]=max( mas[i-1] + (-1)**a[i], (-1)**a[i]) m=max(m,mas[i]) print(a.count(1)+m) ```
349_B. Color the Fence
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d re...
```python v = int(input()) a = [*map(int, input().split())] d = {} for i in range(9): d[a[i]] = i + 1 ans = [*str(d[min(a)]) * (v // min(a))] t = min(a) * len(ans) for i in range(len(ans)): t -= a[int(ans[i]) - 1] for j in range(8, -1, -1): if t + a[j] <= v: ans[i] = str(j + 1) t += a[j] break print('...
372_C. Watching Fireworks is Fun
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1. In the festival m fireworks will be launched. The i-th (1 ≤ i ≤ m) launching is on time ti at section ai. If you are at s...
```python from collections import deque n,m,v=map(int,input().split()) x,t,b,bt,dp,mi,mi2,mi3,dpmin,dp2=[0]*300,[0]*300,0,0,[[0]*2for i in range(150001)],0,100000000000000,10000000000000,0,[0]*150001 d=deque() for i in range(m): x[i],b,t[i]=map(int,input().split()) bt+=b for i2 in range(m-1): if i2==0: ...
417_A. Elimination
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Eac...
```python import math c,d = map(int,input().split()) n,m = map(int,input().split()) k=int(input()) if k>=n*m: print('0') else: left=n*m-k t=c*(math.ceil(left/n)) j= c*(left//n) + (left%n)*d l=d*(left) print(min(t,j,l)) ```
443_D. Andrey and Problem
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends — the probability that this friend will come up with a problem if Andrey asks him. Help Andrey choose...
```python n = input() ans = tmp = 0.0 prod = 1.0 for p in reversed(sorted(map(float, input().split()))): tmp = tmp * (1.0 - p) + prod * p prod *= 1.0 - p ans = max(ans, tmp) print('%0.9f' % ans) ```
489_D. Unbearable Controversy of Being
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of...
```python import sys from collections import defaultdict, Counter # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') input = sys.stdin.readline n, m = map(int, input().split()) g = defaultdict(list) for _ in range(m): a, b = map(int, input().split()) g[a-1].append(b-1) # print(g) rh...
513_B2. Permutations
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn...
```python n, m = map(int, input().split()) s = 1 c = n - 1 arr = [0] * n i = 0 while i <= c: r = 0 j = s while j <= n and r < m: if j < n: r += 2 ** (n - j - 1) j += 1 #print(s, j, r, m) if j > s and j != n + 1: r -= 2 ** (n - j) m -= r j -= 1 arr[i] =...
538_D. Weird Chess
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous. Igor's chessboard is a square of size n × n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of piece...
```python import sys fin = sys.stdin n = int(fin.readline()) ma = [[None]] * n for i in range(0, n): aux = fin.readline() aux = aux[:-1] ma[i] = list(aux) r = [] for i in range(0, 2 * n - 1): r.append(None) r[i] = [] for j in range(0, 2 * n - 1): r[i].append('x') for i in range(0, n): ...
60_B. Serial Time!
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k × n × m, that is, it has k layers (the first layer is the upper one...
```python from collections import deque class CodeforcesTask60BSolution: def __init__(self): self.result = '' self.k_n_m = [] self.plate = [] self.tape = [] def read_input(self): self.k_n_m = [int(x) for x in input().split(" ")] for x in range(self.k_n_m[0]): ...
630_G. Challenge Pennants
Because of budget cuts one IT company established new non-financial reward system instead of bonuses. Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting...
```python from functools import reduce def c(n, m): return 0 if n>m or n<0 else reduce(lambda a,b: a*b, range(m-n+1, m+1), 1)//reduce(lambda a,b: a*b, range(1,n+1), 1) n = int(input()) print(sum([c(i, n)*c(i-1, 2) for i in range(1, 4)])*sum([c(i, n)*c(i-1, 4) for i in range(1, 6)])) ```
658_D. Bear and Polynomials
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally: Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) ...
```python def convert_to_binary(coef): res = [] n = len(coef) carry = 0 i = 0 while i < n + 1000: if i >= n and not carry: break cur = carry if i < n: cur += coef[i] mod = cur % 2 div = cur // 2 # print(cur, div, mod) r...
681_A. A Good Contest
Codeforces user' handle color depends on his rating — it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of hi...
```python #!/usr/bin/env python3 if __name__ == '__main__': n = int(input()) for _ in range(n): handle, prev, curr = input().split() prev = int(prev) curr = int(curr) if prev < 2400: continue if curr > prev: print('YES') break el...
747_E. Comments
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment ex...
```python from queue import Queue def parse(s): A = s.split(',') n = len(A)//2 B = [(A[2*i], int(A[2*i+1])) for i in range(n)] stack = [] E = {i:[] for i in range(n+1)} comment = {} depth = {i:0 for i in range(n+1)} for i, b in enumerate(reversed(B)): comment[i+1] = b[0] ...
770_B. Maximize Sum of Digits
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. Input The first line contains the positive integer x (1 ≤ ...
```python num = list(input()) orgnum = num.copy() if len(num) == 1: print(num[0]) elif num[1:] != list("9"*(len(num)-1)): if num[1:] == list("8"+"9"*(len(num)-2)): print(int("".join(num))) elif "9" in num: finished = False did = False for i in range(len(num)): if ...
794_E. Choosing Carrot
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are n carrots arranged in a...
```python def evens(A): n = len(A) l = n//2-1; r = n//2 if len(A)%2 == 1: l+= 1 ans = [max(A[l], A[r])] while r < n-1: l-= 1; r+= 1 ans.append(max(ans[-1], A[l], A[r])) return ans def interleave(A, B): q = [] for i in range(len(B)): q+= [A[i], B[i]] if len(A) != len(...
887_D. Ratings and Reality Shows
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Mor...
```python from sys import stdin from collections import deque def main(): n, a, b, c, d, st, l = map(int, input().split()) q = deque() po = q.popleft pu = q.append mq = deque() mpop = mq.pop mpo = mq.popleft mpu = mq.append sb = [0] * (n + 1) mst = st pu((0, 0, mst, st)) ...
90_D. Widget Library
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on t...
```python import sys from array import array # noqa: F401 import re def input(): return sys.stdin.buffer.readline().decode('utf-8') class Widget(object): def __init__(self, x, y): self.x = x self.y = y class Box(object): def __init__(self): self.children = [] self.bord...
932_A. Palindromic Supersequence
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c...
```python # -*- coding: utf-8 -*- """ Created on Thu Feb 15 21:01:05 2018 @author: DNARNAprotein """ """ CODEFORCES http://codeforces.com/contest/932/problem/A """ def pikachu(a,c,n): #c is original string prefixes=[a[0:i+1] for i in range(n+1)] suffixes=[a[i:n+1] for i in range(n+1)] maxi=0 for i in...
959_B. Mahmoud and Ehab and the message
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning. Mahmoud knows that the i-th word can be sent with cost ai. For each word in his messa...
```python a = list(map(int,input().split(" "))) n,k,m = a[0],a[1],a[2] words = list(input().split(" ")) cost = list(map(int,input().split(" "))) dic = {} for i in range(k): tmp = list(map(int,input().split(" "))) if tmp[0] == 1: dic[words[tmp[1]-1]] = cost[tmp[1]-1] else: mincost = min(cost[...
p02580 AtCoder Beginner Contest 176 - Bomber
We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right). Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where th...
```python H, W, M = map(int, input().split()) bombs_h = [0] * H bombs_w = [0] * W B = [] for _ in range(M): h, w = map(lambda x: int(x)-1, input().split()) B.append((h, w)) bombs_h[h] += 1 bombs_w[w] += 1 max_h = max(bombs_h) max_w = max(bombs_w) hs = [i for i, x in enumerate(bombs_h) if x == max_h] ws...
p02711 AtCoder Beginner Contest 162 - Lucky 7
Given is a three-digit integer N. Does N contain the digit 7? If so, print `Yes`; otherwise, print `No`. Constraints * 100 \leq N \leq 999 Input Input is given from Standard Input in the following format: N Output If N contains the digit 7, print `Yes`; otherwise, print `No`. Examples Input 117 Output Y...
```python print(['No', 'Yes']['7' in input()]) ```
p02840 AtCoder Beginner Contest 147 - Sum Difference
We have an integer sequence A of length N, where A_1 = X, A_{i+1} = A_i + D (1 \leq i < N ) holds. Takahashi will take some (possibly all or none) of the elements in this sequence, and Aoki will take all of the others. Let S and T be the sum of the numbers taken by Takahashi and Aoki, respectively. How many possible ...
```python N,X,D=map(int,input().split()) from collections import defaultdict A=defaultdict(list) A[0].append([0,0]) MIN=0 MAX=0 if D==0: w=1 else: w=D for i in range(N): MIN+=X+D*i MAX+=X+D*(N-1-i) A[MIN%w].append(sorted([MIN,MAX])) D=abs(D) if D==0: if X==0: D=1 else: ...
p02977 AtCoder Grand Contest 035 - Skolem XOR Tree
You are given an integer N. Determine if there exists a tree with 2N vertices numbered 1 to 2N satisfying the following condition, and show one such tree if the answer is yes. * Assume that, for each integer i between 1 and N (inclusive), Vertex i and N+i have the weight i. Then, for each integer i between 1 and N, th...
```python """ https://atcoder.jp/contests/agc035/tasks/agc035_c 全ての対の頂点に関して、パス上の重みのxorが自分に等しい 1から順に求めていくことを考える A,Bの関係を考える 木なので、片方のパス上にあればいい→片方にのみ含ませることも、両方に含ませることも可能 1をいい感じに使って構築できないか? 101-100-1-101-100 みたいに、1の位だけ違う数字をまとめて処理すればいい感じになる もう一つの1は、どっかの葉につけておけばおk これで、Nが奇数かつ1でない場合は全て構築可能!! 偶数の時は? 2,4みたいな場合は自明にダメ 6は? 00...
p03260 AtCoder Beginner Contest 109 - ABC333
You are given integers A and B, each between 1 and 3 (inclusive). Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number. Constraints * All values in input are integers. * 1 \leq A, B \leq 3 Input Input is given from Standard Input in the following format: A...
```python print("Yes" if all(int(i) % 2 != 0 for i in input().split()) else "No") ```
p03416 AtCoder Beginner Contest 090 - Palindromic Numbers
Find the number of palindromic numbers among the integers between A and B (inclusive). Here, a palindromic number is a positive integer whose string representation in base 10 (without leading zeros) reads the same forward and backward. Constraints * 10000 \leq A \leq B \leq 99999 * All input values are integers. Inp...
```python a,b=map(int,input().split()) ans=0 for i in range(a,b+1): ir=str(i) if ir == ir[::-1]: ans+=1 print(ans) ```
p03576 AtCoder Beginner Contest 075 - Axis-Parallel Rectangle
We have N points in a two-dimensional plane. The coordinates of the i-th point (1 \leq i \leq N) are (x_i,y_i). Let us consider a rectangle whose sides are parallel to the coordinate axes that contains K or more of the N points in its interior. Here, points on the sides of the rectangle are considered to be in the inte...
```python N, K = map(int, input().split()) X, Y = [], [] D = [] for i in range(N): x, y = map(int, input().split()) X.append(x) Y.append(y) D.append((x, y)) X = sorted(X) Y = sorted(Y) num = float("inf") for i in range(N - 1): for j in range(i + 1, N): for k in range(N - 1): for...
p03733 AtCoder Regular Contest 073 - Sentou
In a public bath, there is a shower which emits water for T seconds when the switch is pushed. If the switch is pushed when the shower is already emitting water, from that moment it will be emitting water for T seconds. Note that it does not mean that the shower emits water for T additional seconds. N people will pus...
```python from operator import sub n, t = map(int, input().split()) res = t temp = list(map(int, input().split())) for v in map(sub, temp[1:], temp): res += min(t, v) print(res) ```
p03895 CODE FESTIVAL 2016 Relay (Parallel) - Early Bird
Takahashi recorded his daily life for the last few days as a integer sequence of length 2N, as follows: * a_1, b_1, a_2, b_2, ... , a_N, b_N This means that, starting from a certain time T, he was: * sleeping for exactly a_1 seconds * then awake for exactly b_1 seconds * then sleeping for exactly a_2 seconds * : *...
```python n = int(input()) x,num = [],0 for i in range(n): a,b = (int(j) for j in input().split()) x.append((num+a)%86400) num = (num+a+b)%86400 x,ans = sorted(x),0 from bisect import bisect for i in range(n): ans = max(ans,bisect(x,x[i]+10800)-i) if x[i]<=10800: x.append(x[i]+86400) print(ans) ```
p00001 List of Top 3 Hills
There is a data which provides heights (in meter) of mountains. The data is only for ten mountains. Write a program which prints heights of the top three mountains in descending order. Constraints 0 ≤ height of mountain (integer) ≤ 10,000 Input Height of mountain 1 Height of mountain 2 Height of mountain 3 . . He...
```python h = [int(input()) for i in range(10)] h.sort(reverse = True) for i in range(3): print(h[i]) ```
p00133 Rotation of a Pattern
Create a program that rotates the pattern of 8 characters x 8 lines clockwise by 90 degrees, 180 degrees, and 270 degrees and outputs it. Input A pattern consisting of 8 characters x 8 lines is given. Characters consist of alphanumeric characters, half-width pound'#', and asterisk'*'. Output Output the rotated pa...
```python # AOJ 0133 Rotation of a Pattern # Python3 2018.6.19 bal4u a = [[[0 for c in range(8)] for r in range(8)] for k in range(4)] title = ["0", "90", "180", "270"] for r in range(8): a[0][r] = list(input()) for k in range(1, 4): print(title[k]) for r in range(8): for c in range(8): a[k][c][7-r] = a[k-1][...
p00266 Izua Dictionary
You have obtained the Izua Japanese dictionary, which is the official language of Izua, and the Izua alphabet (list of letters). There are N types of letters in the Izua alphabet. The order of the words that appear in the Izua Japanese dictionary is in the alphabetical order of Izua. Looking at the dictionary, I found...
```python def solve(): from sys import stdin m = 1000000007 f_i = stdin while True: N = int(f_i.readline()) if N == 0: break w = list(range(N)) R = int(f_i.readline()) for i in range(R): s, t = map(int, f_i.readline().split())...
p00453 Pyon-Pyon River Crossing
problem In one river, there is a slightly dangerous game of jumping from one shore to the other on a stone. <image> Now, as shown in Figure 4-1 we consider the stone to be above the squares. The number of rows is n. In Figure 4-1 we have n = 5. In this game, you start with one shore and make a normal jump or a on...
```python from heapq import heappop, heappush while True: n, m = map(int, input().split()) if not n: break num_stones = 0 row_stones = [None] * n edges = [None] * n visited = [None] * n for row in range(n): (num, *stones) = map(int, input().split()) row_stones[row] ...
p00644 Winter Bells
The best night ever in the world has come! It's 8 p.m. of December 24th, yes, the night of Cristmas Eve. Santa Clause comes to a silent city with ringing bells. Overtaking north wind, from a sleigh a reindeer pulls she shoot presents to soxes hanged near windows for children. The sleigh she is on departs from a big ch...
```python from heapq import heappush, heappop INF = 10 ** 20 while True: n, m, p = map(int, input().split()) if n == 0: break edges = [[] for _ in range(n)] for _ in range(m): x, y, w = map(int, input().split()) edges[x].append((y, w)) edges[y].append((x, w)) que = [] heappush(que, (0, 0)) ...
p00788 Rational Irrationals
Rational numbers are numbers represented by ratios of two integers. For a prime number p, one of the elementary theorems in the number theory is that there is no rational number equal to √p. Such numbers are called irrational numbers. It is also known that there are rational numbers arbitrarily close to √p Now, given ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def stern_brocot(p, n): la = 0; lb = 1 ra = 1; rb = 0 lu = ru = 1 lx = 0; ly = 1 rx = 1; ry = 0 while lu or ru: ma = la + ra; mb = lb + rb if p * mb**2 < ma**2: ra = ma; rb = mb i...
p01322 Lottery Checker
You have successfully completed your studies and are preparing to move from near Komaba to near Hongo. As I was organizing my house, I found a lot of lottery tickets I bought last year. After confirming the exchange deadline, I have to cash in by tomorrow, but it is troublesome to go to the lottery counter for a small ...
```python import re while 1: n,m=map(int,input().split()) if n==0:break p=[];s=0 for _ in [0]*n: n,M=input().replace('*','[0-9]').split() p.append([re.compile(n),int(M)]) for _ in [0]*m: l=input() for n,M in p: if n.search(l): s+=M;break ...
p01490 HullMarathon
Example Input 4 5 8 58 85 Output 2970.000000000
```python from itertools import permutations from math import acos, sin, cos, pi import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) R = [int(readline()) for i in range(N)] R.sort(reverse=1) ans = 0 for l in range(3, N+1): for rs in permutation...
p01803 Airport Codes
Airport Codes Airport code In the Kingdom of JAG, airport codes are assigned to each domestic airport for identification. Airport codes are assigned according to the following rules based on the name of the airport in lowercase English alphabet: 1. Extract the first letter of the name and the letter immediately aft...
```python while 1: n=int(input()) if not n:break l=[] m=0 for _ in range(n): s=input() a=s[0] for i,t in enumerate(s[:-1]): if any(t==c for c in'aiueo'): a+=s[i+1] m=max(m,len(a)) l.append(a) for k in range(m+1): if len(...
p01938 A-Z-
A: A-Z- problem There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's...
```python S = input() cur = 'A' ans = 0 for i in range(len(S)): if(S[i] == cur): ans += 1 else: if(cur > S[i]): ans += 1 cur = S[i] print(ans) ```
p02371 Diameter of a Tree
Diameter of a Tree Given a tree T with non-negative weight, find the diameter of the tree. The diameter of a tree is the maximum distance between two nodes in a tree. Constraints * 1 ≤ n ≤ 100,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which repre...
```python import sys readline = sys.stdin.readline from collections import deque from math import isinf INF = float("inf") sys.setrecursionlimit(200000) n = int(readline()) G = [[] for _ in range(n)] D = [INF] * n for _ in [0] * (n - 1): s, t, w = map(int, readline().split()) G[s].append([t, w]) G[t].append...
1011_E. Border
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are...
```python from functools import reduce from math import gcd n, k = map(int, input().split()) A = list(map(int, input().split())) G = gcd(k, reduce(lambda x,y:gcd(x,y),A)) print(k // G) print(*list(range(0, k, G))) ```
1036_F. Relatively Prime Powers
Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} ⋅ 3^{k_2} ⋅ 5^{k_3} ⋅ ... Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 ⋅ 3, 72 = 2^3 ⋅ 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2...
```python from math import sqrt, log2 from sys import stdin from bisect import bisect import time def all_primes(n): res = [] for i in range(1, n+1): prime = True for j in range(2, min(int(sqrt(i))+2, i)): if i % j == 0: prime = False break if...
1059_E. Split the Tree
You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belo...
```python from collections import defaultdict import sys def rec(n, l, s): # dp[i] is a doctionary, where key is the chain length # and value is the weight at node i dp = [{} for _ in range(n)] ans = 0 for cur in range(n - 1, -1, -1): child_of_cur = children.get(cur, None) if not c...
1081_A. Definite Game
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operatio...
```python v = int(input()) print(2 if v == 2 else 1) ```
1100_A. Roman and Browser
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them. He decided to accomplish this...
```python from collections import Counter import math n,m=map(int,input().split()) l=list(map(int,input().split())) c=Counter(l) a1=c[1] a2=c[-1] i=0 s=[] a=0 b=0 while(i<m): for j in range(i,n,m): if l[j]>0: a+=1 else: b+=1 s+=[abs(a1-a2+b-a)] a=0 b=0 i+=1 print(max(s)) ```
1121_E. Once in a casino
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow. A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this o...
```python def main(): n = int(input()) a = list(map(int, (x for x in input()))) b = list(map(int, (x for x in input()))) x = [0] * (n - 1) x[0] = b[0] - a[0] for i in range(1, n - 1): x[i] = b[i] - a[i] - x[i - 1] if a[n - 1] + x[n - 2] != b[n - 1]: print(-1) return ...
116_D. Lawnmower
You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either gras...
```python n, m = map(int, input().split()) t = [(p.find('W'), p.rfind('W')) for p in [input() for i in range(n)]] c, s, k = 0, n - 1, True while s > 0 and t[s][0] == -1: s -= 1 for a, b in t[: s + 1]: if a != -1: if k: s += abs(a - c) + b - a c = b else: ...
1188_C. Array Beauty
Let's call beauty of an array b_1, b_2, …, b_n (n > 1) — min_{1 ≤ i < j ≤ n} |b_i - b_j|. You're given an array a_1, a_2, … a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353. A sequence a is a subsequenc...
```python from collections import defaultdict import sys input = sys.stdin.readline ''' for CASES in range(int(input())): n, m = map(int, input().split()) n = int(input()) A = list(map(int, input().split())) S = input().strip() sys.stdout.write(" ".join(map(str,ans))+"\n") ''' inf = 100000000000000000 # 1e17 mod = 998...
1207_D. Number Of Permutations
You are given a sequence of n pairs of integers: (a_1, b_1), (a_2, b_2), ... , (a_n, b_n). This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences: ...
```python from collections import defaultdict import math MOD = 998244353 def facmod(n): fac = 1 for i in range(2, n + 1): fac *= i fac %= MOD return fac def main(): n = int(input()) s = [tuple(int(s) for s in input().split()) for _ in range(n)] count = defaultdict(int...
1225_E. Rock Is Push
You are at the top left cell (1, 1) of an n × m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y). Some cells of the labyrinth contain r...
```python def getSum(dp, pos, s, e, type_): if e < s: return 0 if type_=='D': if e==m-1: return dp[pos][s] return dp[pos][s]-dp[pos][e+1] else: if e==n-1: return dp[s][pos] return dp[s][pos]-dp[e+1][pos] mod = 10**9+7 n, m = map(i...
124_A. The number of positions
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
```python x,y,z=map(int,input().split()) if y+z>=x: print(x-y) else: print(z+1) ```
1333_D. Challenges in school №41
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right. Children can do the following: in one second several pairs of neighboring...
```python #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): n , k = [int(n) for n in inp...
1354_A. Alarm Clock
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
```python for i in range(int(input())): a,b,c,d=map(int,input().split()) e=a-b if e<1: print(b) continue else: if c-d<1: print(-1) continue else: f=int(e//(c-d)) if b+f*(c-d)>=a: print(b+f*c) else...
1373_F. Network Coverage
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a co...
```python from bisect import bisect_left as bl from bisect import bisect_right as br from heapq import heappush,heappop import math from collections import * from functools import reduce,cmp_to_key,lru_cache import io, os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # import sys # input = sys.stdin.readl...
1420_B. Rock and Lever
"You must lift the dam. With a lever. I will give it to you. You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give Danik the lever. But to get a stone...
```python def nCr(n, k): if k > n: return 0 if(k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) for _ in range(int(input())): N = int(input()) a = list(map(int, input().split())) d = {} for i in range(len(a)): a[i] = bin(a[...
1439_A1. Binary Table (Easy Version)
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n × m. This table consists of symbols 0 and 1. You can make such operat...
```python import sys input=sys.stdin.readline def change(x1,x2,x3,y1,y2,y3,ll): ll[x1][y1]=1-ll[x1][y1] ll[x2][y2]=1-ll[x2][y2] #print(x3,y3,ll) ll[x3][y3]=1-ll[x3][y3] t=int(input()) while t: n,m=map(int,input().split()) ll=[] for i in range(n): l=list(map(int,input().strip())...
1490_A. Dense Array
Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any i (1 ≤ i ≤ n-1), this condition must be satisfied: $$$(max(a[i], a[i+1]))/(min(a[i], a[i+1])) ≤ 2$$$ For example, the arrays [1, 2, 3, 4, 3], [1, 1, 1] and [5, 10] are dense....
```python for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) s=0 for i in range(n-1): a=max(l[i],l[i+1]) b=min(l[i],l[i+1]) while a>(2*b): s+=1 b=b*2 print(s) ```
1512_D. Corrupted Array
You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm: * some array a_1, a_2, …, a_n was guessed; * array a was written to array b, i.e. b_i = a_i (1 ≤ i ≤ n); * The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1...
```python for _ in range(int(input())): n = int(input()) a = sorted(list(map(int,input().split()))) ans = [0]*(n+2) ans[0] = a[0] for i in range(1,n+2): ans[i] = ans[i-1] + a[i] #print(ans) j = -1 for i in range(n+2): if n + 1 != i: if a[n+1] == ans[n] - a[i]:...
166_E. Tetrahedron
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. T...
```python def fast_exp_pow(num, pw, mod): num %= mod if pw == 1: return num evener = 1 if pw % 2 == 1: evener = num return (evener * (fast_exp_pow(num, pw // 2, mod) % mod) ** 2) % mod mod = 1000000007 n = int(input()) if n == 1: print(0) quit() x = ((fast_exp_pow(3, n - 1, mod) + (-1) ** (n & 1) + mod) * ...
208_D. Prizes, Prizes, more Prizes
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it — the number of points that the participant adds to his score as he buys the bar. After ...
```python import bisect n = int(input()) a = [int(x) for x in input().split()] p = [int(x) for x in input().split()] b = [0, 0, 0, 0, 0] s = 0 for i in a: s += i k = bisect.bisect_right(p, s) while k != 0: if (k == 5) or (p[k] > s): k -= 1 b[k] += s // p[k] s %= p[k] ...
25_A. IQ test
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di...
```python n=int(input()) q=list(map(int,input().split())) eve,eve_indx,neg,neg_indx=0,0,0,0 for i in range(n): x=q[i]%2 if x==0: eve +=1 eve_indx=i else: neg +=1 neg_indx=i if eve==1: print(eve_indx+1) else: print(neg_indx+1) ```
283_A. 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 from sys import stdin input = stdin.readline n = int(input()) arr, cnt, curr_len, curr_sum = [0] * (n+1), [0] * (n+1), 1, 0 for _ in range(n): s = input() if s[0] == '1': _, x, y = map(int, s.split()) curr_sum += x*y cnt[x-1] += y elif s[0] == '2': _, x = map(int, s...
305_E. Playing with String
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. <image> An example of the initial situation at s = "abacaba" A player's ...
```python U = input() memo = {} DP = [0]*(len(U)+1) DP[0] = 0 for j in range(1, len(U) + 1): s = set() for i in range(j): s.add(DP[max(0, i - 1)] ^ DP[max(0, j - i - 2)]) mex = 0 while mex in s: mex += 1 DP[j] = mex memo2 = {} def Grundy(S): """ Basically we transform ...
331_C2. The Great Julya Calendar
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open ...
```python c = '0123456789' F = {c[a] + c[b]: (c[10 - a + b], 1) if a > b else (c[10 - a], 2) for a in range(1, 10) for b in range(10)} for b in range(1, 10): F['0' + c[b]] = ('0', 1) F['00'] = ('0', 0) def f(x): global F if x in F: return F[x] a, b, y, s = int(x[0]), int(x[1]), x[2: ], 0 for i in range...
353_D. Queue
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes. Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq,bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(1...
39_B. Company Income Growth
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 — to a2 billion, ..., and in the current (2000 + n)-th...
```python _, values,i,years = int(input()),[int(i) for i in input().split(" ")],1,[] if 1 in values: years.append(values.index(1)) i=2 while i in values[years[-1]:]: years.append(values[years[-1]:].index(i)+years[-1]) i+=1 print(len(years)) if len(years) !=0: for year in years: print(2001+year,end=" ") print...
424_C. Magic Formulas
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas: <image><image> Here, "mod" means the operation of taking the residue after dividing. The expression <image> ...
```python import sys input=sys.stdin.readline n=int(input()) ar=list(map(int,input().split())) dp=[0] pre=0 for i in range(1,n+1): pre^=i dp.append(pre) ans=0 for i in range(1,n+1): xx=ar[i-1]^(dp[i-1]*((n//i)%2))^(dp[n%i]) ans^=xx print(ans) ```
449_A. Jzzhu and Chocolate
Jzzhu has a big rectangular chocolate bar that consists of n × m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements: * each cut should be straight (horizontal or vertical); * each cut should go along edges of unit squares (it is prohibited to divide any unit choc...
```python l = input().split() n = int(l[0]) m = int(l[1]) k = int(l[2]) if ( k <= n+m-2 ): if ( k < n ): outn = int((n / (k + 1))) * m else: outn = int(m / (k - n + 2)) if ( k < m): outm = int( m / ( k + 1)) * n else: outm = int( n / ( k - m + 2 )) print ("", max( ou...
493_C. Vasya and Basketball
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger tha...
```python n = int(input()) score = list(map(lambda x: [int(x), 0], input().split())) m = int(input()) score += list(map(lambda x: [int(x), 1], input().split())) score.sort() f = [] if score[0][1] == 0: f.append([1, 0]) else: f.append([0, 1]) for i in range(1, n + m): if score[i][1] == 0: f.appe...
518_B. Tanya and Postcard
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message — string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The...
```python # Tanya and Postcard from collections import Counter def to_dict(s): d = Counter() for c in s: d[c] += 1 return d def change_case(c): if c.islower(): return c.upper() else: return c.lower() yay_total = 0 whoops_total = 0 tanya = to_dict(input()) newspaper = to_d...
544_B. Sea and Islands
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each ...
```python n,k=input().split() n,k=int(n),int(k) if k>(n*n+1)//2: print("NO") exit() print("YES") for i in range(0,n): for j in range(0,n): if((i+j)%2==0 and k>0): print('L',end='') k-=1 else: print('S',end='') print() # Made By ...
592_B. The Monster and the Squirrel
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel. Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex...
```python n=int(input()) N=0 for i in range(2,n): N=N+2*i-3 print(N) ```
686_C. Robbers' watch
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hour...
```python read = lambda: map(int, input().split()) n, m = read() from itertools import permutations, combinations cnt = 0 p1 = 0 x1 = 1 while x1 <= n - 1: x1 *= 7 p1 += 1 p2 = 0 x2 = 1 while x2 <= m - 1: x2 *= 7 p2 += 1 p1, p2 = max(p1, 1), max(p2, 1) Len = p1 + p2 for comb in combinations([0, 1, 2, ...
709_B. Checkpoints
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order...
```python n, a = map(int, input().split()) x = list(map(int, input().split())) if n == 1: print(0) elif n == 2: if abs(x[0]-a) < abs(x[1]-a): print(abs(x[0]-a)) else: print(abs(x[1]-a)) elif n == 3: x = sorted(x) _min = x[0] _mid = x[1] _max = x[2] ans = abs(_max - a)*2 ...
774_H. Repairing Of String
Stepan had a favorite string s which consisted of the lowercase letters of the Latin alphabet. After graduation, he decided to remember it, but it was a long time ago, so he can't now remember it. But Stepan remembers some information about the string, namely the sequence of integers c1, c2, ..., cn, where n equals t...
```python n = int(input()) arr = list(map(int, input().split())) for i in range(n-1, 0, -1): for j in range(i-1, -1, -1): arr[j] -= arr[i]*(i-j+1) s = "a" def rev(c): if c == "a": return "b" else: return "a" for i in range(n): for j in range(arr[i]): s += rev(s[-1])*(i+1)...
79_A. Bus Game
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. * Initially, there is a pile that contains x 100-yen coins and y 10-yen coi...
```python player_one = 'Ciel' player_two = 'Hanako' c100, c10 = map(int, input().split()) full_moves = min([c100 // 2, c10 // 24]) c100 -= full_moves * 2 c10 -= full_moves * 24 while True: if 100 * c100 + 10 * c10 >= 220 and c10 >= 2: tmp = min([2, c100]) c100 -= tmp c10 -= (220 - 100...
81_C. Average Score
After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark. Now it'...
```python from operator import itemgetter from collections import defaultdict n=int(input()) a,b= map(int,input().split()) arr= list(map(int,input().split())) arr = list(enumerate(arr,0)) arr=sorted(arr,key=itemgetter(1),reverse=True) def find_min(num1,num2): if num1<num2: return num1 else: ret...
867_A. Between the Offices
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
```python print((lambda s: 'YES' if s[1][0] == 'S' and s[1][-1] == 'F' else 'NO')((input(), input().strip()))) ```
892_C. Pride
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of ope...
```python import math n=int(input()) a=list(map(int,input().split())) x=[1 for x in a if x==1] x=len(x) if(x>=1): print(n-x) quit() ans=n for i in range(n): g=a[i] for j in range(i,n): g=math.gcd(g,a[j]) if(g==1): ans=min(ans,j-i) if(ans==n): print(-1) else: print(ans+n-1) ```
914_C. Travelling Salesman and Special Numbers
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310 = 11...
```python def Numb(a,k): if a == 0: return 0 m = len(bin(a))-3 if m + 1 < k: return 0 if k == 1: return m+1 if m + 1 == k: return Numb(a & ((1<<m)-1), k-1) return C[m][k]+Numb(a & ((1<<m)-1), k-1) s = input() nDec = int(s,2) n = len(s) k = int(input()) C = [[1],...
937_A. Olympiad
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: * At least one participant should get a dip...
```python n = int(input()) a = [0] * 601 for x in input().split(): a[int(x)] = 1 a[0] = 0 print(sum(a)) ```
962_C. Make a Square
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently ap...
```python '''input 101 ''' from itertools import chain, combinations def binarysearch(arr, x): l = 0 r = len(arr) - 1 while l <= r: mid = l + (r - l) // 2 if arr[mid] == x: return mid elif arr[mid] < x: l = mid + 1 else: r = mid - 1 re...
p02607 AIsing Programming Contest 2020 - An Odd Problem
We have N squares assigned the numbers 1,2,3,\ldots,N. Each square has an integer written on it, and the integer written on Square i is a_i. How many squares i satisfy both of the following conditions? * The assigned number, i, is odd. * The written integer is odd. Constraints * All values in input are integers. * ...
```python input() print(len([i for n,i in enumerate(map(int,input().split()),1) if i%2==1 and n%2])) ```
p02738 AtCoder Grand Contest 043 - Merge Triplets
Given is a positive integer N. Find the number of permutations (P_1,P_2,\cdots,P_{3N}) of (1,2,\cdots,3N) that can be generated through the procedure below. This number can be enormous, so print it modulo a prime number M. * Make N sequences A_1,A_2,\cdots,A_N of length 3 each, using each of the integers 1 through 3N ...
```python from functools import lru_cache N, M = map(int, input().split()) @lru_cache(maxsize=None) def mod_inv(x): x1, y1, z1 = 1, 0, x x2, y2, z2 = 0, 1, M while z1 != 1: d, m = divmod(z2, z1) x1, x2 = x2-d*x1, x1 y1, y2 = y2-d*y1, y1 z1, z2 = m, z1 return x1%M def gen_Y(i): # sC2/1, (s-2...
p02873 AtCoder Grand Contest 040 - ><
Given is a string S of length N-1. Each character in S is `<` or `>`. A sequence of N non-negative integers, a_1,a_2,\cdots,a_N, is said to be good when the following condition is satisfied for all i (1 \leq i \leq N-1): * If S_i= `<`: a_i<a_{i+1} * If S_i= `>`: a_i>a_{i+1} Find the minimum possible sum of the ele...
```python S = input().rstrip("\n") N = len(S) a = [0] * (N+1) for i in range(N): if S[i] == "<": a[i+1] = max(a[i+1], a[i] + 1) for i in range(N-1,-1,-1): if S[i] == ">": a[i] = max(a[i], a[i+1]+1) print(sum(a)) ```
p03007 diverta 2019 Programming Contest 2 - Successive Subtraction
There are N integers, A_1, A_2, ..., A_N, written on a blackboard. We will repeat the following operation N-1 times so that we have only one integer on the blackboard. * Choose two integers x and y on the blackboard and erase these two integers. Then, write a new integer x-y. Find the maximum possible value of the...
```python n,*a=map(int,open(0).read().split()) a.sort() print(sum(abs(i)for i in a)-2*min(abs(a[-1]),abs(a[0]))*(a[0]*a[-1]>0)) if a[0]>0: print(a[0],a[-1]) a[0]-=a[-1] for i in a[1:-2]: print(a[0],i) a[0]-=i print(a[-2],a[0]) elif a[-1]<0: for i in a[:-1]: print(a[-1],i) ...
p03147 AtCoder Beginner Contest 116 - Grand Garden
In a flower bed, there are N flowers, numbered 1,2,......,N. Initially, the heights of all flowers are 0. You are given a sequence h=\\{h_1,h_2,h_3,......\\} as input. You would like to change the height of Flower k to h_k for all k (1 \leq k \leq N), by repeating the following "watering" operation: * Specify integers...
```python n = int(input()) h = list(map(int,input().split())) ans = h[0] for i in range(1,n): if h[i-1] < h[i]: ans += h[i]-h[i-1] print(ans) ```