name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
285_B. Find Marble
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position s. Then he performs some (pos...
```python from collections import Counter import string import math import sys def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arrber_of_variables>=2: return map(int,sys.stdin...
30_B. Codeforces World Finals
The king Copa often has been reported about the Codeforces site, which is rapidly getting more and more popular among the brightest minds of the humanity, who are using it for training and competing. Recently Copa understood that to conquer the world he needs to organize the world Codeforces tournament. He hopes that a...
```python from itertools import * import sys m=[32,29,32,31,32,31,32,32,31,32,31,32] s,t=[map(int,input().split('.')) for _ in range(2)] g=False a,b,c=s for d,e,f in permutations(t): g|=b<13 and e<13 and a<m[b-1]+(b==2)*(c%4==0)and d<m[e-1]+(e==2)*(f%4==0)and(c-f>18 or(c-f==18 and(b>e or(b==e and(a>=d))))) print(["NO"...
3_B. Lorry
A group of tourists is going to kayak and catamaran tour. A rented lorry has arrived to the boat depot to take kayaks and catamarans to the point of departure. It's known that all kayaks are of the same size (and each of them occupies the space of 1 cubic metre), and all catamarans are of the same size, but two times b...
```python n, v = map(int, input().split()) a = [] b = [] for i in range(n): typ, carry = map(int, input().split()) if typ == 1: a.append([carry, i + 1]) else: b.append([carry, i + 1]) a.sort(reverse=True) b.sort(reverse=True) for i in range(1, len(a)): a[i][0] += a[i - 1][0] for i in ra...
471_C. MUH and House of Cards
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev decided to build a house of cards. For that they've already found a hefty deck of n playing cards. Let's describe the house they want to make: 1. The house consists of some non-zero number of floors. 2. Each ...
```python print((lambda n: len([1 for x in range(1, int((-1 + (24 * n + 25) ** 0.5) / 6) + 1) if not (n - 2 * x) % 3]))(int(input()))) ```
495_D. Obsessive String
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from...
```python def main(): s, t = input(), input() n, m = len(s), len(t) t = '$'.join((t, s)) p = [0] k = 0 for i in range(1, n + m + 1): while k and t[k] != t[i]: k = p[k - 1] if t[k] == t[i]: k += 1 p.append(k) ans = [0] * n sums = [0] * (n + ...
51_B. bHTML Tables Analisys
In this problem is used an extremely simplified version of HTML table markup. Please use the statement as a formal document and read it carefully. A string is a bHTML table, if it satisfies the grammar: TABLE ::= <table>ROWS</table> ROWS ::= ROW | ROW ROWS ROW ::= <tr>CELLS</tr> ...
```python #amros import sys R=str.replace s=R(R(R(R(R(''.join(sys.stdin.readlines()),'\n',''),'</tr>',''),'<tr>',''),'><',' '),'>','').split()[1:] def f(k): r=0;a=[] while s[0]!='/table': if s[0]=='table': s.pop(0);a+=f(k+1) else:r+=s[0]=='td';s.pop(0) s.pop(0) return[r]+a print(' '.join(map(str,sorted(f(1))...
546_C. Soldier and Cards
Two bored soldiers are playing card war. Their card deck consists of exactly n cards, numbered from 1 to n, all values are different. They divide cards between them in some manner, it's possible that they have different number of cards. Then they play a "war"-like card game. The rules are following. On each turn a fi...
```python '''input 4 2 1 3 2 4 2 ''' n = int(input()) a = tuple(map(int, input().split()))[1:] b = tuple(map(int, input().split()))[1:] c = 0 s = set() res = 0 while (a, b) not in s: if not a: res = 2 break if not b: res = 1 break s.add((a, b)) x, y = a[0], b[0] ...
594_C. Edo and Magnets
Edo has got a collection of n refrigerator magnets! He decided to buy a refrigerator and hang the magnets on the door. The shop can make the refrigerator with any size of the door that meets the following restrictions: the refrigerator door must be rectangle, and both the length and the width of the door must be posit...
```python from sys import* # def check(u, d, l, r): used = [pointsx[i][1] for i in range(l)] used += [pointsx[-1 - i][1] for i in range(r)] used += [pointsy[i][1] for i in range(u)] used += [pointsy[-1 - i][1] for i in range(d)] if len(set(used)) > k: return DOHERA dx = pointsx[-1 - r][0...
616_A. Comparing Two Long Integers
You are given two very long integers a, b (leading zeroes are allowed). You should check what number a or b is greater or determine that they are equal. The input size is very large so don't use the reading of symbols one by one. Instead of that use the reading of a whole line or token. As input/output can reach huge...
```python a = input() b = input() if len(a)>len(b): gap = len(a)-len(b) new = '' for _ in range(gap): new+='0' b = new + b elif len(b)>len(a): gap = len(b) - len(a) new = '' for _ in range(gap): new+='0' a = new + a for i in range(0,len(a)): if(a[i]>b[i]): pri...
635_B. Island Puzzle
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one o...
```python n=int(input()) a=input().split() b=input().split() a.remove('0') b.remove('0') k=a.index(b[0]) a=a[k:]+a[:k] if a==b: print('YES') else: print('NO') # Made By Mostafa_Khaled ```
664_A. Complicated GCD
Greatest common divisor GCD(a, b) of two positive integers a and b is equal to the biggest integer d such that both integers a and b are divisible by d. There are many efficient algorithms to find greatest common divisor GCD(a, b), for example, Euclid algorithm. Formally, find the biggest integer d, such that all int...
```python a,b=map(int,input().split()) print(a) if a==b else print(1) ```
688_D. Remainders Game
Today Pari and Arya are playing a game called Remainders. Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winnin...
```python from math import * n,k=map(int,input().split()) arr=list(map(int,input().split())) flag=0 if(k==1): print('Yes') else: arr1=[] temp=k for i in range(2,k+1): if(temp%i==0): cnt=0 while(temp%i==0): cnt+=1 temp=temp//i ar...
710_C. Magic Odd Square
Find an n × n matrix with different numbers from 1 to n2, so the sum in each row, column and both main diagonals are odd. Input The only line contains odd integer n (1 ≤ n ≤ 49). Output Print n lines with n integers. All the integers should be different and from 1 to n2. The sum in each row, column and both main di...
```python n = int(input()) if n==1: print(1) exit() odd = 1 evn = 2 table = [[0 for i in range(n)] for i in range(n)] #(x,y) x row, y col for x in range(n): for y in range(n): x1 = min(x, n-1-x) if y < (n - 1)/2-x1 or y > (n - 1)/2+x1: #even con table[x][y] = ev...
731_C. Socks
Arseniy is already grown-up and independent. His mother decided to leave him alone for m days and left on a vacation. She have prepared a lot of food, left some money and washed all Arseniy's clothes. Ten minutes before her leave she realized that it would be also useful to prepare instruction of which particular clo...
```python from collections import defaultdict, deque from sys import stdin, stdout def dfs(visited, node_idx, graph, color_count, sock_colors): visited[node_idx] = True color_count[sock_colors[node_idx]] += 1 count = 1 for nbor_idx in graph[node_idx]: if not visited[nbor_idx]: coun...
755_E. PolandBall and White-Red graph
PolandBall has an undirected simple graph consisting of n vertices. Unfortunately, it has no edges. The graph is very sad because of that. PolandBall wanted to make it happier, adding some red edges. Then, he will add white edges in every remaining place. Therefore, the final graph will be a clique in two colors: white...
```python def PolandBall(n, k): # condiciones que no cumplen con los requisitos if n < 4 or k > 3 or k == 1 or (k == 2 and n == 4): print('-1') return # si k=2 if k == 2: print(n-1) for i in range(1, n): print(str(i)+' '+str(i+1)) return # si k=...
801_B. Valued Keys
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1...
```python x = input() y = input() z = '' for i in range(len(x)): if x[i] < y[i]: print("-1") exit(0) else: z = z + y[i] print(z) ```
847_D. Dog Show
A new dog show on TV is starting next week. On the show dogs are required to demonstrate bottomless stomach, strategic thinking and self-preservation instinct. You and your dog are invited to compete with other participants and naturally you want to win! On the show a dog needs to eat as many bowls of dog food as poss...
```python # using the min-heap from heapq import heappush,heappop bowels,Time = map(int,input().split()) myLine = [-int(b) for b in input().split()] gulp = []; eat = 0 for i in range(1,min(bowels+1,Time)): # redundant (now that i look at it. the min does that already) if i >= Time: break while gulp...
868_F. Yet Another Minimization Problem
You are given an array of n integers a1... an. The cost of a subsegment is the number of unordered pairs of distinct indices within the subsegment that contain equal elements. Split the given array into k non-intersecting non-empty subsegments so that the sum of their costs is minimum possible. Each element should be p...
```python import sys input = sys.stdin.readline n, m = map(int, input().split()) a = [0]+list(map(int, input().split())) buc = [0]*(n+1) dp_p = [n*(n-1)//2]*(n+1) dp_c = [0]*(n+1) dp_p[0] = 0 buc[a[1]] = 1 L = R = 1 ans = 0 def cal(l, r): global L, R, ans while L < l: ans += 1-buc[a[L]] buc[a[...
894_C. Marco and GCD Sequence
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time. When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be...
```python from math import gcd m = int(input()) s = [int(i) for i in input().split()] gc = s[0] for i in range(0,m): gc = gcd(gc,s[i]) if gc not in s: print(-1) else: print(2*m-1) ans = [s[0]]*(2*m-1) cur = 1 for i in range(2,2*m-1,2): ans[i] = s[cur] cur += 1 print(*ans) ""...
964_B. Messages
There are n incoming messages for Vasya. The i-th message is going to be received after ti minutes. Each message has a cost, which equals to A initially. After being received, the cost of a message decreases by B each minute (it can become negative). Vasya can read any message after receiving it at any moment of time. ...
```python n,a,b,c,t = map(int,input().split()) arr = list() arr = map(int,input().split()) Sum = int(0) for num in arr: Sum += t - num ans = n * a if b >= c: print(ans) else: print(ans + Sum * int(c - b)) ```
991_C. Candies
After passing a test, Vasya got himself a box of n candies. He decided to eat an equal amount of candies each morning until there are no more candies. However, Petya also noticed the box and decided to get some candies for himself. This means the process of eating candies is the following: in the beginning Vasya choos...
```python import sys import math n = int(input()) l = 1 r = 2*n while(l < r): candies = n numeaten = 0 k = (l+r)//2 # print(k) while(candies > 0): if candies > k: numeaten += k candies -= k else: numeaten += candies break c = ...
p02618 Introduction to Heuristics Contest - AtCoder Contest Scheduling
AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to sched...
```python from random import randint for i in range(365): print(randint(1,26)) ```
p02749 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - ThREE
We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i. Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition: * For every pair of vertices (i, j), if the distance betw...
```python import sys sys.setrecursionlimit(10 ** 6) n = int(input()) edge = [[] for i in range(n)] ans = [-1] * n odd = [] even =[] nums = [[],[],[]] for i in range(1,n+1): nums[i % 3].append(i) def dfs(x, last = -1, d = 0): if d % 2 == 0: even.append(x) else: odd.append(x) for nxt in edge[x]: ...
p02884 AtCoder Beginner Contest 144 - Fork in the Road
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N. Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each roo...
```python N, M = map(int, input().split()) G = [[] for _ in range(N)] rG = [[] for _ in range(N)] for _ in range(M): s, t = map(int, input().split()) G[s-1].append(t-1) E = [0]*N for v in range(N-1)[::-1]: n = len(G[v]) for nv in G[v]: E[v]+=(E[nv]+1)*(1/n) ans = E[0] for v in range(N-1): if...
p03019 AtCoder Grand Contest 034 - Tests
Takahashi and Aoki will take N exams numbered 1 to N. They have decided to compete in these exams. The winner will be determined as follows: * For each exam i, Takahashi decides its importance c_i, which must be an integer between l_i and u_i (inclusive). * Let A be \sum_{i=1}^{N} c_i \times (Takahashi's score on Exa...
```python import sys,heapq,time from collections import deque,defaultdict printn = lambda x: sys.stdout.write(x) inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) DBG = True and False def ddprint(x): if DBG: print(x) n,x = inm() blu = [] p...
p03159 AISing Programming Contest 2019 - Attack to a Tree
The server in company A has a structure where N devices numbered 1, 2, ..., N are connected with N - 1 cables. The i-th cable connects Device U_i and Device V_i. Any two different devices are connected through some number of cables. Each device v (1 \leq v \leq N) has a non-zero integer A_v, which represents the follo...
```python import sys readline = sys.stdin.readline inf = 10**18+3 def merge(d1a, d2a, d1b, d2b): la = len(d1a) lb = len(d1b) k = la+lb res1 = [inf]*k res2 = [inf]*k for i in range(la): for j in range(lb): res1[i+j] = min(res1[i+j], d1a[i]+d1b[j], d1a[i]+d2b[j], d2a[i]+d1b[j]...
p03302 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - F
You are given two integers a and b. Determine if a+b=15 or a\times b=15 or neither holds. Note that a+b=15 and a\times b=15 do not hold at the same time. Constraints * 1 \leq a,b \leq 15 * All values in input are integers. Input Input is given from Standard Input in the following format: a b Output If a+b=15,...
```python a,b = list(map(int,input().split())) if a*b == 15: print("*") elif a+b == 15: print("+") else: print("x") ```
p03780 AtCoder Beginner Contest 056 - No Need
AtCoDeer the deer has N cards with positive integers written on them. The number on the i-th card (1≤i≤N) is a_i. Because he loves big numbers, he calls a subset of the cards good when the sum of the numbers written on the cards in the subset, is K or greater. Then, for each card i, he judges whether it is unnecessary...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) a = sorted(a)[::-1] ans = n sm = 0 for i in range(n): if sm + a[i] < k: sm += a[i] else: ans = min(ans, n - i - 1) print(ans) ```
p00040 Affine Cipher
One of the simple ciphers is the affine cipher. First, replace the letters a to z with the numbers a = 0, b = 1, c = 2, ..., x = 23, y = 24, z = 25 and 0 to 25. Then replace the original alphabet with the following formula. $ F (\ gamma) = (\ alpha \ cdot \ gamma + \ beta) $ mod $ 26 $ However, mod 26 represents the ...
```python z='abcdefghijklmnopqrstuvwxyz' for _ in[0]*int(input()): e=input() for i in range(1,26,2): for j in range(26): a='' for c in e: if c in z:a+=z[(z.index(c)*i+j)%26] else:a+=c if'that'in a or'this'in a:print(a);break ```
p00501 Signboard
problem JOI decided to make a signboard for the store. There are N old signboards with letters written at equal intervals. JOI makes a sign by erasing some letters from the old sign. I want the remaining characters to be the name of the store, and the remaining characters to be evenly spaced. Signs must be made from ...
```python n = int(input()) name = input() length = len(name) def check(ss): ind = 0 end = len(ss) while ind < end: while ind < end and ss[ind] != name[0]: ind += 1 for i in range(100): j1 = ind j2 = 0 while j1 < end and j2 < length and ss[j1] == name[j2]: j1 += i ...
p00685 Board Arrangements for Concentration Games
You have to organize a wedding party. The program of the party will include a concentration game played by the bride and groom. The arrangement of the concentration game should be easy since this game will be played to make the party fun. We have a 4x4 board and 8 pairs of cards (denoted by `A' to `H') for the concent...
```python # AOJ 1103: Board Arrangements for Concentration Gam... # Python3 2018.7.14 bal4u def combi(k): global ans if k == 9: ans += 1 return for y in range(4): for x in range(4): if arr[y][x]: continue arr[y][x] = k for i in range(4): x2, y2 = x + a[i<<1], y + a[(i<<1)+1] if x2 < 0 or x2 >...
p00827 The Balance
Ms. Iyo Kiffa-Australis has a balance and only two kinds of weights to measure a dose of medicine. For example, to measure 200mg of aspirin using 300mg weights and 700mg weights, she can put one 700mg weight on the side of the medicine and three 300mg weights on the opposite side (Figure 1). Although she could put fou...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in ...
p00958 Parallel Lines
Problem B Parallel Lines Given an even number of distinct planar points, consider coupling all of the points into pairs. All the possible couplings are to be considered as long as all the given points are coupled to one and only one other point. When lines are drawn connecting the two points of all the coupled point ...
```python m = int(input()) P = [list(map(int, input().split())) for i in range(m)] s = set() for i in range(m): xi, yi = P[i] for j in range(i+1, m): xj, yj = P[j] u = xj - xi; v = yj - yi for x, y in s: if x * v == y * u: break else: s.add...
p01227 Country Road
This is a story in a depopulated area. In this area, houses are sparsely built along a straight road called Country Road. Until now, there was no electricity in this area, but this time the government will give us some generators. You can install the generators wherever you like, but in order for electricity to be supp...
```python NUM=int(input()) for sect in range(NUM): n,k=list(map(int,input().strip().split())) x=list(map(int,input().strip().split())) x.sort() diff=[] for i in range(1,len(x)): diff.append(x[i]-x[i-1]) diff.sort(reverse=True) s=sum(diff[:k-1]) print(max(x)-min(x)-s) `...
p01361 Dungeon Quest II
The cave, called "Mass of Darkness", had been a agitating point of the evil, but the devil king and all of his soldiers were destroyed by the hero and the peace is there now. One day, however, the hero was worrying about the rebirth of the devil king, so he decided to ask security agency to patrol inside the cave. Th...
```python from bisect import bisect from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): cA = ord('A') ds = "LURD" hi, hm = map(int, readline().split()) if hi == hm == 0: return False R, C = map(int, readline().split()) A = [l...
p01543 marukaite
Taro is an elementary school student and has graffiti on the back of the leaflet. At one point, Taro came up with the next game. * Write n × n grid-like squares. * The initial state of each square is either marked or unmarked. * Erase or write these circles so that there is always exactly one circle no matter which co...
```python # -*- coding: utf-8 -*- 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 ...
p01843 Campaign
E-Election campaign Problem Statement You are a supporter of Mr. X, a candidate for the next election. Mr. X is planning a street speech in front of the station and intends to give a speech in a place that can be seen by as many voters as possible. The front of the station is given as a two-dimensional plane with $ ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def cross3(p0, p1, q0): return (p1[0] - p0[0])*(q0[1] - p0[1]) - (p1[1] - p0[1])*(q0[0] - p0[0]) def cross_point(p0, p1, q0, q1): x0, y0 = p0; x1, y1 = p1 x2, y2 = q0; x3, y3 = q1 dx0 = x1 - x0 dy0 = y1 - y0 dx1 = x3 - x...
p02125 OOllOll
Problem Let $ f (x) $ be the sum of each digit when the non-negative integer $ x $ is expressed in binary. Given a positive integer $ N $, output the largest of $ f (0) $, $ f (1) $, ..., $ f (N) $. Example of calculating the function $ f (5) $: When 5 is expressed in binary, it is 101 and the sum of each digit is 1...
```python n = int(input()) ans = 0 tmp = 1 while tmp <= n+1 : tmp *= 2 ans += 1 print(ans-1) ```
p02265 Doubly Linked List
Your task is to implement a double linked list. Write a program which performs the following operations: * insert x: insert an element with key x into the front of the list. * delete x: delete the first element which has the key of x from the list. If there is not such element, you need not do anything. * deleteFirst...
```python from collections import deque a = int(input()) dl = deque() for i in range(a): o = input().split() if o[0] == 'delete': try: dl.remove(o[1]) except ValueError: pass elif o[0] == 'deleteFirst': dl.popleft() elif o[0] == 'deleteLast': dl....
p02413 Spreadsheet
Your task is to perform a simple table calculation. Write a program which reads the number of rows r, columns c and a table of r × c elements, and prints a new table, which includes the total sum for each row and column. Constraints * 1 ≤ r, c ≤ 100 * 0 ≤ an element of the table ≤ 100 Input In the first line, two ...
```python r,c = map(int,input().split()) a =[] for i in range(r) : a.append(list(map(int,input().split()))) a[i].append(sum(a[i])) b = list(map(sum,zip(*a))) for i in range(r) : print(*a[i]) print(*b) ```
1044_A. The Tower is Going Home
On a chessboard with a width of 10^9 and a height of 10^9, the rows are numbered from bottom to top from 1 to 10^9, and the columns are numbered from left to right from 1 to 10^9. Therefore, for each cell of the chessboard you can assign the coordinates (x,y), where x is the column number and y is the row number. Ever...
```python n,m=[int(x) for x in input().split()] v=[] h=[] for i in range(n): x=int(input()) v.append(x) for i in range(m): x,y,z=[int(x) for x in input().split()] if x==1: h.append(y) h.sort() v.sort() m=len(h) n=len(v) if n==0 or v[n-1]!=1000000000: v.append(1000000000) n+=1 mina=999999...
1066_F. Yet another 2D Walking
Maksim walks on a Cartesian plane. Initially, he stands at the point (0, 0) and in one move he can go to any of four adjacent points (left, right, up, down). For example, if Maksim is currently at the point (0, 0), he can go to any of the following points in one move: * (1, 0); * (0, 1); * (-1, 0); * (0, -...
```python def dista(a, b): return abs(lista[a][0]-lista[b][0]) + abs(lista[a][1]-lista[b][1]) lista = [] ne = 0 n = int(input()) dist = [0] * (n+1) lista.append((0, 0)) for _ in range(n): x, y = map(int, input().split()) lista.append((x, y)) lista = sorted(lista, key= lambda x: min(x)) lista = sorted(lista, key= l...
1089_J. JS Minification
International Coding Procedures Company (ICPC) writes all its code in Jedi Script (JS) programming language. JS does not get compiled, but is delivered for execution in its source form. Sources contain comments, extra whitespace (including trailing and leading spaces), and other non-essential features that make them qu...
```python def main(): t = int(input()) reserved = set(input().split()) lines = int(input()) code = '' for i in range(lines): code += input() + '\n' def is_word(suspect): if suspect[0].isdigit(): return False for x in suspect: if (not x.isalpha()) and (not x in {'_', '$'}) and (not x.isdigit()): ret...
1108_D. Diverse Garland
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' — colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
```python n = int(input()) w = list(input()) count = 0 for i in range(1,len(w)): if w[i] != w[i-1]: continue else: if i != len(w) - 1: next = ['R','G','B'] next.remove(w[i-1]) if w[i+1] in next: next.remove(w[i+1]) w[i] = next[0] count += 1 else: next = ['R','G','B'] next.remove(w[i-1]) ...
1156_B. Ugly Pairs
You are given a string, consisting of lowercase Latin letters. A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbou...
```python T = int(input()) for _ in range(T): s = input() d = {} for i in s: d[i] = d.get(i, 0) + 1 k = sorted(list(d.keys())) n = len(k) if n == 2: if abs(ord(k[0]) - ord(k[1])) == 1: ans = "No answer" else: ans = s elif n == 3: if abs...
1178_E. Archaeology
Alice bought a Congo Prime Video subscription and was watching a documentary on the archaeological findings from Factor's Island on Loch Katrine in Scotland. The archaeologists found a book whose age and origin are unknown. Perhaps Alice can make some sense of it? The book contains a single string of characters "a", "...
```python s=input() n=len(s) b=[] for j in s: b.append(j) x=[] y=[] j=0 i=n-1 while(j<i): if b[j]==b[i]: if i!=j: x.append(b[j]) y.append(b[i]) else: x.append(b[j]) i+=-1 j+=1 elif b[j]==b[i-1]: if (i-1) != j: x.append(b...
1196_D2. RGB Substring (hard version)
The only difference between easy and hard versions is the size of the input. You are given a string s consisting of n characters, each character is 'R', 'G' or 'B'. You are also given an integer k. Your task is to change the minimum number of characters in the initial string s so that after the changes there will be ...
```python import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def i...
1213_F. Unstable String Sort
Authors have come up with the string s consisting of n lowercase Latin letters. You are given two permutations of its indices (not necessary equal) p and q (both of length n). Recall that the permutation is the array of length n which contains each integer from 1 to n exactly once. For all i from 1 to n-1 the followi...
```python import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify from copy import deepcopy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin....
1237_B. Balanced Tunnel
Consider a tunnel on a one-way road. During a particular day, n cars numbered from 1 to n entered and exited the tunnel exactly once. All the cars passed through the tunnel at constant speeds. A traffic enforcement camera is mounted at the tunnel entrance. Another traffic enforcement camera is mounted at the tunnel ex...
```python n = int(input()) pre = map(int, input().split()) post = map(int, input().split()) pre_map = {} for i, p in enumerate(pre): pre_map[p] = i post_ = [] # ordered 0, 1, 2, ... n-1 for p in post: post_.append(pre_map[p]) #print(post_) current_min = n ans = 0 for p in post_[::-1]: if current_min < p: ...
1255_A. Changing Volume
Bob watches TV every day. He always sets the volume of his TV to b. However, today he is angry to find out someone has changed the volume to a. Of course, Bob has a remote control that can change the volume. There are six buttons (-5, -2, -1, +1, +2, +5) on the control, which in one press can either increase or decrea...
```python """ Author : thekushalghosh Team : CodeDiggers """ import sys,math input = sys.stdin.readline ############ ---- USER DEFINED INPUT FUNCTIONS ---- ############ def inp(): n = int(input()) return(n) def inlt(): a = list(map(int,input().split())) return(a) def insr(): s = input() ...
1278_F. Cards
Consider the following experiment. You have a deck of m cards, and exactly one card is a joker. n times, you do the following: shuffle the deck, take the top card of the deck, look at it and return it into the deck. Let x be the number of times you have taken the joker out of the deck during this experiment. Assuming ...
```python class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] ...
1299_C. Water Balance
There are n water tanks in a row, i-th of them contains a_i liters of water. The tanks are numbered from 1 to n from left to right. You can perform the following operation: choose some subsegment [l, r] (1≤ l ≤ r ≤ n), and redistribute water in tanks l, l+1, ..., r evenly. In other words, replace each of a_l, a_{l+1},...
```python # -*- coding: utf-8 -*- 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 ...
1322_A. Unusual Competitions
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not. The teacher gave Dmitry's class a very strange task — she asked every student...
```python n=int(input()) l=input() e=[] p=0 for i in l: if i=='(': p+=1 e.append(p) else: p-=1 e.append(p) if e[-1]!=0: print(-1) else: ans=0 z=0 for i in range(n): if e[i]<0: z+=1 else: if z>0: ans+=z+1 ...
1383_B. GameGame
Koa the Koala and her best friend want to play a game. The game starts with an array a of length n consisting of non-negative integers. Koa and her best friend move in turns and each have initially a score equal to 0. Koa starts. Let's describe a move in the game: * During his move, a player chooses any element of...
```python import sys input=sys.stdin.readline for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) base=0 for A in a: base^=A if base==0: print("DRAW") else: m=base.bit_length()-1 count=0 for A in a: count+=(A>>m &1==...
1404_B. Tree Tag
Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first mov...
```python diameter = 0 def dfs(u, tree, depth): global diameter length = 0 level[u] = depth isCheck[u] = True for vertex in tree[u]: if isCheck[vertex] != True: isCheck[vertex] = True cur = dfs(vertex, tree, depth + 1) + 1 diameter = max(diameter, cur + le...
1425_H. Huge Boxes of Animal Toys
Chaneka has a hobby of playing with animal toys. Every toy has a different fun value, a real number. Chaneka has four boxes to store the toys with specification: * The first box stores toys with fun values in range of (-∞,-1]. * The second box stores toys with fun values in range of (-1, 0). * The third box s...
```python for k in range(int(input())): a, b, c, d = list(map(int, input().split())) s = '' if (a+b)%2==1 and (a > 0 or d > 0): s += 'Ya ' else: s += 'Tidak ' if (a+b)%2 == 1 and (b > 0 or c > 0): s += 'Ya ' else: s += 'Tidak ' if (a+b)%2 == 0 and (b > 0 or ...
1447_E. Xor Tree
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way: * Consider a graph on k nodes, with numbers from b_1 to b_k written on them. * For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j,...
```python import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def costs(l, bit = 32): if len(l) <= 2: return 0 left = [] right = [] for el in l: if el & (1<<bit): left.append(el) else: right.append(el) return min(cos...
1472_E. Correct Placement
Polycarp has invited n friends to celebrate the New Year. During the celebration, he decided to take a group photo of all his friends. Each friend can stand or lie on the side. Each friend is characterized by two values h_i (their height) and w_i (their width). On the photo the i-th friend will occupy a rectangle h_i ...
```python from collections import deque, defaultdict, Counter import sys #import numpy as np mod = 10**9 + 7 #mod =998244353 def input(): return sys.stdin.readline().rstrip() def sol(): #start coding here... #print("Hello CodeForces!") #bad implemention, what a shame... n = int(input()) Fri...
1498_F. Christmas Game
Alice and Bob are going to celebrate Christmas by playing a game with a tree of presents. The tree has n nodes (numbered 1 to n, with some node r as its root). There are a_i presents are hanging from the i-th node. Before beginning the game, a special integer k is chosen. The game proceeds as follows: * Alice begin...
```python import sys from sys import stdin from collections import deque n,k = map(int,stdin.readline().split()) N,K = n,k lis = [ [] for i in range(N) ] for i in range(N-1): x,y = map(int,stdin.readline().split()) x -= 1 y -= 1 lis[x].append(y) lis[y].append(x) a = list(map(int,stdin.readline()...
1520_E. Arranging The Sheep
You are playing the game "Arranging The Sheep". The goal of this game is to make the sheep line up. The level in the game is described by a string of length n, consisting of the characters '.' (empty space) and '*' (sheep). In one move, you can move any sheep one square to the left or one square to the right, if the co...
```python t=int(input()) for i in range(t): n=int(input()) s=input();y=0;b=[] for i in range(n): if s[i]=='*':y+=1;b.append(i) x=y//2 if len(b)==n or len(b)==0 or len(b)==1 : print(0) else: moves=0 for i in range(len(b)): moves+=abs(abs(b[x]-b[i]-1)-abs(x-i-1...
176_A. Trading Business
To get money for a new aeonic blaster, ranger Qwerty decided to engage in trade for a while. He wants to buy some number of items (or probably not to buy anything at all) on one of the planets, and then sell the bought items on another planet. Note that this operation is not repeated, that is, the buying and the sellin...
```python n,m,k = [int(s) for s in input().split()] BuyingPrice = [] SellingPrice = [] Number_of_items = [] for i in range(n): input() x = [] y = [] z = [] for j in range(m): a,b,c = [int(s) for s in input().split()] x.append(a) y.append(b) z.append(c) BuyingPri...
21_C. Stripe 2
Once Bob took a paper stripe of n squares (the height of the stripe is 1 square). In each square he wrote an integer number, possibly negative. He became interested in how many ways exist to cut this stripe into three pieces so that the sum of numbers from each piece is equal to the sum of numbers from any other piece,...
```python n = int(input()) lis = list(map(int,input().split())) pre=[0]*(n+1) for i in range(1,n+1): pre[i]=pre[i-1]+lis[i-1] if pre[-1]%3: print(0) else: s=pre[-1]//3 ans=t=0 for i in range(1,n): if pre[i]==2*s: ans+=t if pre[i]==s: t+=1 print(ans) ...
33_C. Wonderful Randomized Sum
Learn, learn and learn again — Valera has to do this every day. He is studying at mathematical school, where math is the main discipline. The mathematics teacher loves her discipline very much and tries to cultivate this love in children. That's why she always gives her students large and difficult homework. Despite th...
```python from sys import stdin n = int(stdin.readline()) nums = [int(x) for x in stdin.readline().split()] total = sum(nums)*-1 best = 0 left = 0 right = 0 current = 0 while right < n: while current >= 0 and right < n: current += nums[right] best = max(best,current) right += 1 wh...
407_B. Long Path
One day, little Vasya found himself in a maze consisting of (n + 1) rooms, numbered from 1 to (n + 1). Initially, Vasya is at the first room and to get out of the maze, he needs to get to the (n + 1)-th one. The maze is organized as follows. Each room of the maze has two one-way portals. Let's consider room number i (...
```python ###### ### ####### ####### ## # ##### ### ##### # # # # # # # # # # # # # ### # # # # # # # # # # # # # ### ###### ######### # # # # ...
479_C. Exams
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
```python n = int(input()) listd = [] res = 0 for i in range(n): listd.append(tuple(map(int, input().split()))) listd.sort() for a, b in listd: res = b if res<=b else a print(res) ```
501_C. Misha and Forest
Let's define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the secon...
```python from collections import defaultdict def main(): n = int(input()) bydegree = defaultdict(set) bys = defaultdict(set) l = [] for i in range(n): degree, s = map(int, input().split()) bydegree[degree].add(i) bys[s].add(i) l.append((degree, s)) res = [] ...
527_A. Playing with Paper
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm × b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t...
```python import operator as op import re import sys from bisect import bisect, bisect_left, insort, insort_left from collections import Counter, defaultdict, deque from copy import deepcopy from decimal import Decimal from functools import reduce from itertools import ( accumulate, combinations, combinations_with_...
552_D. Vanya and Triangles
Vanya got bored and he painted n distinct points on the plane. After that he connected all the points pairwise and saw that as a result many triangles were formed with vertices in the painted points. He asks you to count the number of the formed triangles with the non-zero area. Input The first line contains integer ...
```python import sys from math import gcd from collections import defaultdict input=sys.stdin.readline n=int(input()) p=[list(map(int,input().split())) for i in range(n)] ans=0 for xi,yi in p: angle=defaultdict(int) for x,y in p: if xi==x and yi==y: continue x-=xi;y-=yi if x<...
579_D. "Or" Game
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR. Find the maximum possible value of <image> after performing at most k operations optimally. I...
```python n, k, x = map(int, input().split()) A = list(map(int, input().split())) L, R = [0]*(n+1), [0]*(n+1) for i in range(n): L[i+1] = A[i] | L[i] for i in range(n-1, -1, -1): R[i] = A[i] | R[i+1] x = x**k ans = 0 for i in range(n): ans = max(ans, L[i] | (A[i]*x) | R[i+1]) print(ans) ```
600_C. Make Palindrome
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in th...
```python import sys input=sys.stdin.readline s=input().rstrip() n=len(s) ans=[""]*n c={} for i in range(n): c[s[i]]=c.get(s[i],0)+1 idx=0 l=[] for i in range(26): al=chr(ord("a")+i) if al in c: while c[al]-2>=0: ans[idx]=ans[n-1-idx]=al c[al]-=2 idx+=1 if...
644_B. Processing Queries
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct. When a query appears server may react in three possible ways: 1. If server is free and...
```python import queue n, b = list(map(int, input().split())) class Task: def __init__(self, time: int, duration: int, index: int) -> None: super().__init__() self.time = time self.duration = duration self.index = index remaining = queue.Queue() running = False finish_time = 0...
671_B. Robin Hood
We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor. There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to t...
```python import sys inp = sys.stdin.read().splitlines() n,k = list(map(int,inp[0].split())) lst = list(map(int,inp[1].split())) lst.sort() total = sum(lst) lower = int(total/n) nupper = total%n if nupper == 0: upper = lower; else: upper = lower+1; nlower = n - nupper; i = 0; while i<n and lst[i]<lower: i+=1 low1...
739_B. Alyona and a tree
Alyona has a tree with n vertices. The root of the tree is the vertex 1. In each vertex Alyona wrote an positive integer, in the vertex i she wrote ai. Moreover, the girl wrote a positive integer to every edge of the tree (possibly, different integers on different edges). Let's define dist(v, u) as the sum of the inte...
```python #!/usr/bin/env python3 import sys import threading from bisect import * #def ri(): # return map(int, input().split()) def dfs(v, d, c, w): d += 1 dist[d] = w[v] + dist[d-1] add[d] = 0 for i in c[v]: dfs(i, d, c, w) x = bisect_left(dist, dist[d] - a[v], 0, d) add[x-1] -= ...
762_A. k-th divisor
You are given two integers n and k. Find k-th smallest divisor of n, or report that it doesn't exist. Divisor of n is any such natural number, that n can be divided by it without remainder. Input The first line contains two integers n and k (1 ≤ n ≤ 1015, 1 ≤ k ≤ 109). Output If n has less than k divisors, output ...
```python # # Yet I'm feeling like # There is no better place than right by your side # I had a little taste # And I'll only spoil the party anyway # 'Cause all the girls are looking fine # But you're the only one on my mind import sys # import re # inf = float("inf") # sys.setrecursionlimit(1000000) ...
785_B. Anton and Classes
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes. Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th v...
```python n = int(input()) refA = [] for i in range(n): refA.append([int(x) for x in input().split()]) m = int(input()) refB = [] for i in range(m): refB.append([int(x) for x in input().split()]) refA_early = sorted(refA,key = lambda x:x[1]) refA_late = sorted(refA,key = lambda x:x[0],reverse = True) refB_ear...
807_B. T-Shirt Hunt
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt. Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place p. Now the elimination rou...
```python #!/usr/bin/env python import sys def eligible(score, position, thresh): if score < thresh: return False i = (score // 50) % 475 for __ in range(25): i = (i * 96 + 42) % 475 if position == 26 + i: return True return False def main(): p, x, y= map(int, sy...
831_C. Jury Marks
Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain number of points (may be negative, i. e. points were subtracted). Initially the participant had some score, and each the marks were one by one added to his score. It is known that the i-th jury member gave ai points. P...
```python def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() n,k = map_input() a = list_input() b = list_input() pos = set() pref = [] cur = 0 for i in a: cur += i pref.append(cur) for j in pref: ...
876_E. National Property
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large ve...
```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(...
8_E. Beads
One Martian boy called Zorg wants to present a string of beads to his friend from the Earth — Masha. He knows that Masha likes two colours: blue and red, — and right in the shop where he has come, there is a variety of adornments with beads of these two colours. All the strings of beads have a small fastener, and if on...
```python __author__ = 'Darren' def solve(): def calc(lower, upper, record, eq, eq_i): if lower > upper: return 1 key = lower, eq, eq_i if key in record: return record[key] t = 0 for x in (['0', '1'] if result[lower] == '?' else [result[lower]]): ...
922_D. Robot Vacuum Cleaner
Pushok the dog has been chasing Imp for a few hours already. <image> Fortunately, Imp knows that Pushok is afraid of a robot vacuum cleaner. While moving, the robot generates a string t consisting of letters 's' and 'h', that produces a lot of noise. We define noise of string t as the number of occurrences of strin...
```python n=int(input()) a=[] for i in range(n): b=input() a.append([b.count("h")/len(b),b]) a.sort() b="" for i in range(n): b=b+a[i][1] c=0 s=0 for i in range(len(b)): if b[i]=="s": c=c+1 if b[i]=="h": s=s+c print(s) ```
978_C. Letters
There are n dormitories in Berland State University, they are numbered with integers from 1 to n. Each dormitory consists of rooms, there are a_i rooms in i-th dormitory. The rooms in i-th dormitory are numbered from 1 to a_i. A postman delivers letters. Sometimes there is no specific dormitory and room number in it o...
```python n, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) # aa = [sum(a[:i+1]) for i in range(len(a))] j = 0 s = a[0] for i in range(len(b)): while b[i] > s: # aa[j]: j += 1 s += a[j] print(j+1, b[i]- (s-a[j]) if j > 0 else b[i]) ```
998_B. Cutting
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers. There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti...
```python n, b = input().split() n = int(n) b = int(b) a = [int(x) for x in input().split()] odd = 0 not_odd = 0 pos = list() for i in range(n-1): if a[i] % 2 == 0: not_odd += 1 else: odd += 1 if not_odd == odd: pos.append(abs(a[i+1] - a[i])) pos.sort() sum = 0 count = 0 for i in r...
p02659 AtCoder Beginner Contest 169 - Multiplication 3
Compute A \times B, truncate its fractional part, and print the result as an integer. Constraints * 0 \leq A \leq 10^{15} * 0 \leq B < 10 * A is an integer. * B is a number with two digits after the decimal point. Input Input is given from Standard Input in the following format: A B Output Print the answer as ...
```python a, b = input().split() print((int(a)*round(float(b)*100))//100) ```
p02788 AtCoder Beginner Contest 153 - Silver Fox vs Monster
Silver Fox is fighting with N monsters. The monsters are standing in a row, and we can assume them to be standing on a number line. The i-th monster, standing at the coordinate X_i, has the health of H_i. Silver Fox can use bombs to attack the monsters. Using a bomb at the coordinate x decreases the healths of all mo...
```python from math import * import sys input = sys.stdin.readline def main(): N, D, A = list(map(int, input().split())) XH = sorted([list(map(int, input().split())) for i in range(N)]) t = 0 q = [] ans = 0 for X, H in XH: while q and q[0][0] < X-D: x, c = q.pop(0) ...
p02924 AtCoder Beginner Contest 139 - ModSum
For an integer N, we will choose a permutation \\{P_1, P_2, ..., P_N\\} of \\{1, 2, ..., N\\}. Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i. Find the maximum possible value of M_1 + M_2 + \cdots + M_N. Constraints * N is an integer satisfying 1 \leq N \leq 10^9. Input Input is giv...
```python n = int(input()) m = (n-1)*n//2 print(m) ```
p03059 AtCoder Beginner Contest 125 - Biscuit Generator
A biscuit making machine produces B biscuits at the following moments: A seconds, 2A seconds, 3A seconds and each subsequent multiple of A seconds after activation. Find the total number of biscuits produced within T + 0.5 seconds after activation. Constraints * All values in input are integers. * 1 \leq A, B, T \le...
```python A, B, T = map(int,input().split(' ')) print(int(T/A)*B) ```
p03203 AtCoder Grand Contest 029 - Grid game
Takahashi and Aoki will play a game using a grid with H rows and W columns of square cells. There are N obstacles on this grid; the i-th obstacle is at (X_i,Y_i). Here, we represent the cell at the i-th row and j-th column (1 \leq i \leq H, 1 \leq j \leq W) by (i,j). There is no obstacle at (1,1), and there is a piece ...
```python from operator import itemgetter import bisect h, w, n = map(int, input().split()) info = [tuple(map(int, input().split())) for i in range(n)] memo = set() for i, j in info: memo.add(i * 10**6 + j) pos = [[] for _ in range(w + 1)] info = sorted(info, key = itemgetter(0)) for i, j in info: pos[j].ap...
p03350 AtCoder Grand Contest 024 - Simple Subsequence Problem
You are given a set S of strings consisting of `0` and `1`, and an integer K. Find the longest string that is a subsequence of K or more different strings in S. If there are multiple strings that satisfy this condition, find the lexicographically smallest such string. Here, S is given in the format below: * The data...
```python R=range;N,K=map(int,input().split());Q=R(N+1);d=[[0]*2**N for _ in Q];f=[[0]*2**N for _ in Q] for i in Q: for j,c in enumerate(input()):d[i][j]=int(c) for i in R(1,N+1): for j in R(1<<i): t=j>>i-1&1;r=0 while r<i and j>>i-1-r&1==t:r+=1 f[i][j]=r for i in Q: for k in R(i+1,N+1): z=k-i;m=(1<<z)-1 f...
p03510 Code Festival Team Relay (Parallel) - Capture
In a long narrow forest stretching east-west, there are N beasts. Below, we will call the point that is p meters from the west end Point p. The i-th beast from the west (1 ≤ i ≤ N) is at Point x_i, and can be sold for s_i yen (the currency of Japan) if captured. You will choose two integers L and R (L ≤ R), and throw ...
```python n = int(input()) ans = 0 tmp = 0 prev = 0 for x, s in (map(int, input().split()) for _ in range(n)): dx = x - prev if dx > tmp: tmp = s else: tmp += s - dx ans = max(ans, tmp) prev = x ans = max(ans, tmp) print(ans) ```
p03671 AtCoder Beginner Contest 066 - ringring
Snuke is buying a bicycle. The bicycle of his choice does not come with a bell, so he has to buy one separately. He has very high awareness of safety, and decides to buy two bells, one for each hand. The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively. Find the m...
```python print(sum(sorted([int(tok) for tok in input().split()])[:2])) ```
p03826 AtCoder Beginner Contest 052 - Two Rectangles
There are two rectangles. The lengths of the vertical sides of the first rectangle are A, and the lengths of the horizontal sides of the first rectangle are B. The lengths of the vertical sides of the second rectangle are C, and the lengths of the horizontal sides of the second rectangle are D. Print the area of the r...
```python A, B, C, D = [int(_) for _ in input().split()] print(max(A * B, C * D)) ```
p03993 CODE FESTIVAL 2016 qual A - Friendly Rabbits
There are N rabbits, numbered 1 through N. The i-th (1≤i≤N) rabbit likes rabbit a_i. Note that no rabbit can like itself, that is, a_i≠i. For a pair of rabbits i and j (i<j), we call the pair (i,j) a friendly pair if the following condition is met. * Rabbit i likes rabbit j and rabbit j likes rabbit i. Calculate ...
```python n = int(input()) la = [int(w)-1 for w in input().split()] ans = 0 for i in range(n): if la[la[i]] == i: ans += 1 print(ans//2) ```
p00081 A Symmetric Point
Read a set of coordinates of three different points P1 (x1, y1), P2 (x2, y2), Q (xq, yq) on the plane, and line symmetry with point Q with the straight line passing through point P1 point P2 as the axis of symmetry. Create a program that outputs the point R (x, y) at the position of. Note that the point Q is not on its...
```python import math def get_input(): while True: try: yield ''.join(input()) except EOFError: break N = list(get_input()) for l in range(len(N)): x1,y1,x2,y2,xq,yq = [float(i) for i in N[l].split(",")] # l: a*x + b*y + c = 0 a = y2-y1 b = x1-x2 c = y...
p00213 Subdivide The Land
Housing maker Yamada House has launched a new featured product, a land for sale in a green home town with a rich environment such as schools and hospitals. This lot is divided into multiple lots and you can buy as many as you like, but the shape of the land with the lots you buy must be rectangular (including squares)....
```python from itertools import product # from line_profiler import LineProfiler def putpiece(X,Y,bitmap,unused,pieces,numans,pcsans,FINFLAG): if FINFLAG: return numans,pcsans if not unused: pcsans = pieces return numans + 1, pcsans if numans > 1: return 2, pieces b,k,y...
p00590 Pair of Primes
We arrange the numbers between 1 and N (1 <= N <= 10000) in increasing order and decreasing order like this: 1 2 3 4 5 6 7 8 9 . . . N N . . . 9 8 7 6 5 4 3 2 1 Two numbers faced each other form a pair. Your task is to compute the number of pairs P such that both numbers in the pairs are prime. Input Input cont...
```python primes = [0, 0] + [1]*9999 for i in range(2, 101): if primes[i]: for j in range(i*i, 10001, i): primes[j] = 0 while True: try: n = int(input()) print(sum([1 for a, b in zip(list(range(1,n+1)), list(range(1,n+1)[::-1])) if primes[a] and primes[b]])) except: ...
p00867 Digits on the Floor
Taro attempts to tell digits to Hanako by putting straight bars on the floor. Taro wants to express each digit by making one of the forms shown in Figure 1. Since Taro may not have bars of desired lengths, Taro cannot always make forms exactly as shown in Figure 1. Fortunately, Hanako can recognize a form as a digit i...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def dot3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy) def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy) def dist2(A...
p00998 RMQ
Given n numbers a0, a1, ..., an-1 and q. I want you to perform appropriate processing for q queries. The query has the following three types of operations. * Shift the value Given a pair of l and r. (l <r) Circular shift the value from al to ar. 0 1 2 3 4 5 6 7 8 9 Is given the query l = 2, r = 5. The shifted numb...
```python INF = 10**9 def update(nd): if nd: l = nd[0]; r = nd[1] nd[4] = min((l[4] if l else INF), (r[4] if r else INF), nd[2]) # splay a node nd def __splay(st, dr, nd): l = nd[0]; r = nd[1] L = (l[3] if l else 0); R = (r[3] if r else 0) c = len(st) >> 1 while c: # y(d1)-x...
p01130 Water Pipe Construction
In 21XX, humanity finally began a plan to relocate to Mars. Selected as the first group of immigrants to Mars, you are assigned to the Administrative Center of Mars to deal with various problems that occur on Mars. The biggest problem at the moment of the Central Bureau is securing an independent supply and demand cycl...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p01269 Brave Princess Revisited
A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who is trying to kill the princess is releasing a thug on the way to his wife. You have already decided on a safe route to safely deliver the princess to the other country, but with the wish of the pr...
```python from heapq import heappush, heappop INF = 10 ** 20 while True: n, m, l = map(int, input().split()) if n == 0: break edges = [[] for _ in range(n * (l + 1))] for _ in range(m): a, b, d, e = map(int, input().split()) a -= 1 b -= 1 for i in range(d, l + 1): edges[i * n + a].ap...
p01439 Chinese Classics
Taro, a junior high school student, is working on his homework. Today's homework is to read Chinese classic texts. As you know, Japanese language shares the (mostly) same Chinese characters but the order of words is a bit different. Therefore the notation called "returning marks" was invented in order to read Chinese ...
```python import re num = re.compile(r'\d+$') def testcase_ends(): n = int(input()) if n == 0: return 1 marks = [input().replace('-', '') for i in range(n)] links = {} bares = [] labels = {} for i, mark in enumerate(marks, 1): if not mark: bares.append(i) ...