name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p03759 AtCoder Beginner Contest 058 - ι⊥l
Three poles stand evenly spaced along a line. Their heights are a, b and c meters, from left to right. We will call the arrangement of the poles beautiful if the tops of the poles lie on the same line, that is, b-a = c-b. Determine whether the arrangement of the poles is beautiful. Constraints * 1 \leq a,b,c \leq 10...
```python a,b,c=map(int,input().split());print(" YNEOS"[b-a==c-b::2]) ```
p03921 CODE FESTIVAL 2016 Final (Parallel) - Interpretation
On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M. For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet. The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}. Two participants A and B can c...
```python import sys class UnionFind: def __init__(self, n): # 親要素のノード番号を格納 par[x] == x の時そのノードは根 self.par = [i for i in range(n+1)] # 木の高さを格納する(初期状態では0) self.rank = [0] * (n+1) # 各々の集合の要素数(根が代表して値を持っておく) self.count = [1] * (n+1) # 検索 def find(self, x): ...
p00022 Maximum Sum Sequence
Given a sequence of numbers a1, a2, a3, ..., an, find the maximum sum of a contiguous subsequence of those numbers. Note that, a subsequence of one element is also a contiquous subsequence. Input The input consists of multiple datasets. Each data set consists of: n a1 a2 . . an You can assume that 1 ≤ n ≤ 5000 ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False mi = su = 0 ans = -10**9 for i in range(N): a = int(readline()) su += a ans = max(ans, su - mi) mi = min(su, mi) print(ans...
p00153 Triangle and Circle
Create a program to determine the positional relationship between a triangle and a circle on a plane. All target figures shall include boundaries. The triangle is given the position of three vertices, and the circle is given the position of the center and the radius. The position is given by a set of two integers in a ...
```python def contain(x, y, r): return x**2 + y**2 <= r**2 def outer_p(x0, y0, x1, y1): return (x0*y1 - y0*x1) def line_segment_circle(x0, y0, x1, y1, r, border=True): A = x0**2 + y0**2 B = x0*x1 + y0*y1 C = x1**2 + y1**2 - r**2 D = B**2 - A*C if border: if D < 0: return ...
p00310 The Number of Participants
Welcome to PC Koshien, players. At PC Koshien, competitions are currently being held in a total of three categories: programming category, mobile category, and Ichimai's picture CG category. Given the number of participants in each department, create a program that calculates the total number of participants. Input...
```python p,m,c=map(int,input().split()) ans=p+m+c print(ans) ```
p00474 Icicles
problem There are fine icicles under the eaves of JOI's house in Canada. Because of this, JOI decided to investigate the icicles. There are N (2 ≤ N ≤ 100000 = 105) icicles under the eaves of JOI's house. These icicles are aligned and i cm (1 ≤ i ≤ N) from the left edge of the eaves. There are i-th icicles at the pos...
```python def loadIcicle(): icicles = [] line = input().strip().split(" ") N, L = int(line[0]), int(line[1]) while True: icicles.append(int(input().strip())) if len(icicles) == N: break return icicles, N, L icicles, N, L = loadIcicle() def calcDiff(icicles, N): diff_2times = [0]*N for idx in range(N): di...
p00666 World Domination
Evil organizations that attempt to conquer the world are everywhere, regardless of age, east or west fiction, non-fiction, but what on earth did they try to conquer the world? I suddenly thought about that because I was also planning to conquer the world. The only reason I want to conquer the world is to show the world...
```python E = 10 ** -9 MOD = 100000007 fact_result = {} while True: n = int(input()) if n == 0: break plst = [] wlst = [] diff = [] to = [None for _ in range(n)] for i in range(n): p, Id, w = input().split() to[i] = int(Id) plst.append(float(p)) wlst.append(float(w)) diff.append(1 / f...
p00940 Deadlock Detection
Example Input 2 2 7 3 4 3 2 1 3 1 1 2 2 1 2 2 1 1 2 2 2 1 1 Output 5
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): P, R, T = map(int, readline().split()) *L, = map(int, readline().split()) RS = [list(map(int, readline().split())) for i in range(P)] LG = [list(map(int, input().split())) for i in range(T)] prv = -1 K = [...
p01073 Potatoes
Problem Gaccho owns an N-sided field and M potatoes. Each field is numbered from 1 to N. Gaccho wants to increase the number of potatoes by planting and harvesting potatoes in the field. Gaccho lives alone and can only manage fields up to the K side. In addition, the soil condition and area of ​​each field vary, and ...
```python n, m, k = map(int, input().split()) aList = list(map(int, input().split())) bList = list(map(int, input().split())) abList = sorted(tuple(zip(aList, bList)), key=lambda x:-x[0]) ans = 0 #dp[y][x] ... y面x個の最大値 dp = [[0] * (m + 1) for _ in range(k + 1)] for a, b in abList: for y in range(k - 1, -1, -1): ...
p01511 Three-way Branch
There is a grid that consists of W \times H cells. The upper-left-most cell is (1, 1). You are standing on the cell of (1,1) and you are going to move to cell of (W, H). You can only move to adjacent lower-left, lower or lower-right cells. There are obstructions on several cells. You can not move to it. You cannot mov...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+9 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 ...
p01960 Tree Separator
You are given a tree $T$ and an integer $K$. You can choose arbitrary distinct two vertices $u$ and $v$ on $T$. Let $P$ be the simple path between $u$ and $v$. Then, remove vertices in $P$, and edges such that one or both of its end vertices is in $P$ from $T$. Your task is to choose $u$ and $v$ to maximize the number ...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, K = map(int, readline().split()) G = [[] for i in range(N)] for i in range(N-1): u, v = map(int, readline().split()) G[u-1].append(v-1) G[v-1].append(u-1) P =...
p02247 Naive String Search
Find places where a string P is found within a text T. Print all indices of T where P found. The indices of T start with 0. Constraints * 1 ≤ length of T ≤ 1000 * 1 ≤ length of P ≤ 1000 * The input consists of alphabetical characters and digits Input In the first line, a text T is given. In the second line, a strin...
```python T = input() P = input() if len(P) > len(T): pass else: p = len(P) ans = [] for i in range(len(T)-len(P)+1): tmp = "" for j in range(i,i+p): tmp += T[j] if tmp == P: ans.append(i) for i in ans: print(i) ```
p02394 Circle in a Rectangle
Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given. Circle inside a rectangle Cons...
```python a,b,x,y,r=map(int, input().split()) if r<= y and y<= b-r and r <= x and x<=a-r: print("Yes") else: print("No") ```
1009_B. Minimum Ternary String
You are given a ternary string (it is a string which consists only of characters '0', '1' and '2'). You can swap any two adjacent (consecutive) characters '0' and '1' (i.e. replace "01" with "10" or vice versa) or any two adjacent (consecutive) characters '1' and '2' (i.e. replace "12" with "21" or vice versa). For e...
```python s = input() s = list(s) n = len(s) i=0 j = i while j<n and s[j]!='2': j+=1 a = sorted(s[i:j]) one = [] others = [] while j<n: if s[j]=='1': one+=[s[j]] else: others+=[s[j]] j+=1 ans = a+one+others print(''.join(ans)) ```
1031_E. Triple Flips
You are given an array a of length n that consists of zeros and ones. You can perform the following operation multiple times. The operation consists of two steps: 1. Choose three integers 1 ≤ x < y < z ≤ n, that form an arithmetic progression (y - x = z - y). 2. Flip the values a_x, a_y, a_z (i.e. change 1 to 0...
```python def solve(a): l = len(a) d = sum(a[i] * 2 ** i for i in range(l)) if d == 0: return [] usable = [] if l >= 3: for i in range(l - 2): usable.append(0b111 << i) if l >= 5: for i in range(l - 4): usable.append(0b10101 << i) if l >= 7: ...
1054_E. Chips Puzzle
Egor came up with a new chips puzzle and suggests you to play. The puzzle has the form of a table with n rows and m columns, each cell can contain several black or white chips placed in a row. Thus, the state of the cell can be described by a string consisting of characters '0' (a white chip) and '1' (a black chip), p...
```python def fill(oper, curr, upper, second, n, m): for i in range(n): for j in range(m): for s in reversed(curr[i][j]): if s == '0': if i == 0: dest = (j + 1) % m oper.append((0, j, 0, dest)) ...
1076_E. Vasya and a Tree
Vasya has a tree consisting of n vertices with root in vertex 1. At first all vertices has 0 written on it. Let d(i, j) be the distance between vertices i and j, i.e. number of edges in the shortest path from i to j. Also, let's denote k-subtree of vertex x — set of vertices y such that next two conditions are met: ...
```python import math import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "...
1118_E. Yet Another Ball Problem
The king of Berland organizes a ball! n pair are invited to the ball, they are numbered from 1 to n. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from 1 to k, inclusive. Let b_i be the color of the man's ...
```python n,k=map(int,input().split()) if(n>(k*(k-1))): print('NO') else: ans=[0 for i in range(n)] for i in range(len(ans)): ans[i]=(i+1)%k if(ans[i]==0): ans[i]=k count=1 temp=[0 for i in range(len(ans))] for i in range(len(ans)): if(i%k==0): t...
1145_B. Kanban Numbers
Input The input contains a single integer a (1 ≤ a ≤ 99). Output Output "YES" or "NO". Examples Input 5 Output YES Input 13 Output NO Input 24 Output NO Input 46 Output YES
```python import math k = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen'] n = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'] a = int(input(...
1166_A. Silent Classroom
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha...
```python n = int(input()) l = [] se = set() for _ in range(n): st = input() s = st[0:1] l.append(s) se.add(s) su = 0 for s in se: c = l.count(s) if c>1: x = c//2 y = c-x su += ((x*(x-1))+(y*(y-1)))//2 print(su) ```
1184_E2. Daleks' Invasion (medium)
After a successful field test, Heidi is considering deploying a trap along some Corridor, possibly not the first one. She wants to avoid meeting the Daleks inside the Time Vortex, so for abundance of caution she considers placing the traps only along those Corridors that are not going to be used according to the curren...
```python def naiveSolve(): return from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is Genera...
1203_D1. Remove the Substring (easy version)
The only difference between easy and hard versions is the length of the string. You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without chang...
```python big=input() small=input() pre=[] post=[] i=0 j=0 while 1: if j==len(small): break if big[i]==small[j]: pre.append(i) i+=1 j+=1 else: i+=1 big=big[::-1] small=small[::-1] i=0 j=0 while 1: if j==len(small): break if big[i]==small[j]: ...
1220_A. Cards
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
```python n = int(input()) s = input() for i in range(s.count('n')): print(1, end = ' ') for i in range(s.count('z')): print(0, end = ' ') ```
1245_C. Constanze's Machine
Constanze is the smartest girl in her village but she has bad eyesight. One day, she was able to invent an incredible machine! When you pronounce letters, the machine will inscribe them onto a piece of paper. For example, if you pronounce 'c', 'o', 'd', and 'e' in that order, then the machine will inscribe "code" onto...
```python s=input() a=s.count('m') f=True ans=0 if(a>0): f=False a=s.count('w') if(a>0): f=False n=len(s) if(f==True): dp=[0]*(n+1) dp[0]=1 dp[1]=1 for i in range(2,n+1): if(s[i-1]==s[i-2] and (s[i-1]=='u' or s[i-1]=='n')): dp[i]=(dp[i-1]+dp[i-2])%1000000007 else: ...
1265_A. Beautiful String
A string is called beautiful if no two consecutive characters are equal. For example, "ababcb", "a" and "abab" are beautiful strings, while "aaaaaa", "abaa" and "bb" are not. Ahcl wants to construct a beautiful string. He has a string s, consisting of only characters 'a', 'b', 'c' and '?'. Ahcl needs to replace each c...
```python def inp(): return [int(s) for s in input().split()] if __name__ == '__main__': for i in range(int(input())): s = input() output = '' if len(s) == 1 and s[0] == '?': s = 'a' for j in range(len(s)): if s[j] != '?': output += s[j]...
1305_E. Kuroni and the Score Distribution
Kuroni is the coordinator of the next Mathforces round written by the "Proof by AC" team. All the preparation has been done, and he is discussing with the team about the score distribution for the round. The round consists of n problems, numbered from 1 to n. The problems are ordered in increasing order of difficulty,...
```python import sys reader = (line.rstrip() for line in sys.stdin) input = reader.__next__ n, m = map(int, input().split()) def limit(n): if n < 3: return 0 if n ^ 1: return ((n - 1) * (n - 1)) >> 2 else: return ((n - 2) * n) >> 2 if m > limit(n): print(-1) sys.exit...
136_E. Zero-One
Little Petya very much likes playing with little Masha. Recently he has received a game called "Zero-One" as a gift from his mother. Petya immediately offered Masha to play the game with him. Before the very beginning of the game several cards are lain out on a table in one line from the left to the right. Each card c...
```python def evaluate(a): c1 = a.count('1') c0 = a.count('0') n = len(a) A = (n - 1) // 2 B = (n - 2) // 2 if c1 <= A: return '00' if c0 <= B: return '11' p1 = a.rfind('1') p0 = a.rfind('0') if p0 < p1: return '01' else: return '10' a =...
1392_E. Omkar and Duck
This is an interactive problem. Omkar has just come across a duck! The duck is walking on a grid with n rows and n columns (2 ≤ n ≤ 25) so that the grid contains a total of n^2 cells. Let's denote by (x, y) the cell in the x-th row from the top and the y-th column from the left. Right now, the duck is at the cell (1, ...
```python import sys def pow(i,j): s = i+j if i % 2 ==0: return 0 return 2**s def nxt(): s = input() while not s: s = input() return int(s) def main(): (n,) = map(int, input().split(' ')) a = [] for i in range(n): b = [] for j in range(n): ...
1417_A. Copy-paste
— Hey folks, how do you like this problem? — That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≤ i, j ≤ n and i ≠ j. 2. All candies from pile i are...
```python for _ in range(int(input())): n, k = list(map(int,input().split())) arr = list(map(int,input().split())) arr.sort() i, j = 0, 1 c = 0 while j<n: temp = arr[i] + arr[j] if temp <= k: t = k-arr[j] t = t//arr[i] c += t j += 1 ...
1433_F. Zero Remainder Sum
You are given a matrix a of size n × m consisting of integers. You can choose no more than \left⌊m/2\right⌋ elements in each row. Your task is to choose these elements in such a way that their sum is divisible by k and this sum is the maximum. In other words, you can choose no more than a half (rounded down) of eleme...
```python import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations ...
1458_E. Nim Shortcuts
After your debut mobile game "Nim" blew up, you decided to make a sequel called "Nim 2". This game will expand on the trusted Nim game formula, adding the much awaited second heap! In the game, there are two heaps, each containing a non-negative number of stones. Two players make moves in turn. On their turn, a playe...
```python from heapq import * from bisect import bisect_left n, m = map(int, input().split()) inf = 15 * 10 ** 8 norm = [] rev = [] slow = set() for _ in range(n):x, y = map(int, input().split());heappush(norm, (x,y));heappush(rev, (y,x));slow.add((x,y)) cx = cy = 0 skipX=[] skipY=[] for i in range(2 * n): tl ...
1481_E. Sorting Books
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first. <image> There are n books standing in a row on the shelf, the i-th book has color a_i. You'd like to rearrange the books to make the shelf look beautif...
```python n = int(input()) a = [int(x) - 1 for x in input().split()] l = [-1 for _ in range(n + 1)] r = [-1 for _ in range(n + 1)] freq = [0 for _ in range(n + 1)] dp = [0 for _ in range(n + 1)] for i in range(n): if(l[a[i]] == -1): l[a[i]] = i r[a[i]] = i for i in range(n - 1, -1, -1): dp[i] = dp[i + 1] ...
181_E. Playing with Superglue
Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue. We'll describe ...
```python n,m,x1,y1,x2,y2 = map(int, input().split()) n = abs(x1 - x2) m = abs(y1 - y2) if n > 4 or m > 4: print("Second") elif n <= 3 and m <= 3: print("First") elif min(n, m) <= 2: print("First") else: print("Second") ```
205_B. Little Elephant and Sorting
The Little Elephant loves sortings. He has an array a consisting of n integers. Let's number the array elements from 1 to n, then the i-th element will be denoted as ai. The Little Elephant can make one move to choose an arbitrary pair of integers l and r (1 ≤ l ≤ r ≤ n) and increase ai by 1 for all i such that l ≤ i ...
```python def solve(arr, n): inc = 0 ans = 0 for i in range(1, n): arr[i] += inc if arr[i] >= arr[i - 1]: continue diff = arr[i - 1] - arr[i] ans += diff inc += diff arr[i] += diff # print(arr) # print(ans) return ans def read(): ...
22_A. Second Order Statistics
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
```python n=int(input()) ar=[int(i) for i in input().split()] ar=list(set(sorted(ar))) ar.sort() try: print(ar[1]) except IndexError: print("NO") ```
254_A. Cards with Numbers
Petya has got 2n cards, each card contains some integer. The numbers on the cards can be the same. Let's index all cards by consecutive integers from 1 to 2n. We'll denote the number that is written on a card with number i, as ai. In order to play one entertaining game with his friends, Petya needs to split the cards i...
```python from sys import stdin, stdout import math,sys from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict,Counter from os import path import bisect as bi import heapq mod=10**9+7 def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------...
327_B. Hungry Sequence
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if: * Its elements are in increasing o...
```python n=int(input()) for i in range(n,n+n): print(i,end=' ') ```
349_C. 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 def ceil(x): if int(x) != x: return int(x+1) else: return int(x) def mafia(): n = int(input()) rounds = list(map(int, str(input()).split())) count = 0 rounds.sort(reverse=True) for i in range(n-1, 0, -1): if rounds[i-1] == rounds[i]: continue ...
394_A. Counting Sticks
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add...
```python v = input().split('+') a = len(v[0]) v = v[1].split('=') b = len(v[0]) c = len(v[1]) def good(a, b, c): return a+b==c and a>0 and b>0 and c>0 if good(a-1, b, c+1): a = a-1 c = c+1 if good(a, b-1, c+1): b = b-1 c = c+1 if good(a+1, b, c-1): a = a+1 c = c-1 if good(a, b+1, c-1):...
417_B. Crash
During the "Russian Code Cup" programming competition, the testing system stores all sent solutions for each participant. We know that many participants use random numbers in their programs and are often sent several solutions with the same source code to check. Each participant is identified by some unique positive i...
```python def readln(): return tuple(map(int, input().split())) n, = readln() max_pref = [-1] * 100001 flag = True for _ in range(n): x, k = readln() flag &= max_pref[k] + 1 >= x max_pref[k] = max(max_pref[k], x) print('YES' if flag else 'NO') ```
443_E. 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 n = input() s = [] a = 0 for i in map(int, input().split()): while len(s) > 1 and min(s[-2], i)>=s[-1]: a += min(i, s[-2]) del(s[-1]) s.append(i) s.sort() print(a + sum(s[0: -2])) ```
466_A. Cheap Travel
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
```python inp = input().split() n = int(inp[0]) m = int(inp[1]) a = int(inp[2]) b = int(inp[3]) sumary = min(b,a*m) print(min((sumary)*(n//m + 1), sumary*(n // m) + (n - (n//m)*m) * a )) ```
489_E. Hiking
A traveler is planning a water hike along the river. He noted the suitable rest points for the night and wrote out their distances from the starting point. Each of these locations is further characterized by its picturesqueness, so for the i-th rest point the distance from the start equals xi, and its picturesqueness e...
```python import os import sys if os.path.exists(r'C:\Users\User\codeforces'): f = iter(open('A.txt').readlines()) def input(): return next(f).strip() # input = lambda: sys.stdin.readline().strip() else: input = lambda: sys.stdin.readline().strip() fprint = lambda *args: print(*args, flush=True...
513_C. Second price auction
Nowadays, most of the internet advertisements are not statically linked to a web page. Instead, what will be shown to the person opening a web page is determined within 100 milliseconds after the web page is opened. Usually, multiple companies compete for each ad slot on the web page in an auction. Each of them receive...
```python import sys MaxV = int(1e4) data = [] readIdx = 0 for line in sys.stdin.readlines(): data += line.split() def read(): global readIdx readIdx += 1 return data[readIdx - 1] n, average, power, mul = int(read()), 0, 1, 1 froms, tos, r = [], [], [] def generate(i, maxIdx, secondMax, equal, ways): global n...
538_E. Demiurges Play Again
Demiurges Shambambukli and Mazukta love to watch the games of ordinary people. Today, they noticed two men who play the following game. There is a rooted tree on n nodes, m of which are leaves (a leaf is a nodes that does not have any children), edges of the tree are directed from parent to children. In the leaves of ...
```python import sys input = sys.stdin.readline def solve(): n = int(input()) g = [[] for i in range(n+1)] for i in range(1, n): u, v = map(int, input().split()) g[u].append(v) g[v].append(u) q = [1] d = [None]*(n+1) d[1] = 0 i = 0 while i < len(q): x = q[i] #print(x) i += 1 for v in g[x]: if...
566_F. Clique in the Divisibility Graph
As you must know, the maximum clique problem in an arbitrary graph is NP-hard. Nevertheless, for some graphs of specific kinds it can be solved effectively. Just in case, let us remind you that a clique in a non-directed graph is a subset of the vertices of a graph, such that any two vertices of this subset are connec...
```python for _ in range(1): n=int(input()) l=list(map(int,input().split())) dp=[0]*(10**6+1) for i in l: dp[i]=1 for i in l: if dp[i]: for x in range(i*2,10**6+1,i): if dp[x]: dp[x]=max(dp[x],dp[i]+1) print(max(dp)) ...
588_A. Duff and Meat
Duff is addicted to meat! Malek wants to keep her happy for n days. In order to be happy in i-th day, she needs to eat exactly ai kilograms of meat. <image> There is a big shop uptown and Malek wants to buy meat for her from there. In i-th day, they sell meat for pi dollars per kilogram. Malek knows all numbers a1, ....
```python n=int(input()) y,s=101,0 for i in range(n): a,b=map(int,input().split()) if y>b: y=b s+=(a*y) print(s) ```
630_H. Benches
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections. The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob...
```python from collections import Counter 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 ...
681_B. Economy Game
Kolya is developing an economy simulator game. His most favourite part of the development process is in-game testing. Once he was entertained by the testing so much, that he found out his game-coin score become equal to 0. Kolya remembers that at the beginning of the game his game-coin score was equal to n and that he...
```python n = int(input()) for i in range((n//1234567) + 1): for j in range((n//123456) + 1): t = n - i * 1234567 - j * 123456 if t >= 0 and t % 1234 == 0: print("YES") exit() print("NO") ```
704_A. Thor
Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't). q events are abou...
```python n , q = map(int, input().split()) stacks = [[] for i in range(n + 1)] queue = [] q_start = 0 unread = 0 ans = [] for i in range(q): action, num = map(int, input().split()) if action == 1: queue.append(0) stacks[num].append(len(queue) - 1) unread += 1 elif action =...
725_F. Family Photos
Alice and Bonnie are sisters, but they don't like each other very much. So when some old family photos were found in the attic, they started to argue about who should receive which photos. In the end, they decided that they would take turns picking photos. Alice goes first. There are n stacks of photos. Each stack con...
```python num_stacks = int(input()) answer = 0 array = [] for i in range(num_stacks): a1, b1, a2, b2 = input().split(' ') a1 = int(a1) a2 = int(a2) b1 = int(b1) b2 = int(b2) if a1 + b1 >= a2 + b2: answer += a1 + a2 array.append(a2 + b2) array.append(a1 + b1) e...
770_C. Online Courses In BSU
Now you can take online courses in the Berland State University! Polycarp needs to pass k main online courses of his specialty to get a diploma. In total n courses are availiable for the passage. The situation is complicated by the dependence of online courses, for each course there is a list of those that must be pas...
```python f = lambda: map(int, input().split()) g = lambda: [[] for x in range(n)] n, k = f() n += 1 s, p = [], list(f()) c, d = [0] * n, [0] * n u, v = g(), g() for x in range(1, n): t = list(f()) m = t.pop(0) if m: c[x] = m v[x] = t for y in t: u[y].append(x) else: s....
862_A. Mahmoud and Ehab and the MEX
Dr. Evil kidnapped Mahmoud and Ehab in the evil land because of their performance in the Evil Olympiad in Informatics (EOI). He decided to give them some problems to let them go. Dr. Evil is interested in sets, He has a set of n integers. Dr. Evil calls a set of integers evil if the MEX of it is exactly x. the MEX of ...
```python n,m = map(int, input().split()) s = set([int(i) for i in input().split()]) ans = 0 for i in range (m): if i not in s: ans += 1 print(ans+1 if m in s else ans) ```
959_C. Mahmoud and Ehab and the wrong algorithm
Mahmoud was trying to solve the vertex cover problem on trees. The problem statement is: Given an undirected tree consisting of n nodes, find the minimum number of vertices that cover all the edges. Formally, we need to find a set of vertices such that for each edge (u, v) that belongs to the tree, either u is in the ...
```python n = int(input()) if n <= 5: print(-1) else: print('1 2', '1 3', '1 4', '2 5', sep = '\n') for i in range(6, n + 1): print('2 {0:d}'.format(i)) for i in range(2, n + 1): print('1 {0:d}'.format(i)) ```
p02581 AtCoder Beginner Contest 176 - Brave CHAIN
We have 3N cards arranged in a row from left to right, where each card has an integer between 1 and N (inclusive) written on it. The integer written on the i-th card from the left is A_i. You will do the following operation N-1 times: * Rearrange the five leftmost cards in any order you like, then remove the three le...
```python N = int(input()) A = [int(a) for a in input().split()] + [0] * 2 X = [[-10**10] * (N+1) for _ in range(N+1)] X[A[0]][A[1]] = 0 ans = 0 ma = 0 MA = [-5] * (N+1) MA[A[0]] = MA[A[1]] = 0 for i in range(N): B = A[i*3+2:i*3+5] cnt = len(set(B)) if cnt == 1: ans += 1 elif cnt == 2: a...
p02712 AtCoder Beginner Contest 162 - FizzBuzz Sum
Let us define the FizzBuzz sequence a_1,a_2,... as follows: * If both 3 and 5 divides i, a_i=\mbox{FizzBuzz}. * If the above does not hold but 3 divides i, a_i=\mbox{Fizz}. * If none of the above holds but 5 divides i, a_i=\mbox{Buzz}. * If none of the above holds, a_i=i. Find the sum of all numbers among the first...
```python N = int(input()) s = sum([i for i in range(1, N+1) if ((i%3)!=0) and ((i%5)!=0)]) print(s) ```
p02841 Sumitomo Mitsui Trust Bank Programming Contest 2019 - November 30
In this problem, a date is written as Y-M-D. For example, 2019-11-30 means November 30, 2019. Integers M_1, D_1, M_2, and D_2 will be given as input. It is known that the date 2019-M_2-D_2 follows 2019-M_1-D_1. Determine whether the date 2019-M_1-D_1 is the last day of a month. Constraints * Both 2019-M_1-D_1 and 20...
```python input() _, d = input().split() print('1' if d == '1' else '0') ```
p02978 AtCoder Grand Contest 035 - Add and Remove
There is a stack of N cards, each of which has a non-negative integer written on it. The integer written on the i-th card from the top is A_i. Snuke will repeat the following operation until two cards remain: * Choose three consecutive cards from the stack. * Eat the middle card of the three. * For each of the other ...
```python #YouTube import sys sys.setrecursionlimit(10**6) def kukan(l,r,el=1,er=1): em=el+er if l+1==r: return 0 if l+2==r: return a[l+1]*em t=(l,r,el,er) if t in memo: return memo[t] re=10**11 for m in range(l+1,r): tmp=kukan(l,m,el,em)+kukan(m,r,em,er)+a[m...
p03118 World Tour Finals 2019 Open Contest - e
There is a very long bench. The bench is divided into M sections, where M is a very large integer. Initially, the bench is vacant. Then, M people come to the bench one by one, and perform the following action: * We call a section comfortable if the section is currently unoccupied and is not adjacent to any occupied s...
```python #参考URL #https://qiita.com/ageprocpp/items/104c051b2ec2086f5a9b mod=10**9+7 def value(obj): if type(obj)==modint: tmp=obj.number else: tmp=obj return tmp%mod class modint(): number=0 def __init__(self,num): self.number=num%mod def __add__(self,other): tm...
p03261 AtCoder Beginner Contest 109 - Shiritori
Takahashi is practicing shiritori alone again today. Shiritori is a game as follows: * In the first turn, a player announces any one word. * In the subsequent turns, a player announces a word that satisfies the following conditions: * That word is not announced before. * The first character of that word is the same a...
```python N = int(input()) W = [input() for i in range(N)] if all(W[i][0]==W[i-1][-1] and W[i] not in W[:i] for i in range(1, N)): print('Yes') else: print('No') ```
p03419 AtCoder Regular Contest 091 - Flip Flip and Flip......
There is a grid with infinitely many rows and columns. In this grid, there is a rectangular region with consecutive N rows and M columns, and a card is placed in each square in this region. The front and back sides of these cards can be distinguished, and initially every card faces up. We will perform the following op...
```python n,m = map(int, input().split()) if n == 1 or m == 1: if n == 1 and m == 1: print(1) else: print(max(n,m)-2) else: print((m-2)*(n-2)) ```
p03577 CODE FESTIVAL 2017 qual B - XXFESTIVAL
Rng is going to a festival. The name of the festival is given to you as a string S, which ends with `FESTIVAL`, from input. Answer the question: "Rng is going to a festival of what?" Output the answer. Here, assume that the name of "a festival of s" is a string obtained by appending `FESTIVAL` to the end of s. For ex...
```python # Problem A - XXFESTIVAL # input S = input() # inititliazation s_len = len(S) ans = S[:(s_len - 8)] # output print(ans) ```
p03734 AtCoder Regular Contest 073 - Simple Knapsack
You have N items and a bag of strength W. The i-th item has a weight of w_i and a value of v_i. You will select some of the items and put them in the bag. Here, the total weight of the selected items needs to be at most W. Your objective is to maximize the total value of the selected items. Constraints * 1 ≤ N ≤ 10...
```python # -*- coding: utf-8 -*- from itertools import accumulate, product from operator import itemgetter def inpl(): return tuple(map(int, input().split())) N, W = inpl() I = [inpl() for _ in range(N)] w1 = I[0][0] A = {w1 + x: [] for x in range(4)} for w, v in I: A[w].append(v) for k, v in A.items(): A[k...
p03896 CODE FESTIVAL 2016 Relay (Parallel) - 3y3s Challenge
There are N persons, conveniently numbered 1 through N. They will take 3y3s Challenge for N-1 seconds. During the challenge, each person must look at each of the N-1 other persons for 1 seconds, in some order. If any two persons look at each other during the challenge, the challenge ends in failure. Find the order i...
```python n = int(input()) if n == 2: print(-1) exit() if n % 2 == 1: for i in range(n): print(" ".join([str((item + i + 1) % n + 1) for item in range(n-1)])) else: for i in range(n): ans = [(item + i + 1) % n + 1 for item in range(n-1) if item != n // 2 - 1] ans.insert(0, (n // ...
p00002 Digit Number
Write a program which computes the digit number of sum of two integers a and b. Constraints * 0 ≤ a, b ≤ 1,000,000 * The number of datasets ≤ 200 Input There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF. ...
```python while 1: try: a,b=map(int,input().split()) print(len(str(a+b))) except: break ```
p00134 Exit Survey
I conducted an exit poll of the shopping amount at a department store. Create a program that takes the shopping amount data as input, calculates the average shopping amount per person, and outputs it. The number of people surveyed shall be 100,000 or less, and the shopping amount per person shall not exceed 1 million y...
```python # AOJ 0134 Exit Survey # Python3 2018.6.18 bal4u sum = 0 n = int(input()) for i in range(n): sum += int(input()) print(sum // n) ```
p00267 The Lonely Girl's Lie
There is a game called Packet Monster. A game that catches, raises, fights and exchanges monsters, and is very popular all over Japan. Of course, in my class. That's why I also raise monsters so that I can play with everyone in this game, but sadly there is no opponent to play against. I'm not the type who is good at t...
```python from collections import deque while True: n = int(input()) if n == 0:break q1 = deque(sorted(map(int, input().split()))) q2 = deque(sorted(map(int, input().split()))) cnt = 0 for k in range(1, n): top1 = q1.pop() top2 = q2.pop() if top1 > top2: cnt +...
p00454 Paint Color
problem Information I want to paint a rectangular veneer board to make a signboard for the promotion of the Olympic Games. Some rectangular masking tapes are pre-attached to the veneer board where I do not want to paint. We decided to paint each area with a different color. For example, in the case of Figure 5-1 we us...
```python # -*- coding: utf-8 -*- from typing import Union, List import io, sys import bisect from collections import deque def main(): w,h = list(map(int, sys.stdin.readline().split())) if w == h == 0: return "END" n = int( sys.stdin.readline() ) x1y1x2y2_list = [ list(map(int, sys....
p00789 Square Coins
People in Silverland use square coins. Not only they have square shapes but also their values are square numbers. Coins with values of all square numbers up to 289 (= 172), i.e., 1-credit coins, 4-credit coins, 9-credit coins, ..., and 289-credit coins, are available in Silverland. There are four combinations of coins...
```python # AOJ 1209: Square Coins #Python3 2018.7.19 bal4u dp = [1]*300 for i in range(2, 18): for j in range(i**2, 300): dp[j] += dp[j-i**2] while True: n = int(input()) if n == 0: break print(dp[n]) ```
p00921 Don't Burst the Balloon
An open-top box having a square bottom is placed on the floor. You see a number of needles vertically planted on its bottom. You want to place a largest possible spheric balloon touching the box bottom, interfering with none of the side walls nor the needles. Java Specific: Submitted Java programs may not use "java.a...
```python from math import sqrt def getcircle(nee, R): #針にぶつかる範囲の円 (x, y, h) = nee if R <= h: return (x, y, R) r = sqrt(R**2 - (R-h)**2) return (x, y, r) def crosscircle(c1, c2): #円の交点 (x1, y1, r1) = c1 (x2, y2, r2) = c2 if (x1-x2)**2 + (y1-y2)**2 > (r1+r2)**2: return (...
p01054 String Conversion
Problem Jennifer and Marian presented Carla with the string S. However, Carla is not happy to receive the string S. I wanted the string T. The three decided to work together to change the string S to the string T. Jennifer first sorts the letters in any order. Marian then exchanges the lowercase letters of the two ...
```python # AOJ 1568: String Conversion # Python3 2018.7.13 bal4u cha, chzn = ord('a'), ord('z')+1 S, T = [0]*128, [0]*128 input() a = input() for x in a: S[ord(x)] += 1 S = sorted(S[cha:chzn], reverse=True) a = input() for x in a: T[ord(x)] += 1 T = sorted(T[cha:chzn], reverse=True) ans = 0 for i in range(26): ans +=...
p01323 Compile
Masa Kita, who entered the University of Tokyo, joined a circle called TSG (University of Tokyo Super Gamers). This circle exhibits games at the Komaba Festival every year, and Masa Kita decided to create and display the games as well. The game created by Kitamasa is a common falling block puzzle game such as the fol...
```python def kesu(x, s, c, h): global n if (x[0] - 1, x[1]) not in s and a[x[0] - 1][x[1]] == c: s.add((x[0] - 1, x[1])) kesu((x[0] - 1, x[1]), s, c, h + 1) if (x[0] + 1, x[1]) not in s and a[x[0] + 1][x[1]] == c: s.add((x[0] + 1, x[1])) kesu((x[0] + 1, x[1]), s, c, h + 1) ...
p01491 RabbitLunch
Example Input 2 3 1 3 1 0 Output 2
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): M, N, m0, md, n0, nd = map(int, readline().split()) S = [0]*(M+1) S[0] = mi = m0 for i in range(1, M): S[i] = mi = (mi * 58 + md) % (N + 1) S.sort() for i in range(M): S[i+1] += S[i] T ...
p01653 Magical Bridges
Problem Statement A magician lives in a country which consists of N islands and M bridges. Some of the bridges are magical bridges, which are created by the magician. Her magic can change all the lengths of the magical bridges to the same non-negative integer simultaneously. This country has a famous 2-player race ga...
```python from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M, S1, S2, T = map(int, readline().split()) if N == 0: return False S1 -= 1; S2 -= 1; T -= 1 G = [[] for i in range(N)] Gx = [[] for i in range(N)] L = 0 fo...
p01804 Falling Block Puzzle
Falling Block Puzzle Block drop You are playing a falling block puzzle. As shown in the figure below, the field of this puzzle has a shape in which cubic cells are arranged in 2 squares x 2 squares in each row, and the rows are infinitely arranged on the top. <image> Each cell either has one block that fits snugly ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): H, N = map(int, readline().split()) if H == N == 0: return False def get_block(): s = readline().strip() v = (s[0] == '#') + (s[1] == '#')*2 s = readline().strip() v += (s[0] == '...
p01939 Ebi-chan and Integer Sequences
B: Ebi-chan and Integer Sequences- problem Ebi-chan likes sequences. I especially like arithmetic progressions. This time, I decided to create a sequence that meets the following conditions. * Arithmetic progression of length n * When the i-th element of the sequence is defined as s_i, all s_i (1 \ leq i \ leq n) ar...
```python MOD = 10**9+7 def sum(a,d,n): return n*(2*a+(n-1)*d)//2 def main(): n,m = map(int,input().split()) s = 0 if n == 1: s = m+1 else: s = sum(m+1,-n+1,1+m//(n-1)) s *= 2 s -= (m+1) print(s%MOD) if __name__ == '__main__': main() ```
p02088 Union Ball
A: Union Ball Problem Statement There are N balls in a box. The i-th ball is labeled with a positive integer A_i. You can interact with balls in the box by taking actions under the following rules: * If integers on balls in the box are all odd or all even, you cannot take actions anymore. * Otherwise, you select ar...
```python n = int(input()) a = list(map(int, input().split())) p, q = 0, 0 for i in a: if i % 2 == 0: p += 1 else: q += 1 if p == 0 or q == 0: print(0) exit() res = p if q % 2 == 0: res += 2 * max(q // 2 - 1, 0) else: res += (q // 2) * 2 print(res) ```
p02372 Height of a Tree
Given a tree T with non-negative weight, find the height of each node of the tree. For each node, the height is the distance to the most distant leaf from the node. Constraints * 1 ≤ n ≤ 10,000 * 0 ≤ wi ≤ 1,000 Input n s1 t1 w1 s2 t2 w2 : sn-1 tn-1 wn-1 The first line consists of an integer n which represents th...
```python from sys import stdin from collections import defaultdict readline = stdin.readline #readline = open('GRL_5_B-in10.txt').readline def main(): n = int(readline()) g = defaultdict(list) for _ in range(n - 1): s, t, d = map(int, readline().split()) g[s].append([d, t]) g[t].a...
1007_A. Reorder the Array
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
```python n = int(input()) l = list(map(int,input().split())) l.sort() i = 0 c = 0 stack = [] k = 1 i = 0 while i < n-1 and k < n: stack.append(l[i]) if l[i] != l[i+1]: if k <= i: k = i+1 while k < n and len(stack): stack.pop() c = c + 1 k = k + 1 i = i + 1 print(c) ```
1030_A. In Search of an Easy Problem
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
```python n = int(input()) str = input() difficulty = [] difficulty = str.split() flag = 1 for i in difficulty: if i == '1': print("HARD") flag = 0 break if(flag ==1): print("EASY") ''' 3 0 0 1 HARD 1 0 EASY ''' ```
1096_A. Find Divisible
You are given a range of positive integers from l to r. Find such a pair of integers (x, y) that l ≤ x, y ≤ r, x ≠ y and x divides y. If there are multiple answers, print any of them. You are also asked to answer T independent queries. Input The first line contains a single integer T (1 ≤ T ≤ 1000) — the number of...
```python for _ in range(int(input())): l, r = map(int, input().split()) for i in range(l,r+1): k = r//i if k>1: print(i, i*2) break ```
1117_B. Emotes
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy). You have time to use some emotes only m times. You are allowed t...
```python n,m,k=map(int,input().split()) a=list(map(int,input().split())) c=0 a.sort() q=a[n-1] w=a[n-2] r=k*q+w u=m//(k+1) c=u*r+q*(m-(u*(k+1))) print(c) ```
1143_D. The Beatles
Recently a Golden Circle of Beetlovers was found in Byteland. It is a circle route going through n ⋅ k cities. The cities are numerated from 1 to n ⋅ k, the distance between the neighboring cities is exactly 1 km. Sergey does not like beetles, he loves burgers. Fortunately for him, there are n fast food restaurants on...
```python """This code was written by Russell Emerine - linguist, mathematician, coder, musician, and metalhead.""" from math import gcd n, k = map(int, input().split()) a, b = map(int, input().split()) lll = [a + b, abs(a - b), k - a - b, k - abs(a - b)] x, y = n * k, 0 for ll in lll: for i in range(n): l = ll +...
1163_C2. Power Transmission (Hard Edition)
This problem is same as the previous one, but has larger constraints. It was a Sunday morning when the three friends Selena, Shiro and Katie decided to have a trip to the nearby power station (do not try this at home). After arriving at the power station, the cats got impressed with a large power transmission system c...
```python from itertools import combinations n = int(input()) points = [] for _ in range(n): x, y = map(int, input().split(' ')) points.append((x, y)) directions = {} for pair in combinations(points, 2): (x1, y1), (x2, y2) = pair if x1 == x2: dir = (0, 1) b = x1 else: dir ...
1184_A2. Heidi Learns Hashing (Medium)
After learning about polynomial hashing, Heidi decided to learn about shift-xor hashing. In particular, she came across this interesting problem. Given a bitstring y ∈ \{0,1\}^n find out the number of different k (0 ≤ k < n) such that there exists x ∈ \{0,1\}^n for which y = x ⊕ \mbox{shift}^k(x). In the above, ⊕ is ...
```python import math num = int(input()) x = tuple(map(int, list(input()))) integer = 0 dic = dict() for i in range(1,num+1): a = math.gcd(i,num) if a in dic: integer += dic[a] else: lijst = [0]*a for j in range(num): b = j%a lijst[b] += x[j] ...
1219_D. Workout plan
Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in ...
```python n, k = tuple(map(int, input().split())) plan = list(map(int, input().split())) power = int(input()) cost = list(map(int, input().split())) money = 0 current_pow = 0 store = [] # Запас breaked = False for i in range(n): store.append(cost[i]) if plan[i] > k + current_pow: if plan[i] > k + cur...
1243_D. 0-1 MST
Ujan has a lot of useless stuff in his drawers, a considerable part of which are his math notebooks: it is time to sort them out. This time he found an old dusty graph theory notebook with a description of a graph. It is an undirected weighted graph on n vertices. It is a complete graph: each pair of vertices is conne...
```python import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ n,m = map(int, input().split()) G = [set() for i in range(n)] for i in range(m): a,b = map(int, input().split()) a,b = a-1,b-1 G[a].add(b) G[b].add(a) ans = 0 unused = set(range(n)) while unused: cur = {unused.po...
1263_C. Everyone is a Winner!
On the well-known testing system MathForces, a draw of n rating units is arranged. The rating will be distributed according to the following algorithm: if k participants take part in this event, then the n rating is evenly distributed between them and rounded to the nearest lower integer, At the end of the drawing, an ...
```python for _ in range(int(input())): n=int(input()) ar1=[] ar2=[0] count=1 for k in range(1,int(n**(1/2))+1): p=n//k if(p!=k and n%k<=p): count+=2 ar1.append(p) ar2.append(k) elif(p==k and n%k<=p): count+=1 ar1.ap...
1304_A. Two Rabbits
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
```python def main(): test = int(input().strip()) while test>0 : x,y,a,b =map( int,input().strip().split()) z = (y-x)/(a+b) h=(y-x)%(a+b) if h==0: print(int(z)) else: print(-1) test-=1 if __name__ == "__main__": main() ```
1328_B. K-th Beautiful String
For the given integer n (n > 2) let's write down all the strings of length n which contain n-2 letters 'a' and two letters 'b' in lexicographical (alphabetical) order. Recall that the string s of length n is lexicographically less than string t of length n, if there exists such i (1 ≤ i ≤ n), that s_i < t_i, and for a...
```python tc = int(input()) while tc > 0: n, k = map(int, input().split()) t = 0 for i in range(n): if t + i >= k: s = ["a"] * n s[n - i - 1] = "b" s[n - k + t] = "b" print("".join(s)) break t += i tc -= 1 ```
1348_B. Phoenix and Beauty
Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length k have the same sum. A subarray of an array is any sequence of consecutive elements. Phoenix currently has an array a of length n. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautifu...
```python for _ in range(int(input())): n,k=map(int,input().split()) d=dict() a=[] new=[] for x in input().split(): x=int(x) a.append(x) if x not in d: d[x]=0 new.append(x) d[x]+=1 if len(d)>k: print("-1") else: while l...
1413_B. A New Technique
All techniques in the ninja world consist of hand seals. At the moment Naruto is learning a new technique, which consists of n⋅ m different seals, denoted by distinct numbers. All of them were written in an n× m table. The table is lost now. Naruto managed to remember elements of each row from left to right, and eleme...
```python # Source: PyRival import os import sys from io import BytesIO, IOBase def main(): for _ in range(int(input())): n, m = map(int, input().split()) row = [] col = [] for i in range(n): row.append(list(map(int, input().split()))) for j in range(m): ...
1455_B. Jumps
You are standing on the OX-axis at point 0 and you want to move to an integer point x > 0. You can make several jumps. Suppose you're currently at point y (y may be negative) and jump for the k-th time. You can: * either jump to the point y + k * or jump to the point y - 1. What is the minimum number of jum...
```python t = int(input()) for i in range(t): n = int(input()) i=1 sum=0 cnt=0 while sum<n: sum+=i cnt+=1 i+=1 if sum==n or sum-n>1: print(cnt) else: print(cnt+1) ```
1479_C. Continuous City
Some time ago Homer lived in a beautiful city. There were n blocks numbered from 1 to n and m directed roads between them. Each road had a positive length, and each road went from the block with the smaller index to the block with the larger index. For every two (different) blocks, there was at most one road between th...
```python import sys input = sys.stdin.readline l,r=map(int,input().split()) dif=r-l+1 print("YES") n=2 while 2**(n-2)<dif:n+=1 edges=[] for i in range(n-2): for j in range(i+1,n-1): if i==0: edges.append([1,j+1,1]) else: edges.append([i+1,j+1,2**(i-1)]) mx=l-1 i=1 if mx==0 o...
1506_B. Partial Replacement
You are given a number k and a string s of length n, consisting of the characters '.' and '*'. You want to replace some of the '*' characters with 'x' characters so that the following conditions are met: * The first character '*' in the original string should be replaced with 'x'; * The last character '*' in the...
```python t = int(input()) for i in range(t): n, k = map(int, input().split()) s = input() index = s.find('*') num = 1 last = s.rfind('*') while index < last: if s[index] == '*': index += k num += 1 else: index -= 1 print(num) ```
152_A. Marks
Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook. Overall the group has n students. They received marks for m subjects. Each student got a mark from 1 to 9 (inclusive) for each subject. Let's consider a student the best at some...
```python n,m=map(int,input().split()) a=list() b=list() c=list() for i in range(n): a.append([int(i) for i in list(input())]) for i in range(m): x=0 for j in range(n): if(a[j][i]>x): x=a[j][i] b=list() b.append(j) elif(a[j][i]==x): b.append(j)...
160_C. Find Pair
You've got another problem dealing with arrays. Let's consider an arbitrary sequence containing n (not necessarily different) integers a1, a2, ..., an. We are interested in all possible pairs of numbers (ai, aj), (1 ≤ i, j ≤ n). In other words, let's consider all n2 pairs of numbers, picked from the given array. For e...
```python #import math #from functools import lru_cache #import heapq #from collections import defaultdict from collections import Counter #from collections import deque #from sys import stdout #from sys import setrecursionlimit #setrecursionlimit(10**7) #from bisect import bisect_left from sys import stdin input = std...
203_A. Two Problems
A boy Valera registered on site Codeforces as Valera, and wrote his first Codeforces Round #300. He boasted to a friend Arkady about winning as much as x points for his first contest. But Arkady did not believe his friend's words and decided to check whether Valera could have shown such a result. He knows that the con...
```python x, t, a, b, da, db = (int(q) for q in input().split()) if (x in (a - da * i + b - db * j for i in range(t) for j in range(t)) or (a >= x and (a - x) % da == 0 and (a - x) // da < t) or (b >= x and (b - x) % db == 0 and (b - x) // db < t) or x == 0): print('YES') else: print('NO') ```
276_D. Little Girl and Maximum XOR
A little girl loves problems on bitwise operations very much. Here's one of them. You are given two integers l and r. Let's consider the values of <image> for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones. Expression <image> means applying bitwise excl...
```python def bin(a): if a <= 1: return a else: return 10*bin(a//2)+a%2 def convBin(a): k,i = 0,0 while a!=0: k += (a%10)*int((2**i)) a //= 10 i += 1 return k def maxi(a,b): if a == b: return 0 elif a+1 == b: return a^b elif a+2 =...
29_A. Spit Problem
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task. ...
```python n=int(input()) a1=[] a2=[] for i in range(n): x,d=list(map(int,input().split())) a1.append(x) a2.append(d) flag=1 for i in range(n): for j in range(i+1,n): if ((a1[i]+a2[i]==a1[j]) and (a1[j]+a2[j]==a1[i])): print("YES") flag=0 break if(flag==0): break if(flag==1): print("NO") ```