name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1369_D. TediousLee
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes... Let's define a Rooted Dead Bush (RDB) of level n ...
```python import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, ...
1391_C. Cyclic Permutations
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
```python n = int(input()) M = 10**9+7 fact = [1]*(n+2) for i in range(2, n+1): fact[i] = (i*fact[i-1])%M print(((fact[n]-pow(2, n-1, M))+M)%M) ```
1506_F. Triangular Paths
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r ...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase from collections import deque, Counter, defaultdict from heapq import heapify, heappush, heappop def solve(Y, X, N): points = list(zip(Y, X)) points.sort() res = 0 y1 = x1 = 1 for y2, x2 in points: if y1 - x1 == y2 - x2: if (...
161_B. Discounts
One day Polycarpus stopped by a supermarket on his way home. It turns out that the supermarket is having a special offer for stools. The offer is as follows: if a customer's shopping cart contains at least one stool, the customer gets a 50% discount on the cheapest item in the cart (that is, it becomes two times cheape...
```python n, k = list(map(int, input().split())) p = [[], []] for i in range(1, n + 1): c, t = map(int, input().split()) p[t > 1].append((c, i)) if k > len(p[0]): l = k - len(p[0]) - 1 print(sum(c for c, i in p[0]) / 2 + sum(c for c, i in p[1])) print('\n'.join('1 ' + str(i) for c, i in p[0]...
180_D. Name
Everything got unclear to us in a far away constellation Tau Ceti. Specifically, the Taucetians choose names to their children in a very peculiar manner. Two young parents abac and bbad think what name to give to their first-born child. They decided that the name will be the permutation of letters of string s. To keep...
```python def findmin(lcopy, toexceed): toex = ord(toexceed) - 97 for each in lcopy[(toex+1):]: if each > 0: return True return False def arrange(lcopy, toexceed = None): if toexceed is None: ans = "" for i in range(26): ans += chr(i+97)*lcopy[i] ...
252_B. Unsorting Array
Little Petya likes arrays of integers a lot. Recently his mother has presented him one such array consisting of n elements. Petya is now wondering whether he can swap any two distinct integers in the array so that the array got unsorted. Please note that Petya can not swap equal integers even if they are in distinct po...
```python n=int(input()) a=[int(i) for i in input().split()] b=len(set(a)) c=sorted(a,reverse=True) if n==1 or n==2 or b==1: print("-1") elif n==3: if b==2: if a[0]==a[2]: print("-1") elif a[0]==a[1]: print("2 3") else: print("1 2") elif a[1]!=max(...
348_A. Mafia
One day n friends gathered together to play "Mafia". During each round of the game some player must be the supervisor and other n - 1 people take part in the game. For each person we know in how many rounds he wants to be a player, not the supervisor: the i-th person wants to play ai rounds. What is the minimum number ...
```python # mafia N=int(input()) a=list(map(int,input().split())) def isok(X): sums=0 for num in a: if X<num: return False sums+=max(0,X-num) if sums>=X: return True return False l=0 r=10**12 #l -- case_impossible #r --case_possible while r-l>1: m=(l+...
371_B. Fox Dividing Cheese
Two little greedy bears have found two pieces of cheese in the forest of weight a and b grams, correspondingly. The bears are so greedy that they are ready to fight for the larger piece. That's where the fox comes in and starts the dialog: "Little bears, wait a little, I want to make your pieces equal" "Come off it fox...
```python from math import pow def take_input(s): #for integer inputs if s == 1: return int(input()) return map(int, input().split()) def factor(n,k): i = 0 while(n%k==0): i += 1 n //= k return i a, b = take_input(2) count = 0 if a == b: print(0) exit() a...
442_C. Artem and Array
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
```python MAXN = 5 * 10**5 + 100 a = [] ans = 0 n = int(input()) a = list( map ( int, input().split() ) ) a.append(0) a = [0] + a n = n + 2 arr = [] arr.append( a[0] ) arr.append( a[1] ) i = 2 while i < n : ln = a[i] l1 = arr[-1] l0 = arr[-2] while l1 <= l0 and l1 <= ln : ans = ans + min ( l0 , ln ) ar...
488_C. Fight the Monster
A monster is attacking the Cyberland! Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF). During the battle, every second the monster's HP decrease by max(0, ATKY - DEFM), while Yang's HP decreases by max(0,...
```python # HEY STALKER hp_y, at_y, df_y = map(int, input().split()) hp_m, at_m, df_m = map(int, input().split()) cst_hp, cst_at, cst_df = map(int, input().split()) ans = 2e18 for ati in range(201): for dfi in range(201): if ati + at_y > df_m: k = hp_m // ((at_y + ati) - df_m) if hp_...
512_B. Fox And Jumping
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0. There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After app...
```python def gcd(x,y): while x % y > 0: x, y = y, x % y return y n = int(input()) a, b, c = [int(x) for x in input().split()], [int(x) for x in input().split()], [{} for i in range(n)] def f(i,g): if g == 1: return 0 if i == n: return 100000000000 if g in c[i]: retur...
560_D. Equivalent Strings
Today on a lecture about strings Gerald learned a new definition of string equivalency. Two strings a and b of equal length are called equivalent in one of the two cases: 1. They are equal. 2. If we split string a into two halves of the same size a1 and a2, and string b into two halves of the same size b1 and b2...
```python def equals(a, b): if (a == b): return True len_a, len_b = len(a), len(b) if (len_a & 1 or len_b & 1): return False if (len_a == 1): return False as1 = a[0:len_a//2] as2 = a[len_a//2:(len_a//2)*2] bs1 = b[:len_b//2] bs2 = b[len_b//2:(len_b//2)*2] return (equals(as1, bs2) ...
586_F. Lizard Era: Beginning
In the game Lizard Era: Beginning the protagonist will travel with three companions: Lynn, Meliana and Worrigan. Overall the game has n mandatory quests. To perform each of them, you need to take exactly two companions. The attitude of each of the companions to the hero is an integer. Initially, the attitude of each o...
```python #!/usr/bin/env python3 n = int(input()) a = [0] * n b = [0] * n c = [0] * n for i in range(n): a[i], b[i], c[i] = map(int, input().split()) middle = { } stack = [ ] result = (-1e10, ()) phase = 1 def search(pos, l, m, w): global result if (pos == n >> 1) if phase == 1 else (pos < n >> 1): ...
609_B. The Best Gift
Emily's birthday is next week and Jack has decided to buy a present for her. He knows she loves books so he goes to the local bookshop, where there are n books on sale from one of m genres. In the bookshop, Jack decides to buy two books of different genres. Based on the genre of books on sale in the shop, find the nu...
```python n, m = list(map(int, input().split())) a = list(map(int, input().split())) t = 0 for i in range(m): cnt = a.count(i + 1) t += cnt * (n - cnt) n -= cnt print(t) ```
630_A. Again Twenty Five!
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
```python n=int(input()) if(n==0): print(1) elif(n==1): print(5) else: print(25) ```
656_E. Out of Controls
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them. Input The first line of the input contains a single integer N (3 ≤ N ≤ 10). Th...
```python #!/usr/bin/python3 import sys sys.setrecursionlimit(10000) n = int(input()) a = [] def read(i): try: 1 / (n - i) a.append(list(map(int, input().split()))) read(i + 1); except: pass def f(i, j, k): try: 1 / (n - i) 1 / (n - j) 1 / (n - k)...
702_E. Analysis of Pathes in Functional Graph
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1. Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights o...
```python import sys n, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split()) a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) b = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) logk = len(bin(k)) - 2 sum_w, sum_w_p = b[:], b[:] min_w, min_w_p = b[:], b[:] dest, ...
814_C. An impassioned circulation of affection
Nadeko's birthday is approaching! As she decorated the room for the party, a long garland of Dianthus-shaped paper pieces was placed on a prominent part of the wall. Brother Koyomi will like it! Still unsatisfied with the garland, Nadeko decided to polish it again. The garland has n pieces numbered from 1 to n from le...
```python """ Python 3 compatibility tools. """ from __future__ import division, print_function import itertools import sys import os from io import BytesIO, IOBase if sys.version_info[0] < 3: input = raw_input range = xrange filter = itertools.ifilter map = itertools.imap zip = itertools.izip def is_it_...
83_C. Track
You already know that Valery's favorite sport is biathlon. Due to your help, he learned to shoot without missing, and his skills are unmatched at the shooting range. But now a smaller task is to be performed, he should learn to complete the path fastest. The track's map is represented by a rectangle n × m in size divi...
```python import sys from array import array # noqa: F401 from itertools import combinations from collections import deque def input(): return sys.stdin.buffer.readline().decode('utf-8') n, m, k = map(int, input().split()) chars = ( ['}' * (m + 2)] + ['}' + ''.join('{' if c == 'S' else '|' if c == 'T' ...
886_D. Restoration of string
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
```python StringsNumber = int(input()) FinalStrings = [] Strings = [] for i in range(StringsNumber): Strings.append(input()) LetterGraph = {} # Генерим граф for i in range(len(Strings)): if len(Strings[i]) == 1: if Strings[i] not in LetterGraph: LetterGraph[Strings[i]] = "" #...
909_D. Colorful Points
You are given a set of points on a straight line. Each point has a color assigned to it. For point a, its neighbors are the points which don't have any other points between them and a. Each point has at most two neighbors - one from the left and one from the right. You perform a sequence of operations on this set of p...
```python name = input() blocks = [] now = name[0] counter = 1 for x in range(1, len(name)): if name[x] != now: blocks.append((now, counter)) now = name[x] counter = 1 else: counter += 1 blocks.append((now, counter)) counter = 0 temp = [] while len(blocks) > 1: counter += 1...
931_A. Friends Meeting
Two friends are on the coordinate axis Ox in points with integer coordinates. One of them is in the point x1 = a, another one is in the point x2 = b. Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes according to the f...
```python a=int(input()) b=int(input()) def fact(a): ans=0 for i in range(a,0,-1): ans=ans+i return ans d=abs(a-b) if d==1: print("1") elif d%2==0: a=fact(d//2) a=a*2 print(a) else: a=fact(d//2) b=fact((d+1)//2) print(a+b) ```
985_A. Chess Placing
You are given a chessboard of size 1 × n. It is guaranteed that n is even. The chessboard is painted like this: "BWBW...BW". Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to <image>. In one step you can mov...
```python import re import math import decimal import bisect def read(): return input().strip() n = int(read()) ps = [0 for i in range(1, n+1)] nadd = 10 for x in sorted([int(_) for _ in read().split()]): ps[x-1] = nadd nadd += 10 nadd = 15 for i, p in enumerate(ps): if p == 0: ps[i] = nadd nadd += 10 # prin...
p02574 AtCoder Beginner Contest 177 - Coprime
We have N integers. The i-th number is A_i. \\{A_i\\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N. \\{A_i\\} is said to be setwise coprime when \\{A_i\\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1. Determine if \\{A_i\\} is pairwise coprime, setw...
```python N = int(input()) A = list(map(int,input().split())) A = sorted(A,reverse = True) prime = [0] * (10**6+1) eratos = [True] * (A[0] + 1) D = [0] * (A[0]+1) D[1] = 1 for i in range(2,A[0] + 1): if not eratos[i]: continue else: for j in range(i,A[0] + 1,i): if not D[j]: D[j] = i if...
p02705 AtCoder Beginner Contest 163 - Circle Pond
Print the circumference of a circle of radius R. Constraints * 1 \leq R \leq 100 * All values in input are integers. Input Input is given from Standard Input in the following format: R Output Print the circumference of the circle. Your output is considered correct if and only if its absolute or relative error ...
```python R=int(input()) print(R*6.2831853) ```
p02834 AtCoder Beginner Contest 148 - Playing Tag on Tree
We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vert...
```python import sys sys.setrecursionlimit(10**8) input = sys.stdin.readline n, u, v = map(int, input().split()) u, v = u - 1, v - 1 graph = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a, b = a - 1, b - 1 graph[a].append(b) graph[b].append(a) def dfs(v, d, count): ...
p02971 AtCoder Beginner Contest 134 - Exception Handling
You are given a sequence of length N: A_1, A_2, ..., A_N. For each integer i between 1 and N (inclusive), answer the following question: * Find the maximum value among the N-1 elements other than A_i in the sequence. Constraints * 2 \leq N \leq 200000 * 1 \leq A_i \leq 200000 * All values in input are integers. Inp...
```python n=int(input()) a=[int(input()) for _ in [0]*n] b,c=sorted(a,reverse=True)[0:2] for A in a: if A==b: print(c) else: print(b) ```
p03107 AtCoder Beginner Contest 120 - Unification
There are N cubes stacked vertically on a desk. You are given a string S of length N. The color of the i-th cube from the bottom is red if the i-th character in S is `0`, and blue if that character is `1`. You can perform the following operation any number of times: choose a red cube and a blue cube that are adjacent...
```python S = input() print(min(S.count('1'),S.count('0'))*2) ```
p03254 AtCoder Grand Contest 027 - Candy Distribution Again
There are N children, numbered 1, 2, ..., N. Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets. For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy ...
```python n, x = map(int, input().split()) a = list(map(int, input().split())) a.sort() ans = 0 for i in a: if x < i: break ans += 1 x -= i else: if x > 0: ans -= 1 print(ans) ```
p03407 AtCoder Beginner Contest 091 - Two Coins
An elementary school student Takahashi has come to a variety store. He has two coins, A-yen and B-yen coins (yen is the currency of Japan), and wants to buy a toy that costs C yen. Can he buy it? Note that he lives in Takahashi Kingdom, and may have coins that do not exist in Japan. Constraints * All input values a...
```python a,b,c = map(int,input().split()) if c > a + b: print('No') else: print('Yes') ```
p03570 CODE FESTIVAL 2017 qual C - Yet Another Palindrome Partitioning
We have a string s consisting of lowercase English letters. Snuke is partitioning s into some number of non-empty substrings. Let the subtrings obtained be s_1, s_2, ..., s_N from left to right. (Here, s = s_1 + s_2 + ... + s_N holds.) Snuke wants to satisfy the following condition: * For each i (1 \leq i \leq N), it ...
```python import sys readline = sys.stdin.readline from collections import defaultdict S = list(map(lambda x: ord(x)-97, readline().strip())) N = len(S) table = [0] + [1<<S[i] for i in range(N)] for i in range(1, N+1): table[i] ^= table[i-1] inf = 10**9+7 dp = defaultdict(lambda: inf) dp[0] = 0 for i in range(1...
p03725 AtCoder Grand Contest 014 - Closed Rooms
Takahashi is locked within a building. This building consists of H×W rooms, arranged in H rows and W columns. We will denote the room at the i-th row and j-th column as (i,j). The state of this room is represented by a character A_{i,j}. If A_{i,j}= `#`, the room is locked and cannot be entered; if A_{i,j}= `.`, the r...
```python from collections import deque h,w,k = map(int,input().split()) a = [] for i in range(h): b = input() tmp = [] for j in range(w): tmp.append(b[j]) if b[j] == "S": sx = i sy = j a.append(tmp) ma = [[0]*w for i in range(h)] def dfs(x,y,z): if ma[x][y] == 1: return if z>k: ...
p03889 CODE FESTIVAL 2016 Relay (Parallel) - Mirror String
You are given a string S consisting of letters `b`, `d`, `p` and `q`. Determine whether S is a mirror string. Here, a mirror string is a string S such that the following sequence of operations on S results in the same string S: 1. Reverse the order of the characters in S. 2. Replace each occurrence of `b` by `d`, `d...
```python r=str.replace s=input() print(['No','Yes'][s==''.join(reversed(r(r(r(r(r(r(r(r(s,'b','0'),'d','1'),'p','2'),'q','3'),'0','d'),'1','b'),'2','q'),'3','p')))]) ```
p04048 AtCoder Grand Contest 001 - Mysterious Light
Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light. Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c. Inside the triangle, the rifle is placed at the point p on segment ab such that ap ...
```python """B - Mysterious Light""" N,X=(int(i) for i in input().split()) def MysteriousLight(tmp,rem): while rem: tmp, rem= rem,tmp%rem return tmp print(3*(N-MysteriousLight(N,X))) ```
p00127 Pocket Pager Input
One day, Taro received a strange email with only the number "519345213244" in the text. The email was from my cousin, who was 10 years older than me, so when I called and asked, "Oh, I sent it with a pocket bell because I was in a hurry. It's convenient. Nice to meet you!" I got it. You know this cousin, who is always ...
```python mes = {11:"a",12:"b",13:"c",14:"d",15:"e" ,21:"f",22:"g",23:"h",24:"i",25:"j" ,31:"k",32:"l",33:"m",34:"n",35:"o" ,41:"p",42:"q",43:"r",44:"s",45:"t" ,51:"u",52:"v",53:"w",54:"x",55:"y" ,61:"z",62:".",63:"?",64:"!",65:" "} while True: try: s = input() except: break...
p00447 Searching Constellation
problem You are looking for a constellation in a picture of the starry sky. The photo always contains exactly one figure with the same shape, orientation, and size as the constellation you are looking for. However, there is a possibility that extra stars are shown in the photograph other than the stars that make up th...
```python import operator for e in iter(input,'0'): target = [[*map(int,input().split())]for _ in[0]*int(e)] s,t = min(target) b = {tuple(map(int,input().split()))for _ in[0]*int(input())} m=max(b)[0] - max(target)[0] + s for x,y in b: if x>m:continue for u,v in target: i...
p00638 Old Bridges
Long long ago, there was a thief. Looking for treasures, he was running about all over the world. One day, he heard a rumor that there were islands that had large amount of treasures, so he decided to head for there. Finally he found n islands that had treasures and one island that had nothing. Most of islands had sea...
```python while True: n = int(input()) if n == 0: break z = sorted([tuple(map(int, input().split())) for _ in range(n)], key=lambda x: x[1]) total = 0 for a, b in z: total += a if total > b: print("No") break else: print("Yes") ```
p00914 Equal Sum Sets
Let us consider sets of positive integers less than or equal to n. Note that all elements of a set are different. Also note that the order of elements doesn't matter, that is, both {3, 5, 9} and {5, 9, 3} mean the same set. Specifying the number of set elements and their sum to be k and s, respectively, sets satisfyin...
```python import itertools while True: N,K,S = map(int,input().split()) if N == 0: break cnt = 0 for comb in itertools.combinations(range(1,N+1),K): if sum(comb) == S: cnt += 1 print(cnt) ```
p01316 Differential Pulse Code Modulation
Differential pulse code modulation is one of the compression methods mainly used when compressing audio signals. The audio signal is treated as an integer sequence (impulse sequence) on the computer. The integer sequence is a sample of the input signal at regular time intervals and the amplitude recorded. In general, ...
```python def solve(): from sys import stdin INF = float('inf') f_i = stdin while True: N, M = map(int, f_i.readline().split()) if N == 0: break C = tuple(int(f_i.readline()) for i in range(M)) # decode table tbl_1 = tuple(tuple(...
p01646 Dictionary
Problem Statement We found a dictionary of the Ancient Civilization Mayo (ACM) during excavation of the ruins. After analysis of the dictionary, we revealed they used a language that had not more than 26 letters. So one of us mapped each letter to a different English alphabet and typed all the words in the dictionary ...
```python def add_edge(node, adj_lst, s1, s2): ind = 0 max_len = min(len(s1), len(s2)) while ind < max_len and s1[ind] == s2[ind]: ind += 1 if ind == max_len: return max_len < len(s1) c1 = ord(s1[ind]) - ord("a") c2 = ord(s2[ind]) - ord("a") adj_lst[c1].add(c2) node.add(c1) node.add(c2) ret...
p01931 Check answers
problem AOR Ika is studying to pass the test. AOR Ika-chan solved the $ N $ question. After that, round the solved problem according to the following procedure. 1. Check the correctness of the answer. 2. If the answer is correct, write a circle mark, and if it is incorrect, write a cross mark on the answer sheet. ...
```python def main(): N = int(input()) S = input() try: ans = S.index('xx') + 1 print(ans) except: print(N) main() ```
p02365 Minimum-Cost Arborescence
Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the...
```python from collections import defaultdict from itertools import chain nv, ne, r = map(int, input().split()) in_edges = defaultdict(set) out_edges = defaultdict(set) while ne: s, t, w = map(int, input().split()) in_edges[t].add((w, s)) out_edges[s].add((w, t)) ne -= 1 def chu_liu_edmond(vertices,...
1003_D. Coins and Queries
Polycarp has n coins, the value of the i-th coin is a_i. It is guaranteed that all the values are integer powers of 2 (i.e. a_i = 2^d for some non-negative integer number d). Polycarp wants to know answers on q queries. The j-th query is described as integer number b_j. The answer to the query is the minimum number of...
```python # @oj: codeforces # @id: hitwanyang # @email: 296866643@qq.com # @date: 2020-10-14 16:44 # @url:https://codeforc.es/contest/1003/problem/D import sys,os from io import BytesIO, IOBase import collections,itertools,bisect,heapq,math,string from decimal import * # region fastio BUFSIZE = 8192 BUFSIZE = 8192 c...
1027_E. Inverse Coloring
You are given a square board, consisting of n rows and n columns. Each tile in it should be colored either white or black. Let's call some coloring beautiful if each pair of adjacent rows are either the same or different in every position. The same condition should be held for the columns as well. Let's call some col...
```python import sys from array import array # noqa: F401 def readline(): return sys.stdin.buffer.readline().decode('utf-8') n, k = map(int, readline().split()) mod = 998244353 if k == 1: print(0) exit() dp1 = [array('i', [0])*n for _ in range(n)] dp2 = [array('i', [0])*n for _ in range(n)] dp1[0][0] = ...
1091_G. New Year and the Factorisation Collaboration
Integer factorisation is hard. The RSA Factoring Challenge offered $100 000 for factoring RSA-1024, a 1024-bit long product of two prime numbers. To this date, nobody was able to claim the prize. We want you to factorise a 1024-bit number. Since your programming language of choice might not offer facilities for handli...
```python import sys import random def gcd(x, y): return x if y == 0 else gcd(y, x % y) def isPrime(n): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. """ if n!=int(n): return False ...
1110_E. Magic Stones
Grigory has n magic stones, conveniently numbered from 1 to n. The charge of the i-th stone is equal to c_i. Sometimes Grigory gets bored and selects some inner stone (that is, some stone with index i, where 2 ≤ i ≤ n - 1), and after that synchronizes it with neighboring stones. After that, the chosen stone loses its ...
```python n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) f=a[0]==b[0] a=sorted([a[i+1]-a[i] for i in range(n-1)]) b=sorted([b[i+1]-b[i] for i in range(n-1)]) print('YES' if f and a==b else 'NO') ```
1140_B. Good String
You have a string s of length n consisting of only characters > and <. You may do some operations with this string, for each operation you have to choose some character that still remains in the string. If you choose a character >, the character that comes right after it is deleted (if the character you chose was the l...
```python t = int(input()) tests = [] for i in range(t): length = int(input()) tests.append(input()) def solve(s): streak1 = 0 streak2 = 0 for i in range(len(s)): if s[i] == "<": streak1 +=1 else: break for i in range(len(s)): if s[-i-1] == ">...
1199_E. Matching vs Independent Set
You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line...
```python import sys input = sys.stdin.readline T = int(input()) for _ in range(T): n, m = map(int, input().split()) v = [True] * (3 * n + 1) e = [0] * n ptr = 0 for i in range(1, m + 1): a, b = map(int, input().split()) if ptr < n and v[a] and v[b]: e[ptr] = i ...
1216_D. Swords
There were n types of swords in the theater basement which had been used during the plays. Moreover there were exactly x swords of each type. y people have broken into the theater basement and each of them has taken exactly z swords of some single type. Note that different people might have taken different types of swo...
```python n= int(input()) s = list(map(int,input().split())) s.sort() maxm = s[n-1] ans = 0 def computeGCD(x, y): while(y): x, y = y, x % y return x a = maxm-s[0] for i in range(1,n-1): a = computeGCD(a,maxm-s[i]) for i in range(0,n-1): ans += maxm - s[i] print(ans//a,a) ```
1281_B. Azamon Web Services
Your friend Jeff Zebos has been trying to run his new online company, but it's not going very well. He's not getting a lot of sales on his website which he decided to call Azamon. His big problem, you think, is that he's not ranking high enough on the search engines. If only he could rename his products to have better ...
```python for _ in range(int(input())): a,c=input().split() a=list(a) b=sorted(a) if a!=b: for i,x in enumerate(b): if a[i]!=x: tmp=a[i] a[i]=x break for i in range(len(a)-1,-1,-1): if a[i]==x: a[i]=t...
1301_B. Motarack's Birthday
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
```python # import sys # file = open('test1') # sys.stdin = file def ii(): return int(input()) def ai(): return list(map(int, input().split())) def mi(): return map(int, input().split()) for _ in range(int(input())): n = ii() lst = ai() nlst = [] for ind, ele in enumerate(lst): if ele==-1: if ind!=0 and lst[i...
1325_B. CopyCopyCopyCopyCopy
Ehab has an array a of length n. He has just enough free time to make a new array consisting of n copies of the old array, written back-to-back. What will be the length of the new array's longest increasing subsequence? A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (pos...
```python t = int(input()) for i in range(t): n = int(input()) a = input().split() s_a = set(a) print(f"{len(s_a)}\n") ```
1344_A. Hilbert's Hotel
Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,...
```python # cook your dish here t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) l=[0]*n d={} f=0 for i in range(n): l[i]=i+a[i%n] d[l[i]]=d.get(l[i],0)+1 if d[l[i]]==2: f=1 break r={} for i in range(n): ...
1366_A. Shovels and Swords
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick. Each tool can be sold for exactly one emerald. How many...
```python import math t=int(input()) for i in range(t): a,b=map(int,input().split()) m=min(a,b,(a+b)/3) print(math.floor(m)) ```
1408_A. Circle Coloring
You are given three sequences: a_1, a_2, …, a_n; b_1, b_2, …, b_n; c_1, c_2, …, c_n. For each i, a_i ≠ b_i, a_i ≠ c_i, b_i ≠ c_i. Find a sequence p_1, p_2, …, p_n, that satisfy the following conditions: * p_i ∈ \\{a_i, b_i, c_i\} * p_i ≠ p_{(i mod n) + 1}. In other words, for each element, you need to choose ...
```python import sys from sys import stdin,stdout import math import random import heapq from collections import Counter from functools import lru_cache #@lru_cache(maxsize=None) #for optimizing the execution time of callable objects/functions(placed above callable functions) try: for _ in range(int(input())): ...
1428_D. Bouncing Boomerangs
To improve the boomerang throwing skills of the animals, Zookeeper has set up an n × n grid with some targets, where each row and each column has at most 2 targets each. The rows are numbered from 1 to n from top to bottom, and the columns are numbered from 1 to n from left to right. For each column, Zookeeper will t...
```python n, *a = map(int, open(0).read().split()) now = 1 heights = [[] for _ in range(n)] st0 = [] st1 = [] failed = False for i in range(n - 1, -1, -1): if a[i] == 1: heights[i].append(now) st0.append((now, i)) now += 1 elif a[i] == 2: if len(st0): h, j = st0.pop()...
1451_D. Circle Game
Utkarsh is forced to play yet another one of Ashish's games. The game progresses turn by turn and as usual, Ashish moves first. Consider the 2D plane. There is a token which is initially at (0,0). In one move a player must increase either the x coordinate or the y coordinate of the token by exactly k. In doing so, the...
```python import sys input = lambda:sys.stdin.readline().strip() t = int(input()) while t: t-=1 d,k = map(int,input().split()) x = 0 y = 0 while 1: if x<=y and (x+k)*(x+k)+y*y<=d*d: x+=k elif x>y and (y+k)*(y+k)+x*x<=d*d: y+=k else: brea...
1475_D. Cleaning the Phone
Polycarp often uses his smartphone. He has already installed n applications on it. Application with number i takes up a_i units of memory. Polycarp wants to free at least m units of memory (by removing some applications). Of course, some applications are more important to Polycarp than others. He came up with the fol...
```python #lösningsmängd är nedåtbegränsad och ordnad. -> optimal minsta existerar i kontext. #Vet att det är sant att lösning består av x stna 1-cost x tillhör [0..all(1-cost)] #för x stna 1-cost bestäms y stna 2-cost entydligt. #itererar alla x, försök i varje steg reducera y från mx(2-cost) #same hold tru if conv p...
1500_B. Two chandeliers
Vasya is a CEO of a big construction company. And as any other big boss he has a spacious, richly furnished office with two crystal chandeliers. To stay motivated Vasya needs the color of light at his office to change every day. That's why he ordered both chandeliers that can change its color cyclically. For example: r...
```python def main(): n, m, k = list(map(lambda x: int(x), str(input()).split(' '))) a = list(map(lambda x: int(x), str(input()).split(' '))) b = list(map(lambda x: int(x), str(input()).split(' '))) if n < m: print(solve(m, n, k, b, a)) return print(solve(n, m, k, a, b)) def solve(n...
1525_D. Armchairs
There are n armchairs, numbered from 1 to n from left to right. Some armchairs are occupied by people (at most one person per armchair), others are not. The number of occupied armchairs is not greater than n/2. For some reason, you would like to tell people to move from their armchairs to some other ones. If the i-th ...
```python import sys input = sys.stdin.buffer.readline import math n=int(input()) arr=[int(x) for x in input().split()] h=[] v=[] for i in range(n): if arr[i]: v.append(i) else: h.append(i) hh=len(h) vv=len(v) dp=[[0 for j in range(hh+1)] for i in range(vv+1)] for i in range(1,vv+1): dp...
157_A. Game Outcome
Sherlock Holmes and Dr. Watson played some game on a checkered board n × n in size. During the game they put numbers on the board's squares by some tricky rules we don't know. However, the game is now over and each square of the board contains exactly one number. To understand who has won, they need to count the number...
```python n = int(input()) r = lambda : list(map(int, input().split())) arr = [] for i in range(n): a = r() arr.append(a) row = [sum(i) for i in arr] col = [] for i in range(n): c = 0 for j in range(n): c+=arr[j][i] col.append(c) ans = 0 for i in range(n): for j in range(n): if row[...
178_A1. Educational Game
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
```python n = int(input()) a = [int(t) for t in input().split()] c = 0 for i in range(n - 1): if a[i] > 0: c += a[i] print(c) j = 0 while 2 ** j + i < n: j += 1 a[2 ** (j - 1) + i] += a[i] a[i] = 0 else: print(c) ```
19_B. Checkout Assistant
Bob came to a cash & carry store, put n items into his trolley, and went to the checkout counter to pay. Each item is described by its price ci and time ti in seconds that a checkout assistant spends on this item. While the checkout assistant is occupied with some item, Bob can steal some other items from his trolley. ...
```python n=int(input()) ar=[float('inf')]*(n+1) ar[0]=0 for i in range(n): t,c=map(int,input().split()) for j in range(n-1,-1,-1): w=min(j+t+1,n) ar[w]=min(ar[w],ar[j]+c) print(ar[n]) ```
223_C. Partial Sums
You've got an array a, consisting of n integers. The array elements are indexed from 1 to n. Let's determine a two step operation like that: 1. First we build by the array a an array s of partial sums, consisting of n elements. Element number i (1 ≤ i ≤ n) of array s equals <image>. The operation x mod y means that ...
```python n, k = map(int, input().split()) num = list(map(int, input().split())) MOD = 10 ** 9 + 7 cf = [1] for i in range(1, 2020): cf.append((cf[-1] * (k + i - 1) * pow(i, MOD - 2, MOD)) % MOD) ans = [0 for i in range(n)] for i in range(n): for j in range(i + 1): ans[i] = (ans[i] + cf[i - j] * num[j...
248_A. Cupboards
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house. Karlsson's gaze immediately fell on n wooden ...
```python k = int(input()) lo=ro=rc=lc=0 for _ in range(k): n , m = map(int,input().split()) if(n==0): lo+=1 else: lc=lc+1 if(m==0): ro+=1 else : rc=rc+1 print(min(lo,lc)+min(ro,rc)) ```
272_B. Dima and Sequence
Dima got into number sequences. Now he's got sequence a1, a2, ..., an, consisting of n positive integers. Also, Dima has got a function f(x), which can be defined with the following recurrence: * f(0) = 0; * f(2·x) = f(x); * f(2·x + 1) = f(x) + 1. Dima wonders, how many pairs of indexes (i, j) (1 ≤ i < j ≤...
```python def f(x): return str(bin(x)).count('1') n = int(input()) a = list(map(int, input().split())) ans = [f(x) for x in a] s = set(ans) counts = {x:ans.count(x) for x in s} ans = 0 for i in counts: ans += (counts[i]*(counts[i]-1))//2 print(ans) ```
319_B. Psychos in a Line
There are n psychos standing in a line. Each psycho is assigned a unique integer from 1 to n. At each step every psycho who has an id greater than the psycho to his right (if exists) kills his right neighbor in the line. Note that a psycho might kill and get killed at the same step. You're given the initial arrangeme...
```python n, t = int(input()), list(map(int, input().split())) p, s, r = [0] * n, [0] * n, t[0] for i in range(n - 1): j = i + 1 x = t[j] if x > r: r = x else: while t[i] < x: s[j], i = max(s[j], s[i]), p[i] p[j] = i s[j] += 1 print(max(s)) # Made By Mostafa_Khaled `...
343_B. Alternating Current
Mad scientist Mike has just finished constructing a new device to search for extraterrestrial intelligence! He was in such a hurry to launch it for the first time that he plugged in the power wires without giving it a proper glance and started experimenting right away. After a while Mike observed that the wires ended u...
```python list_inp=input() stack_jud=[] for i in list_inp: if len(stack_jud)>0: if stack_jud[-1]==i:stack_jud.pop() else: stack_jud.append(i) else: stack_jud.append(i) if stack_jud==[]:print ('Yes') else:print ('No') ```
38_C. Blinds
The blinds are known to consist of opaque horizontal stripes that can be rotated thus regulating the amount of light flowing in the room. There are n blind stripes with the width of 1 in the factory warehouse for blind production. The problem is that all of them are spare details from different orders, that is, they ma...
```python m, l = map(int, input().split()) a = list(map(int, input().split())) print(max(i * sum(ai // i for ai in a) for i in range(l, 101))) ```
40_B. Repaintings
A chessboard n × m in size is given. During the zero minute we repaint all the black squares to the 0 color. During the i-th minute we repaint to the i color the initially black squares that have exactly four corner-adjacent squares painted i - 1 (all such squares are repainted simultaneously). This process continues a...
```python import itertools import math n, m = [int(k) for k in input().split()] x = int(input()) if n-2*(x-1) < 1 or m-2*(x-1) < 1: print(0) elif n-2*(x-1) == 1 or m-2*(x-1) == 1: print((n+m-4*(x-1))//2) else: print(n+m-2 - 4*(x-1)) ```
438_A. The Child and Toy
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy. The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 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 list(map(int, sys.stdin.rea...
45_H. Road Problem
The Berland capital (as you very well know) contains n junctions, some pairs of which are connected by two-way roads. Unfortunately, the number of traffic jams in the capital has increased dramatically, that's why it was decided to build several new roads. Every road should connect two junctions. The city administrat...
```python import sys import threading def main(): p = input().split() n = int(p[0]) #number of locations m = int(p[1]) #number of passages if n==1: #if there's only one location, there's nothing to do print(0) return if n==2: #if there's only two nodes, the only edge between ...
483_B. Friends and Presents
You have two friends. You want to present each of them several positive integers. You want to present cnt1 numbers to the first friend and cnt2 numbers to the second friend. Moreover, you want all presented numbers to be distinct, that also means that no number should be presented to both friends. In addition, the fir...
```python c1,c2,x,y=map(int,input().split()) def fn(val): f=[val//x,val//y] both=val//(x*y) f=[i-both for i in f] oth=val-f[0]-f[1]-both cnt=[c1-f[1],c2-f[0]] if cnt[0]<0:cnt[0]=0 if cnt[1] < 0: cnt[1] = 0 return (sum(cnt)<=oth) l=0;r=int(1e18) while r-l>1: m=(r+l)//2 if fn(m): ...
507_B. Amr and Pins
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ...
```python import math #.sqrt def ceil (a, b): return -(-a // b) def answer(r, x, y, xp, yp): d = math.sqrt((xp-x)**2 + (yp-y)**2) num_rs = ceil(d, 2*r) return int(num_rs) def main(): r, x, y, xp, yp = [int(i) for i in input().split()] print(answer(r, x, y, xp, yp)) return main() ```
556_C. Case of Matryoshkas
Andrewid the Android is a galaxy-famous detective. He is now investigating the case of vandalism at the exhibition of contemporary art. The main exhibit is a construction of n matryoshka dolls that can be nested one into another. The matryoshka dolls are numbered from 1 to n. A matryoshka with a smaller number can be ...
```python n, m = [int(x) for x in input().split()] a = [] for i in range(m): a.append([int(x) for x in input().split()][1:]) b = [] curt = 0 for i in a: j = 0 b.append([]) while (j < len(i)) and (i[j] == (j + 1)): j += 1 if j != 0: b[-1] = [j] b[-1] += [1] * (len(i) - j) curt...
582_A. GCD Table
The GCD table G of size n × n for an array of positive integers a of length n is defined by formula <image> Let us remind you that the greatest common divisor (GCD) of two positive integers x and y is the greatest integer that is divisor of both x and y, it is denoted as <image>. For example, for array a = {4, 3, 6,...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write i...
604_A. Uncowed Forces
Kevin Sun has just finished competing in Codeforces Round #334! The round was 120 minutes long and featured five problems with maximum point values of 500, 1000, 1500, 2000, and 2500, respectively. Despite the challenging tasks, Kevin was uncowed and bulldozed through all of them, distinguishing himself from the herd a...
```python t=list(map(int,input().split())) w=list(map(int,input().split())) q,z=map(int,input().split()) c=0 v=0 for i in range(500,3000,500): x=(1-(t[v]/250))*i-50*w[v] a=max(0.3*i,x) c=c+a v=v+1 f=q*100-z*50 dp=c+f print(int(dp)) ```
626_D. Jerry's Protest
Andrew and Jerry are playing a game with Harry as the scorekeeper. The game consists of three rounds. In each round, Andrew and Jerry draw randomly without replacement from a jar containing n balls, each labeled with a distinct positive integer. Without looking, they hand their balls to Harry, who awards the point to t...
```python def main(): n = int(input()) a = list(map(int, input().split())) max_element = max(a) + 1 #print(max_element) diff_freq = [0 for i in range(max_element)] for i in range(n): for j in range(i): diff_freq[abs(a[i] - a[j])] += 1 largest = [0 for i in range(max_elem...
650_B. Image Preview
Vasya's telephone contains n photos. Photo number 1 is currently opened on the phone. It is allowed to move left and right to the adjacent photo by swiping finger over the screen. If you swipe left from the first photo, you reach photo n. Similarly, by swiping right from the last photo you reach photo 1. It takes a sec...
```python def main(): n, a, b, t = map(int, input().split()) b += 1 l = [b if char == "w" else 1 for char in input()] t -= sum(l) - a * (n + 2) hi, n2 = n, n * 2 n21 = n2 + 1 lo = res = 0 l *= 2 while lo <= n and hi < n2: t -= l[hi] hi += 1 b = hi - n ...
675_E. Trains and Statistic
Vasya commutes by train every day. There are n train stations in the city, and at the i-th station it's possible to buy only tickets to stations from i + 1 to ai inclusive. No tickets are sold at the last station. Let ρi, j be the minimum number of tickets one needs to buy in order to get from stations i to station j....
```python n=int(input()) a=list(map(int, input().split())) a=[ai-1 for ai in a] a[n:n] = [n - 1] dp=[0]*n ans=0 i=n-2 nmax=2**17 tree=[[0,0]]*2*nmax; #Build Segment tree j=0 while j<n: tree[nmax + j] = [a[j], j] j=j+1 j=nmax-1 while j>0: tree[j]=max(tree[j*2],tree[j*2+1]) j=j-1 #get max of a int...
765_D. Artsem and Saunders
Artsem has a friend Saunders from University of Chicago. Saunders presented him with the following problem. Let [n] denote the set {1, ..., n}. We will also write f: [x] → [y] when a function f is defined in integer points 1, ..., x, and all its values are integers from 1 to y. Now then, you are given a function f: [...
```python n = int(input()) f = list(map(int, input().split())) h = [] ind_h = [-1] * (n + 1) g = [0] * n occs = {} for i in range(len(f)): if f[i] not in occs: occs[f[i]] = {i + 1} h.append(f[i]) ind_h[f[i]] = len(h) - 1 g[i] = len(h) else: g[i] = ind_h[f[i]] + 1 ...
789_A. Anastasia and pebbles
Anastasia loves going for a walk in Central Uzhlyandian Park. But she became uninterested in simple walking, so she began to collect Uzhlyandian pebbles. At first, she decided to collect all the pebbles she could find in the park. She has only two pockets. She can put at most k pebbles in each pocket at the same time....
```python import math n,k = map(int,input().split()) stones = list(map(int, input().split())) days = 0 for i in range(n): days += math.ceil(stones[i]/k) print(math.ceil(days/2)) ```
80_C. Heroes
The year of 2012 is coming... According to an ancient choradrican legend in this very year, in 2012, Diablo and his brothers Mephisto and Baal will escape from hell, and innumerable hordes of demons will enslave the human world. But seven brave heroes have already gathered on the top of a mountain Arreat to protect us...
```python # -*- coding: utf-8 -*- """ Created on Fri Nov 1 14:28:37 2019 @author: PC-4 """ from itertools import combinations, product Teams = [[1, 1, 5], [1, 2, 4], [1, 3, 3], [2, 2, 3]] Names = {} Names["Anka"] = 0 Names["Chapay"] = 1 Names["Cleo"] = 2 Names["Dracul"] = 3 Names["Hexadec...
835_A. Key races
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
```python s, v1, v2, t1, t2 = list(map(int, input().split())) a = 2*t1 + s*v1 b = 2*t2 + s*v2 if a > b: print("Second") elif a < b: print("First") else: print("Friendship") ```
87_B. Vasya and Types
Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below...
```python types = {'void':'void', 'errtype':'errtype'} def getRealType(type_expr): expr_type = type_expr.strip('&*') full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype")) base_type = full_type_name.strip('&*') if base_type == "void": addr_count = full_type_name.count('*') ...
903_D. Almost Difference
Let's denote a function <image> You are given an array a consisting of n integers. You have to calculate the sum of d(ai, aj) over all pairs (i, j) such that 1 ≤ i ≤ j ≤ n. Input The first line contains one integer n (1 ≤ n ≤ 200000) — the number of elements in a. The second line contains n integers a1, a2, ..., ...
```python from sys import stdin, stdout n = int(stdin.readline()) a = [int(i) for i in stdin.readline().split()] d = dict() ans, sm = 0, 0 for i in range(n): if a[i] not in d.keys(): d[a[i]] = 0 d[a[i]] += 1 ans += i * a[i] - sm if (a[i] + 1) in d.keys(): ans += 1 * d[a[i] + 1] if (a...
954_F. Runner's Problem
You are running through a rectangular field. This field can be represented as a matrix with 3 rows and m columns. (i, j) denotes a cell belonging to i-th row and j-th column. You start in (2, 1) and have to end your path in (2, m). From the cell (i, j) you may advance to: * (i - 1, j + 1) — only if i > 1, * (i, ...
```python from operator import itemgetter import sys input = sys.stdin.buffer.readline def _mul(A, B, MOD): C = [[0] * len(B[0]) for i in range(len(A))] for i in range(len(A)): for k in range(len(B)): for j in range(len(B[0])): C[i][j] = (C[i][j] + A[i][k] * B[k][j]) % MOD ...
9_E. Interesting Graph and Apples
Hexadecimal likes drawing. She has drawn many graphs already, both directed and not. Recently she has started to work on a still-life «interesting graph and apples». An undirected graph is called interesting, if each of its vertices belongs to one cycle only — a funny ring — and does not belong to any other cycles. A f...
```python def dfs(v, comp): used[v] = comp for u in graph[v]: if not used[u]: dfs(u, comp) n, m = map(int, input().split()) graph = [[] for i in range(n)] for i in range(m): v, u = map(int, input().split()) graph[v - 1].append(u - 1) graph[u - 1].append(v - 1) used = [0] * n nc...
p02548 AtCoder Beginner Contest 179 - A x B + C
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A \times B + C = N? Constraints * 2 \leq N \leq 10^6 * All values in input are integers. Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 3 Output 3 Input 100 ...
```python N = int(input()) ans = 0 for i in range(1, N): ans += (N - 1) // i print(ans) ```
p02679 AtCoder Beginner Contest 168 - ∙ (Bullet)
We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively. We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time. The i-th and j-th sardines (i \neq j) are on bad terms if and o...
```python from collections import defaultdict def gcd(a, b): return gcd(b, a%b) if b else a mod = 10 ** 9 + 7 N = int(input()) X = defaultdict(lambda: [0, 0]) # X = dict() x = 0 y = 0 z = 0 for i in range(N): a, b = map(int, input().split()) g = abs(gcd(a, b)) if a * b > 0: X[(abs(a) // g, abs...
p02807 Dwango Programming Contest 6th - Fusing Slimes
There are N slimes standing on a number line. The i-th slime from the left is at position x_i. It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}. Niwango will perform N-1 operations. The i-th operation consists of the following procedures: * Choose an integer k between 1 and N-i (inclusive) with equ...
```python n = int(input()) lst1 = list(map(int,input().split())) mod = 10**9+7 def pow(n, p): res = 1 while p > 0: if p % 2 == 0: n = n ** 2 % mod p //= 2 else: res = res * n % mod p -= 1 return res % mod fac = [1] for i in range(n-1): fac...
p02943 AtCoder Grand Contest 037 - Reversing and Concatenating
Takahashi has a string S of length N consisting of lowercase English letters. On this string, he will perform the following operation K times: * Let T be the string obtained by reversing S, and U be the string obtained by concatenating S and T in this order. * Let S' be some contiguous substring of U with length N, an...
```python def solve(n, k, s): u = s + s[::-1] t = min(u[i:i + n] for i in range(n + 1)) i, h = 0, t[0] for i, c in enumerate(t): if c != h: break j = i for _ in range(k - 1): j <<= 1 if j >= n: return h * n return h * j + t[i:i + n - j] n, k ...
p03080 ExaWizards 2019 - Red or Blue
There are N people numbered 1 to N. Each person wears a red hat or a blue hat. You are given a string s representing the colors of the people. Person i wears a red hat if s_i is `R`, and a blue hat if s_i is `B`. Determine if there are more people wearing a red hat than people wearing a blue hat. Constraints * 1 \l...
```python n = input() s = input() if s.count('R') > s.count('B') : print('Yes') else : print('No') ```
p03225 Tenka1 Programmer Contest - Equilateral
There are some coins in the xy-plane. The positions of the coins are represented by a grid of characters with H rows and W columns. If the character at the i-th row and j-th column, s_{ij}, is `#`, there is one coin at point (i,j); if that character is `.`, there is no coin at point (i,j). There are no other coins in t...
```python H,W=map(int,input().split()) S=[list(input()) for i in range(H)] table=[[0]*(H+W-1) for i in range(H+W-1)] for j in range(H): for i in range(W): if S[j][i]=='#': table[i+j][i-j+H-1]=1 yoko=[[0]*(H+W) for i in range(H+W-1)] for j in range(H+W-1): for i in range(1,H+W): y...
p03371 AtCoder Beginner Contest 095 - Half and Half
"Pizza At", a fast food chain, offers three kinds of pizza: "A-pizza", "B-pizza" and "AB-pizza". A-pizza and B-pizza are completely different pizzas, and AB-pizza is one half of A-pizza and one half of B-pizza combined together. The prices of one A-pizza, B-pizza and AB-pizza are A yen, B yen and C yen (yen is the curr...
```python a, b, c, x, y = map(int, input().split()) print(min(a*x+b*y, c*2*max(x,y), c*2*min(x,y)+abs(x-y)*(a if x>y else b))) ```
p03534 CODE FESTIVAL 2017 Final (Parallel) - Palindrome-phobia
Snuke has a string S consisting of three kinds of letters: `a`, `b` and `c`. He has a phobia for palindromes, and wants to permute the characters in S so that S will not contain a palindrome of length 2 or more as a substring. Determine whether this is possible. Constraints * 1 \leq |S| \leq 10^5 * S consists of `a`...
```python s=input() from collections import defaultdict d=defaultdict(int) for c in s: d[c]+=1 a,b,c=d["a"],d["b"],d["c"] mx=max(a,b,c) mn=min(a,b,c) #a,b,c = map(lambda x:x-mn, [a,b,c]) if mx-mn >=2: print("NO") else: print("YES") ```
p03694 AtCoder Beginner Contest 064 - Traveling AtCoDeer Problem
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts. There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses. Find the minimum distance to be traveled when AtCoDeer can start and ...
```python num = input() l = list(map(int, input().split())) print(max(l) - min(l)) ```
p03849 AtCoder Regular Contest 066 - Xor Sum
You are given a positive integer N. Find the number of the pairs of integers u and v (0≦u,v≦N) such that there exist two non-negative integers a and b satisfying a xor b=u and a+b=v. Here, xor denotes the bitwise exclusive OR. Since it can be extremely large, compute the answer modulo 10^9+7. Constraints * 1≦N≦10^{18...
```python n=int(input()) d=dict() def get(n): if(n==1):return 1 if(n==0):return 0 if(n in d.keys()):return d[n] if(n%2==0): d[n]=2*get(n//2)+get(n//2-1) else: d[n]=2*get(n//2)+get(n//2+1) d[n]%=(10**9+7) return d[n] def check(u,v,n): for a in range(n+1): b=u ^ a ...
p04015 AtCoder Regular Contest 060 - Tak and Cards
Tak has N cards. On the i-th (1 \leq i \leq N) card is written an integer x_i. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection? Constraints * 1 \leq N \leq 50 * 1 \leq A \leq 50 * 1 \leq x_...
```python n,a=map(int,input().split()) X=list(map(int,input().split())) dp=[[[0]*(sum(X)+1) for _ in range(n+1)] for _ in range(n+1)] dp[0][0][0]=1 for i in range(1,n+1): #x_1,x_2...x_n for k in range(i): #k枚数選ぶ for s in range(sum(X)+1): #合計 if dp[i-1][k][s]: dp[i][k+1][s+X[i-1]]+=dp[i-1][k][s]...
p00100 Sale Result
There is data on sales of your company. Your task is to write a program which identifies good workers. The program should read a list of data where each item includes the employee ID i, the amount of sales q and the corresponding unit price p. Then, the program should print IDs of employees whose total sales proceeds ...
```python while True: try: n=int(input()) except: break if n==0: break data={} staff=[] for i in range(n): spam=list(map(int,input().split())) if spam[0] in data.keys(): data[spam[0]]+=spam[1]*spam[2] else: data[spam[0]]=spa...