name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1033_B. Square Difference
Alice has a lovely piece of cloth. It has the shape of a square with a side of length a centimeters. Bob also wants such piece of cloth. He would prefer a square with a side of length b centimeters (where b < a). Alice wanted to make Bob happy, so she cut the needed square out of the corner of her piece and gave it to ...
```python def check(n): i=2 while i*i<=n: if n%i==0: return 1 i+=1 return 0 for _ in range(int(input())): a,b=map(int,input().split()) if (a-b)!=1: print('NO') else: if check((a*a)-(b*b)):print('NO') else:print('YES') ```
1078_A. Barcelonian Distance
In this problem we consider a very simplified model of Barcelona city. Barcelona can be represented as a plane with streets of kind x = c and y = c for every integer c (that is, the rectangular grid). However, there is a detail which makes Barcelona different from Manhattan. There is an avenue called Avinguda Diagonal...
```python a, b, c = map(int, input().split()) x1, y1, x2, y2 = map(int, input().split()) l = 0 xz1 = x1 if b != 0: yz1 = (-c - x1 * a) / b else: yz1 = 9999999999999999999 if a != 0: xz2 = (-c - y1 * b) / a else: xz2 = 9999999999999999999 yz2 = y1 xf1 = x2 if b != 0: yf1 = (-c - x2 * a) / b else: ...
1099_A. Snowball
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain. Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,...
```python w , h = map(int , input().split()) u1 , d1 = map(int , input().split()) u2 , d2 = map(int , input().split()) while h > 0: if h == d1: w = w + h w = w - u1 h -= 1 elif h == d2: w = w + h w = w - u2 h -= 1 else: w = w + h h -= 1 ...
1146_E. Hot is Cold
You are given an array of n integers a_1, a_2, …, a_n. You will perform q operations. In the i-th operation, you have a symbol s_i which is either "<" or ">" and a number x_i. You make a new array b such that b_j = -a_j if a_j s_i x_i and b_j = a_j otherwise (i.e. if s_i is '>', then all a_j > x_i will be flipped). A...
```python n,q=map(int,input().split()) a=list(map(int,input().split())) swaps=[0]*q for i in range(q): b=input().split() b[1]=int(b[1]) out=1 if (b[0]=="<" and b[1]<=0) or (b[0]==">" and b[1]>=0) else 0 split=b[1]+0.5 if b[0]==">" else b[1]-0.5 sign=1 if split>0 else -1 split=abs(split) swap...
1167_E. Range Deleting
You are given an array consisting of n integers a_1, a_2, ... , a_n and an integer x. It is guaranteed that for every i, 1 ≤ a_i ≤ x. Let's denote a function f(l, r) which erases all values such that l ≤ a_i ≤ r from the array a and returns the resulting array. For example, if a = [4, 1, 1, 4, 5, 2, 4, 3], then f(2, 4...
```python n, x = map(int, input().split()) a = list(map(int, input().split())) fst, last, sm = [], [], [] for i in range(1000005): fst.append(0) last.append(0) sm.append(0) for i in range(n): if fst[a[i]] == 0: fst[a[i]] = i + 1 last[a[i]] = i + 1 for i in range(x + 2): if fst[i] == 0: ...
1204_E. Natasha, Sasha and the Prefix Sums
Natasha's favourite numbers are n and 1, and Sasha's favourite numbers are m and -1. One day Natasha and Sasha met and wrote down every possible array of length n+m such that some n of its elements are equal to 1 and another m elements are equal to -1. For each such array they counted its maximal prefix sum, probably a...
```python import sys import math MOD = 998244853 def prepare_c(n): result = [1] last = [1, 1] for i in range(2, n + 1): new = [1] for j in range(1, i): new.append((last[j - 1] + last[j]) % MOD) new.append(1) last = new return new def main(): (a, b) = tu...
1221_D. Make The Fence Great Again
You have a fence consisting of n vertical boards. The width of each board is 1. The height of the i-th board is a_i. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from 2 to n, the condition a_{i-1} ≠ a_i ...
```python import sys input = sys.stdin.readline q = int(input()) for i in range(q): n = int(input()) dp = [[0] * n for _ in range(3)] prev = 0 for i in range(n): l, c = [int(item) for item in input().split()] if i == 0: dp[0][0] = 0 dp[1][0] = c dp[2]...
1248_A. Integer Points
DLS and JLS are bored with a Math lesson. In order to entertain themselves, DLS took a sheet of paper and drew n distinct lines, given by equations y = x + p_i for some distinct p_1, p_2, …, p_n. Then JLS drew on the same paper sheet m distinct lines given by equations y = -x + q_i for some distinct q_1, q_2, …, q_m. ...
```python t = int(input()) for a in range(t): n = int(input()) p = list(map(int, input().split())) m = int(input()) q = list(map(int, input().split())) cnt = 0 evencnt = 0 oddcnt = 0 for i in range(m): if(q[i] % 2 == 0): evencnt += 1 else: oddcnt += 1 for i in range(n): if(p[i] %2 == 0): cnt +=...
1266_E. Spaceship Solitaire
Bob is playing a game of Spaceship Solitaire. The goal of this game is to build a spaceship. In order to do this, he first needs to accumulate enough resources for the construction. There are n types of resources, numbered 1 through n. Bob needs at least a_i pieces of the i-th resource to build the spaceship. The numbe...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) a = [0]+list(map(int,input().split())) su = sum(a) le = [0]*(n+1) dct = {} for _ in range(int(input())): s,t,u = map(int,input().split()) ...
1331_C. ...And after happily lived ever they
Input The input contains a single integer a (0 ≤ a ≤ 63). Output Output a single number. Examples Input 2 Output 2 Input 5 Output 24 Input 35 Output 50
```python # And after happily lived ever they n = int(input()) d = [0,5,3,2,4,1] r=0 for dd in d: r=r*2 + bool(n&1<<(5-dd)) print (r) ```
1351_A. A+B (Trial Problem)
You are given two integers a and b. Print a+b. Input The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Each test case is given as a line of two integers a and b (-1000 ≤ a, b ≤ 1000). Output Print t integers — the required numbers a+b. Example ...
```python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio 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...
1371_C. A Cookie for You
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
```python #dt = {} for i in x: dt[i] = dt.get(i,0)+1 import sys;input = sys.stdin.readline inp,ip = lambda :int(input()),lambda :[int(w) for w in input().split()] for _ in range(inp()): a,b,n,m = ip() if a+b < n+m: print("No") continue no = min(n,m) if a < no or b < no: print("N...
1418_E. Expected Damage
You are playing a computer game. In this game, you have to fight n monsters. To defend from monsters, you need a shield. Each shield has two parameters: its current durability a and its defence rating b. Each monster has only one parameter: its strength d. When you fight a monster with strength d while having a shiel...
```python def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x...
1436_D. Bandit in a City
Bandits appeared in the city! One of them is trying to catch as many citizens as he can. The city consists of n squares connected by n-1 roads in such a way that it is possible to reach any square from any other square. The square number 1 is the main square. After Sunday walk all the roads were changed to one-way ro...
```python n = int(input()) parent = [0] + [x-1 for x in list(map(int, input().split()))] citizen = list(map(int, input().split())) sz = [1] * n for i in range(1, n): sz[parent[i]] = 0 #print(sz) for i in range(n-1, 0, -1): citizen[parent[i]] += citizen[i] sz[parent[i]] += sz[i] #print(citizen) #print(sz)...
1461_B. Find the Spruce
Holidays are coming up really soon. Rick realized that it's time to think about buying a traditional spruce tree. But Rick doesn't want real trees to get hurt so he decided to find some in an n × m matrix consisting of "*" and ".". <image> To find every spruce first let's define what a spruce in the matrix is. A set ...
```python for _ in range(int(input())): n,m = list(map(int,input().split())) arr = [] c = 0 for i in range(n): z = list(input()) c+=z.count("*") arr.append(z) ans = [] for i in range(n): ans.append([0]*m) for i in range(m): for g in range(n): ...
1486_C2. Guessing the Greatest (hard version)
The only difference between the easy and the hard version is the limit to the number of queries. This is an interactive problem. There is an array a of n different numbers. In one query you can ask the position of the second maximum element in a subsegment a[l..r]. Find the position of the maximum element in the arra...
```python from __future__ import print_function # for PyPy2 from collections import Counter, OrderedDict from itertools import permutations as perm from fractions import Fraction from collections import deque from sys import stdin from bisect import * from heapq import * # from math import * g = lambda : stdin.readl...
1536_E. Omkar and Forest
Omkar's most recent follower, Ajit, has entered the Holy Forest. Ajit realizes that Omkar's forest is an n by m grid (1 ≤ n, m ≤ 2000) of some non-negative integers. Since the forest is blessed by Omkar, it satisfies some special conditions: 1. For any two adjacent (sharing a side) cells, the absolute value of the d...
```python import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline input = sys.stdin.readline from collections import defaultdict from math import gcd for _ in range (int(input())): n,m = [int(i) for i in input().split()] mod = 10**9 + 7 a = [] cnt = 0 for i in range (n): ...
231_A. Team
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
```python n=int(input()) count=0 for _ in range(n): l=list(map(int,input().split())) if(sum(l)>=2): count+=1 print(count) ```
27_E. Number With The Given Amount Of Divisors
Given the number n, find the smallest positive integer which has exactly n divisors. It is guaranteed that for the given n the answer will not exceed 1018. Input The first line of the input contains integer n (1 ≤ n ≤ 1000). Output Output the smallest positive integer with exactly n divisors. Examples Input 4 ...
```python # # of divisors of p1^e1 p2^e2 ... is (e1 + 1)(e2 + 1) ... (en + 1) # Try all possible partitions, sort, see which gives the least answer? # 1: 1 # 2: 2 # 3: 4 # 4: 6, 2^3 = 8, 2 * 3 = 6 # 5: 16 # 6: 12 ans = [0, 1, 2, 4, 6, 16, 12, 64, 24, 36, 48, 1024, 60, 14096, 192, 144, 120, 65536, 180, 262144, 240, 57...
350_C. Bombs
You've got a robot, its task is destroying bombs on a square plane. Specifically, the square plane contains n bombs, the i-th bomb is at point with coordinates (xi, yi). We know that no two bombs are at the same point and that no bomb is at point with coordinates (0, 0). Initially, the robot is at point with coordinate...
```python import os,sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writ...
397_A. On Segment's Own Points
Our old friend Alexey has finally entered the University of City N — the Berland capital. Alexey expected his father to get him a place to live in but his father said it was high time for Alexey to practice some financial independence. So, Alexey is living in a dorm. The dorm has exactly one straight dryer — a 100 ce...
```python n=int(input()) d=[1]*100 a,b=map(int,input().split()) for i in range(n-1): l,r=map(int,input().split()) for i in range(l,r): d[i]=0 print(sum(d[a:b])) ```
41_B. Martian Dollar
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Mar...
```python I = lambda : map(int,input().split()) n,m = I() li = list(I()) ma = li[n-1] ans=m for i in range(n-2,-1,-1) : ma=max(ma,li[i]) ans = max(ans,m%li[i]+(m//li[i])*(ma)) print(ans) ```
468_A. 24 Game
Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game. Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ...
```python def test(n): if n >= 4: print('YES') if n%2 == 0: print("1 + 2 = 3") print("3 + 3 = 6") print("6 * 4 = 24") i = 4 while (i <= n-2): print(str(i+2)+' - '+str(i+1)+' = 1') print("24 * 1 = 24") ...
490_A. Team Olympiad
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
```python try: n = int(input()) nums = list(map(int, input().split())) def count(nums, x): cnt_ar = [] for idx, ele in enumerate(nums): if(ele == x): cnt_ar.append(idx+1) return cnt_ar def teams(nums): ones = count(nums, 1) twos = co...
514_A. Chewbaсca and Number
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
```python x = list(input()) for i in range(len(x)): if (i == 0 and '5' <= x[0] <= '8') or (i != 0 and '5' <= x[i] <= '9'): x[i] = str(9-int(x[i])) print(x[i], end = '') ```
540_B. School Marks
Little Vova studies programming in an elite school. Vova and his classmates are supposed to write n progress tests, for each test they will get a mark from 1 to p. Vova is very smart and he can write every test for any mark, but he doesn't want to stand out from the crowd too much. If the sum of his marks for all tests...
```python n, k, p, x, y = map(int, input().split()) b = list(map(int, input().split())) lower_bound = 1 for i in range(k): if b[i] < y: lower_bound += 1 ans = [1]*min((n+1) // 2 - lower_bound, n-k) while len(ans) < n-k: ans.append(y) if sum(ans+b) <= x and (n+1) // 2 - lower_bound >= 0 and p >= y: print(' '.joi...
58_A. Chat room
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
```python s=input() s=s.lower() ss='hello' cnt=0 for i in range(len(s)): if s[i]==ss[cnt]: cnt+=1 if cnt==5: break if cnt==5: print("YES") else: print("NO") ```
611_C. New Year and Domino
They say "years are like dominoes, tumbling one after the other". But would a year fit into a grid? I don't think so. Limak is a little polar bear who loves to play. He has recently got a rectangular grid with h rows and w columns. Each cell is a square, either empty (denoted by '.') or forbidden (denoted by '#'). Row...
```python from itertools import accumulate import math import bisect def list_sum(L1, L2): return [L1[i] + L2[i] for i in range(len(L1))] h, w = [int(x) for x in input().split()] M = [] for i in range(h): M.append([1 if c == '.' else 0 for c in input().rstrip()]) H = [[0]+list(accumulate(M[i][j] and M[i][j+...
630_R. Game
There is a legend in the IT City college. A student that failed to answer all questions on the game theory exam is given one more chance by his professor. The student has to play a game with the professor. The game is played on a square field consisting of n × n cells. Initially all cells are empty. On each turn a pla...
```python n = int(input("")) if n % 2 == 0: print (2) else: print (1) ```
65_C. Harry Potter and the Golden Snitch
Brothers Fred and George Weasley once got into the sporting goods store and opened a box of Quidditch balls. After long and painful experiments they found out that the Golden Snitch is not enchanted at all. It is simply a programmed device. It always moves along the same trajectory, which is a polyline with vertices at...
```python import math import functools import sys def eulen(x, y): r = functools.reduce(lambda x, y: x + y, \ map(lambda x: (x[0] - x[1]) ** 2, zip(x, y))) return math.sqrt(r) def output(t, p): print('YES') print(t) print(' '.join(map(str, p))) n = int(input()) points = [] for i in ra...
706_A. Beru-taxi
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy ...
```python import math, sys def solve(): bx,by = map(int, input().split()) dist = lambda f1, f2, v: math.sqrt(f1*f1+f2*f2) / v n = int(input()) ans = sys.maxsize for _ in range(n): x,y,v = map(int, input().split()) ans = min(ans, dist(x-bx, y-by,v)) return ans print(solve()) ```
749_D. Leaving Auction
There are n people taking part in auction today. The rules of auction are classical. There were n bids made, though it's not guaranteed they were from different people. It might happen that some people made no bids at all. Each bid is define by two integers (ai, bi), where ai is the index of the person, who made this ...
```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(...
772_C. Vulnerable Kerbals
You are given an integer m, and a list of n distinct integers between 0 and m - 1. You would like to construct a sequence satisfying the properties: * Each element is an integer between 0 and m - 1, inclusive. * All prefix products of the sequence modulo m are distinct. * No prefix product modulo m appears as...
```python maxn = 200500 g = [[] for i in range(maxn)] # Array de array g[i][j] en el cual la posicion i representa gcd(a,m) # y en el array [j] se guardan todos los ¨a¨ con gcd comunes dp = [0 for i in range(maxn)] # guarda la profundidad mayor para cada nodo ban = [0 for i in range(maxn)...
797_C. Minimal string
Petya recieved a gift of a string s with length up to 105 characters for his birthday. He took two more empty strings t and u and decided to play a game. This game has two possible moves: * Extract the first character of s and append t with this character. * Extract the last character of t and append u with this ...
```python s = list(input()) t = [] u = [] letters = [[] for _ in range(ord('z') - ord('a') + 1)] for (index, letter) in enumerate(s): letters[ord(letter) - ord('a')] += [index] for indexes in letters: indexes.reverse() current = 0 while current < len(s): if len(t) == 0: t += s[current] ...
817_E. Choosing The Commander
As you might remember from the previous round, Vova is currently playing a strategic game known as Rage of Empires. Vova managed to build a large army, but forgot about the main person in the army - the commander. So he tries to hire a commander, and he wants to choose the person who will be respected by warriors. Ea...
```python import sys from collections import defaultdict class Node: def __init__(self, val): self.val = val self.left = None self.right = None q = int(sys.stdin.readline()) root = Node(0) # def search(node, bit, ) for _ in range(q): l = list(map(int, sys.stdin.readline().split())) if l[0] == 1: # add b...
863_E. Turn Off The TV
Luba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive. Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at leas...
```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_siz...
889_B. Restoration of string
A substring of some string is called the most frequent, if the number of its occurrences is not less than number of occurrences of any other substring. You are given a set of strings. A string (not necessarily from this set) is called good if all elements of the set are the most frequent substrings of this string. Res...
```python import sys n = int(input()) a=[] for i in range(n): a.append([j for j in input()]) b=[] for i in range(n): b.append({}) for j in a[i]: if j in b[i]: print('NO') sys.exit() b[i][j]=1 c=[-1 for i in range(26)] d=[-1 for i in range(26)] e=[0 for i in range(26)] for word in a: l=ord(word[0])-97 e...
960_B. Minimize the error
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined <image>. You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1. Output the minimum poss...
```python n, k1, k2 = map(int, input().split()) a1 = list(map(int, input().split())) a2 = list(map(int, input().split())) e = [] for i in range(n): e.append(abs(a1[i]-a2[i])) #print(e) for k in range(k1+k2): e[e.index(max(e))] = abs(max(e) - 1) print(sum(i * i for i in e)) ```
987_E. Petr and Permutations
Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tr...
```python n = int(input()) a = list(map(int,input().split())) b = [x for x in range(1,n+1)] c = [(x,y) for x,y in zip(a,b)] d = set(c) cnt = 0 while d: x = d.pop() sti = x[1] while x[0] != sti: x = c[x[0]-1] cnt += 1 if x in d: d.remove(x) else: break ...
p02591 AtCoder Grand Contest 047 - Twin Binary Trees
Inspired by the tv series Stranger Things, bear Limak is going for a walk between two mirror worlds. There are two perfect binary trees of height H, each with the standard numeration of vertices from 1 to 2^H-1. The root is 1 and the children of x are 2 \cdot x and 2 \cdot x + 1. Let L denote the number of leaves in ...
```python #import random,time H=int(input()) #P=[i for i in range(2**(H-1))] #random.shuffle(P) P=list(map(lambda x:int(x)-1,input().split())) mod=10**9+7 inv=pow(2,mod-2,mod) L=2**(H-1) base_t=[1 for i in range(1+1<<H)] base_t[0]=0 for i in range(2,1+1<<H): base_t[i]=i*base_t[i>>1] base_t[i]%=mod base_s=[(...
p02722 AtCoder Beginner Contest 161 - Division or Subtraction
Given is a positive integer N. We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K. * Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K. In how many choices of K will N become 1 in the end? Constraints * 2 \leq N ...
```python N = int(input()) ans = set() def check(N, k): if k<2: return False N //= k while N: if (N-1)%k==0: return True if N%k: return False N //= k for k in range(1, int(N**0.5)+1): if (N-1)%k==0: ans.add(k) ans.add((N-1)//k) ...
p02853 DISCO Presents Discovery Channel Code Contest 2020 Qual - DDCC Finals
We held two competitions: Coding Contest and Robot Maneuver. In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen....
```python X, Y = list(map(int, input().split())) ans = 0 if X <= 3: ans += (4-X) * 100000 if Y <= 3: ans += (4-Y) * 100000 if X * Y == 1: ans += 400000 print(ans) ```
p02989 AtCoder Beginner Contest 132 - Divide the Problems
Takahashi made N problems for competitive programming. The problems are numbered 1 to N, and the difficulty of Problem i is represented as an integer d_i (the higher, the harder). He is dividing the problems into two categories by choosing an integer K, as follows: * A problem with difficulty K or higher will be for ...
```python n = int(input()) q= sorted(list(map(int,input().split()))) print(q[n//2]-q[n//2-1]) ```
p03130 Yahoo Programming Contest 2019 - Path
There are four towns, numbered 1,2,3 and 4. Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally. No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roa...
```python lst = [0] * 5 for _ in range(3): a, b = map(int, input().split()) lst[a] += 1 lst[b] += 1 if lst.count(2) == 2: print ('YES') else: print ('NO') ```
p03273 AtCoder Beginner Contest 107 - Grid Compression
There is a grid of squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column from the left is represented as (i, j). Each square is black or white. The color of the square is given as an H-by-W matrix (a_{i, j}). If a_{i, j} is `.`, the square (i, j) is white; if...
```python h,w = map(int,input().split()) a = [[i for i in input()] for j in range(h)] b = [a[i] for i in range(h) if "#" in a[i]] #print(b) t = [i for i in zip(*b)] c = zip(*[i for i in t if "#" in i]) for d in c: print("".join(d)) ```
p03430 AtCoder Grand Contest 021 - Reversed LCS
Takahashi has decided to give a string to his mother. The value of a string T is the length of the longest common subsequence of T and T', where T' is the string obtained by reversing T. That is, the value is the longest length of the following two strings that are equal: a subsequence of T (possibly non-contiguous), ...
```python import sys readline = sys.stdin.readline S = list(map(ord, readline().strip())) N = len(S) S = [None] + S + [None] K = int(readline()) if N == 1: ans = 1 elif N == 2: ans = 1 if S[1] == S[2]: ans = 2 if K: ans = 2 else: dp1 = [[0]*(K+1) for _ in range(N+2)] dp2 = [[0]...
p03588 Tenka1 Programmer Beginner Contest - Different Distribution
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
```python N = int(input()) AB = [list(map(int, input().split())) for i in range(N)] v = max(AB) print(v[0]+v[1]) ```
p03746 AtCoder Grand Contest 013 - Hamiltonish Path
You are given a connected undirected simple graph, which has N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices A_i and B_i. Your task is to find a path that satisfies the following conditions: * The path traverses two or more vertices. * The...
```python N,M=map(int,input().split()) edge=[set([]) for i in range(N)] for i in range(M): a,b=map(int,input().split()) edge[a-1].add(b-1) edge[b-1].add(a-1) visit=set([0]) ans=[0] pos=0 while True: for i in edge[pos]: if i not in visit: ans.append(i) visit.add(i) ...
p00012 A Point in a Triangle
There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of ea...
```python # A Point in a Triangle import math def simul_eq(a,b,c,d,e,f): # A = [[a,b],[d,e]] C = [c,f] detA = a*e - b*d # if detA == 0: raise # det(A) == 0. At = [[e,-b],[-d,a]] x = sum(map((lambda x,y: x*y), At[0], C)) / detA y = sum(map((lambda x,y: x*y), At[1], C)) / detA return (x,y)...
p00144 Packet Transportation
On the Internet, data is divided into packets, and each packet is transferred to a destination via a relay device called a router. Each router determines the next router to forward from the destination described in the packet. In addition, a value called TTL (Time To Live) is added to the packet to prevent it from bein...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0144 """ import sys from sys import stdin input = stdin.readline from enum import Enum class Graph(object): """ single source shortest path """ class Status(Enum): """ ?????????????¨??????¶??? """ w...
p00277 Programming Contest
A programming contest is held every year at White Tiger University. When the total number of teams is N, each team is assigned a team ID from 1 to N. The contest starts with all teams scoring 0 and runs continuously for L seconds. This year's contest will be broadcast on TV. Only the team with the highest score at the...
```python import sys from heapq import heappush, heappop, heapreplace def solve(): file_input = sys.stdin N, R, L = map(int, file_input.readline().split()) pq = [[0, i] for i in range(1, N + 1)] m = dict(zip(range(1, N + 1), pq)) time = [0] * (N + 1) INVALID = -1 pre_t = 0 for...
p00465 Authentication Level
problem Do you know Just Odd Inventions? The business of this company is to "just odd inventions". Here we call it JOI for short. JOI has two offices, each of which has square rooms of the same size arranged in a grid pattern. All the rooms that are in contact with each other have an ID card authentication function. ...
```python from heapq import heappop as pop from heapq import heappush as push INF = 1000000000000 def bfs(lst, used, que, w, h): v, y, x = pop(que) if y > 0 and not used[y - 1][x]: push(que, (lst[y - 1][x], y - 1, x)) used[y - 1][x] = True if h > y + 1 and not used[y + 1][x]: push(que, (lst[y + 1][x...
p01334 Let's JUMPSTYLE
Description F, who likes to dance, decided to practice a hardcore dance called JUMP STYLE at a certain dance hall. The floor is tiled in an N × N grid. To support the dance practice, each tile has the coordinates of the tile to jump to the next step. F has strong motor nerves through daily practice and can jump to an...
```python while True: n = int(input()) if n == 0:break to = [] fr = [[] for _ in range(n * n)] for i in range(n): line = list(map(int, input().split())) for j in range(n): x, y = line[2 * j:2 * j + 2] to.append(y * n + x) fr[y * n + x].append(i * n + j) order = [] used = [Fals...
p01814 Nearly Cyclic String
Almost periodic string Given the string S. Answer Q queries for this string S. In the i-th query, determine if S [l_i, \ r_i] can be a string of period t_i when you can change from S [l_i, \ r_i] to one character. S [l, \ r] represents the substring of the string S from the lth to the rth. If the character string W i...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): base = 37; MOD = 10**9 + 9 S = readline().strip() L = len(S) H = [0]*(L+1) pw = [1]*(L+1) ca = ord('a') v = 0 for i in range(L): H[i+1] = v = (v * base + (ord(S[i]) - ca)) % MOD v = 1 ...
p02098 The Mean of Angles
Problem Find the angle between the two given angles θ1 and θ2. Here, the angle between them is defined as "θ1 & plus; t'when t'is the one with the smallest absolute value among the t satisfying θ1 & plus; t = θ2 − t" as shown in the figure below. A image of angles Constraints The input satisfies the following condi...
```python s1 = int(input()) s2 = int(input()) a = min(s1,s2) b = max(s1,s2) if b-a>180: print((b+(360-b+a)/2)%360) else: print((a+b)/2) ```
p02236 Optimal Binary Search Tree
Optimal Binary Search Tree is a binary search tree constructed from $n$ keys and $n+1$ dummy keys so as to minimize the expected value of cost for a search operation. We are given a sequence $K = {k_1, k_2, ..., k_n}$ of $n$ distinct keys in sorted order $(k_1 < k_2 < ... < k_n)$, and we wish to construct a binary sea...
```python n=int(input()) A=[0.0]+[float(i) for i in input().split()] B=[float(i) for i in input().split()] W={} E={} for i in range(1,n+2): W[i,i-1] = B[i-1] E[i,i-1] = B[i-1],i for i in range(1,n+1): for j in range(i,n+1): W[i,j] = W[i,j-1]+A[j]+B[j] for i in range(1,n+1): E[i,i] = E[i,i-1][0] ...
p02382 Distance II
Your task is to calculate the distance between two $n$ dimensional vectors $x = \\{x_1, x_2, ..., x_n\\}$ and $y = \\{y_1, y_2, ..., y_n\\}$. The Minkowski's distance defined below is a metric which is a generalization of both the Manhattan distance and the Euclidean distance. \\[ D_{xy} = (\sum_{i=1}^n |x_i - y_i|^p)...
```python n = int(input()) x = list(map(int,input().split())) y = list(map(int,input().split())) d = [] for i in range(n): d.append(abs(x[i]-y[i])) print(sum(d)) print(sum(list(map(lambda x:x**2,d)))**(1/2)) print(sum(list(map(lambda x:x**3,d)))**(1/3)) print(max(d)) ```
1017_E. The Supersonic Rocket
After the war, the supersonic rocket became the most common public transportation. Each supersonic rocket consists of two "engines". Each engine is a set of "power sources". The first engine has n power sources, and the second one has m power sources. A power source can be described as a point (x_i, y_i) on a 2-D plan...
```python import sys # > 0 anti-clock, < 0 clockwise, == 0 same line def orientation(p1, p2, p3): return (p2[0] - p1[0])*(p3[1] - p1[1]) - (p2[1] - p1[1])*(p3[0] - p1[0]) def dot(p1, p2, p3, p4): return (p2[0]-p1[0])*(p4[0]-p3[0]) + (p2[1]-p1[1])*(p4[1]-p3[1]) def theta(p1, p2): dx = p2[0] - p1[0] ...
1041_B. Buying a TV Set
Monocarp has decided to buy a new TV set and hang it on the wall in his flat. The wall has enough free space so Monocarp can buy a TV set with screen width not greater than a and screen height not greater than b. Monocarp is also used to TV sets with a certain aspect ratio: formally, if the width of the screen is w, an...
```python from fractions import gcd a, b, x, y = map(int, input().split()) gcd = gcd(x, y) x /= gcd y /= gcd res = int(min(a // x, b // y)) print(res) ```
1064_A. Make a triangle!
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks. What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ...
```python a, b, c = map(int, input().split()) m = max(a, b, c) n = a+b+c-m if n<=m: print(m-n+1) else: print(0) ```
1105_D. Kilani and the Game
Kilani is playing a game with his friends. This game can be represented as a grid of size n × m, where each cell is either empty or blocked, and every player has one or more castles in some cells (there are no two castles in one cell). The game is played in rounds. In each round players expand turn by turn: firstly, t...
```python # ------------------- fast io -------------------- 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...
1153_C. Serval and Parenthesis Sequence
Serval soon said goodbye to Japari kindergarten, and began his life in Japari Primary School. In his favorite math class, the teacher taught him the following interesting definitions. A parenthesis sequence is a string, containing only characters "(" and ")". A correct parenthesis sequence is a parenthesis sequence ...
```python n = int(input()) s = list(input()) if n % 2 == 1: print(":(") else: op = n // 2 - s.count("(") for i in range(n): if s[i] == "?": if op > 0: s[i] = "(" else: s[i] = ")" op -= 1 #print("".join(s)) b = 0 for i in...
1175_B. Catch Overflow!
You are given a function f written in some basic language. The function accepts an integer value, which is immediately written into some variable x. x is an integer variable and can be assigned values from 0 to 2^{32}-1. The function contains three types of commands: * for n — for loop; * end — every command betw...
```python import sys MAX_NUMBER = 2**32 - 1 def solve(): input = sys.stdin.readline n = int(input()) stack = [] for _ in range(n): oper = input().strip() if oper == 'add': stack.append(1) elif oper == 'end': cur = 0 while len(stack) > 0:...
1194_A. Remove a Progression
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
```python test=int(input()) while(test!=0): n,x=map(int,input().split()) print(2*x) test-=1 ```
1272_F. Two Bracket Sequences
You are given two bracket sequences (not necessarily regular) s and t consisting only of characters '(' and ')'. You want to construct the shortest regular bracket sequence that contains both given bracket sequences as subsequences (not necessarily contiguous). Recall what is the regular bracket sequence: * () is t...
```python def scs(str1, str2): """Shortest Common Supersequence""" INF = 10 ** 9 dp = [[[INF] * 210 for _ in range(210)] for _ in range(210)] dp[0][0][0] = 0 prv = [[[None] * 210 for _ in range(210)] for _ in range(210)] len_str1 = len(str1) len_str2 = len(str2) str1 += "#" str2...
1296_A. Array with Odd Sum
You are given an array a consisting of n integers. In one move, you can choose two indices 1 ≤ i, j ≤ n such that i ≠ j and set a_i := a_j. You can perform such moves any number of times (possibly, zero). You can choose different indices in different operations. The operation := is the operation of assignment (i.e. yo...
```python T=int(input()) t=0 while t<T: N=int(input()) A=list(map(int, input().split())) n=0 pari=0 dispari=0 somma=0 while n<N: a=A[n] somma=somma+a if a%2==1: dispari=dispari+1 else: pari=pari+1 n=n+1 if somma %2==1: ...
131_A. cAPS lOCK
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
```python a=str(input()) b=a[:];c=a[:];d=a[:] b=b.upper();d=d.upper();c=c.lower() if a==b: a=a.lower() elif a[0]==c[0]: if len(a)>1: if a[1:]==d[1:]: a=a.capitalize() else: pass else: a=a.upper() else: pass print(a) ```
1338_C. Perfect Triples
Consider the infinite sequence s of positive integers, created by repeating the following steps: 1. Find the lexicographically smallest triple of positive integers (a, b, c) such that * a ⊕ b ⊕ c = 0, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). * a, b, ...
```python import sys input = sys.stdin.readline import bisect L=[4**i for i in range(30)] def calc(x): fami=bisect.bisect_right(L,x)-1 base=(x-L[fami])//3 cl=x%3 if cl==1: return L[fami]+base else: cl1=L[fami]+base ANS=0 for i in range(30): x=cl1//L[i]...
1360_B. Honest Coach
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i. You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team. You want...
```python for i in range(int(input())): n=int(input()) lst=list() x=list(map(int,input().split())) x.sort() if len(set(x))!=len(x): print(0) else: for i in range(n-1): lst.append(x[i+1]-x[i]) print(min(lst)) ```
1380_C. Create The Teams
There are n programmers that you want to split into several non-empty teams. The skill of the i-th programmer is a_i. You want to assemble the maximum number of teams from them. There is a restriction for each team: the number of programmers in the team multiplied by the minimum skill among all programmers in the team ...
```python def f(a,b): if a%b == 0: return(a//b) else: return(a//b +1) t = int(input()) while(t>0): t = t-1 n,x = map(int,input().split()) a = input() A = list(map(int,list(a.split()))) A.sort() table = [0]*(n) b = [0]*(n) for i in range(n): b[i] = f(x,A[i]...
1400_C. Binary String Reconstruction
Consider the following process. You have a binary string (a string where each character is either 0 or 1) w of length n and an integer x. You build a new binary string s consisting of n characters. The i-th character of s is chosen as follows: * if the character w_{i-x} exists and is equal to 1, then s_i is 1 (forma...
```python def fn1(n,num,lis): for i in range(n): if i-x>=0 and num[i-x]==1: lis.append(1) elif i+x<n and num[i+x]==1: lis.append(1) else: lis.append(0) def fn2(st,s,num): if st==s: for i in num: print(i,end="") print() e...
1444_D. Rectangular Polyline
One drew a closed polyline on a plane, that consisted only of vertical and horizontal segments (parallel to the coordinate axes). The segments alternated between horizontal and vertical ones (a horizontal segment was always followed by a vertical one, and vice versa). The polyline did not contain strict self-intersecti...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): t = int(input()) for _ in range(t): if _ != 0: input() h = int(input()) l1 = list(map(int,input().split())) v = int(input()) l2 = list(map(int,input().split())) ...
1469_E. A Bit Similar
Let's call two strings a and b (both of length k) a bit similar if they have the same character in some position, i. e. there exists at least one i ∈ [1, k] such that a_i = b_i. You are given a binary string s of length n (a string of n characters 0 and/or 1) and an integer k. Let's denote the string s[i..j] as the su...
```python import sys input = sys.stdin.buffer.readline T = int(input()) for _ in range(T): n, k = map(int, input().split()) a = list(input().decode()[:n]) cc = max(0, k-20) can, one, rm = set(), 0, k-cc for u in range(n-rm+1): if one >= cc: p = 0 for v in range(rm):...
1495_A. Diamond Miner
Diamond Miner is a game that is similar to Gold Miner, but there are n miners instead of 1 in this game. The mining area can be described as a plane. The n miners can be regarded as n points on the y-axis. There are n diamond mines in the mining area. We can regard them as n points on the x-axis. For some reason, no m...
```python """ """ import sys from sys import stdin tt = int(stdin.readline()) for loop in range(tt): n = int(stdin.readline()) x = [] y = [] for i in range(2*n): X,Y = map(int,stdin.readline().split()) X = abs(X) Y = abs(Y) if Y == 0: x.append(X) ...
172_D. Calendar Reform
Reforms have started in Berland again! At this time, the Parliament is discussing the reform of the calendar. To make the lives of citizens of Berland more varied, it was decided to change the calendar. As more and more people are complaining that "the years fly by...", it was decided that starting from the next year t...
```python F = {} def f(k): if not k in F: s, i, j = 0, 4, 4 while i <= k: s += i * f(k // i) i += j + 1 j += 2 F[k] = (k * (k + 1)) // 2 - s return F[k] def g(k): s, i, j = 0, 4, 4 while i <= k: s += (i - 1) * f(k // i) i += j...
216_E. Martian Luck
You know that the Martians use a number system with base k. Digit b (0 ≤ b < k) is considered lucky, as the first contact between the Martians and the Earthlings occurred in year b (by Martian chronology). A digital root d(x) of number x is a number that consists of a single digit, resulting after cascading summing of...
```python k, b, n = map(int, input().split()) digits = list(map(int, input().split())) def ans0(): j = -1 answer = 0 for i in range(n): if digits[i] != 0 or i < j: continue j = i while j < n and digits[j] == 0: j += 1 r = j - i answer += r ...
23_E. Tree
Recently Bob invented a new game with a tree (we should remind you, that a tree is a connected graph without cycles): he deletes any (possibly, zero) amount of edges of the tree, and counts the product of sizes of the connected components left after the deletion. Your task is to find out the maximum number that Bob can...
```python from fractions import Fraction n = int(input()) adj = [list() for x in range(n)] H = [0] * n F = [0] * n FoH = [list() for x in range(n)] sz = 0 order = [0] * n pi = [-1] * n def dfs(u, p = -1): global pi, order, sz pi[u] = p for v in adj[u]: if v != p: dfs(v, u) order[sz] = u sz += 1 ...
265_C. Escape from Stones
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order. The stones always fall to the center of Liss's inter...
```python s=input() r=[] l=[] num=1 for i in s: if i=='r': r.append(num) elif i=='l': l.append(num) num+=1 res=r+l[::-1] for i in res: print(i) ```
289_C. Polo the Penguin and Strings
Little penguin Polo adores strings. But most of all he adores strings of length n. One day he wanted to find a string that meets the following conditions: 1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct. 2. No two neighbouring...
```python def fastio(): import sys from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() MOD = 10**9 + 7 I = la...
430_E. Guess the Tree
Iahub and Iahubina went to a picnic in a forest full of trees. Less than 5 minutes passed before Iahub remembered of trees from programming. Moreover, he invented a new problem and Iahubina has to solve it, otherwise Iahub won't give her the food. Iahub asks Iahubina: can you build a rooted tree, such that * each ...
```python def DFS(x): for i in range(x): if(Seen[i][x]): continue if(Rem[i]>=C[x]): if(Rem[i]==C[x] and len(Children[i])==0): continue Rem[i]-=C[x] Parent[x]=i Children[i].append(x) return True for...
49_A. Sleuth
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans...
```python s = input() for x in s: if x != ' ' and x != '?': t = x if t in 'aeiouyAEIOUY': print('YES') else: print('NO') ```
523_C. Name Quest
A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy...
```python import sys count = 0 matrix = [] for line in sys.stdin: if count == 0: pattern = line.strip() count += 1 else: s = line.strip() dp1 = [0 for i in range(len(s))] dp2 = [0 for i in range(len(s))] i = 0 j = 0 while i < len(pattern) and j < len(s): if pattern[i] == s[j]: ...
54_A. Presents
The Hedgehog likes to give presents to his friend, but no less he likes to receive them. Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he c...
```python def searchInRange(arr: list, start: int, end: int) -> int: for i in range(start, end + 1): if i in arr: return i return -1 n, k = [int(item) for item in input().split(' ')] holidays = [int(item) for item in input().split(' ')] del holidays[:1] ans, start, end = 0, 1, k while sta...
576_B. Invariance of Tree
A tree of size n is an undirected connected graph consisting of n vertices without cycles. Consider some tree with n vertices. We call a tree invariant relative to permutation p = p1p2... pn, if for any two vertices of the tree u and v the condition holds: "vertices u and v are connected by an edge if and only if vert...
```python def read_data(): n = int(input()) ps = list(map(int, input().split())) return n, ps def solve(n, ps): ps = [p - 1 for p in ps] cycles = [0] * n roots = [] has_odd_cycle = False for i in range(n): if cycles[i] > 0: continue q = ps[i] cycle = ...
598_F. Cut Length
Given simple (without self-intersections) n-gon. It is not necessary convex. Also you are given m lines. For each line find the length of common part of the line and the n-gon. The boundary of n-gon belongs to polygon. It is possible that n-gon contains 180-degree angles. Input The first line contains integers n and...
```python def main(): from math import hypot n, m = map(int, input().split()) vertices = list(tuple(map(float, input().split())) for _ in range(n)) ax, ay = vertices[-1] for i, (bx, by) in enumerate(vertices): vertices[i], ax, ay = (bx, by, bx - ax, by - ay), bx, by for _ in range(m): ...
61_D. Eternal Victory
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal! He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too ti...
```python import sys def solve(): n, = rv() edges = [list() for _ in range(n)] for i in range(n - 1): x, y, w, = rv() edges[x - 1].append((y - 1, w)) edges[y - 1].append((x - 1, w)) res = dfs(0, -1, edges) print(res[0] * 2 - res[1]) def dfs(cur, prev, edges): total, sing...
63_C. Bulls and Cows
The "Bulls and Cows" game needs two people to play. The thinker thinks of a number and the guesser tries to guess it. The thinker thinks of a four-digit number in the decimal system. All the digits in the number are different and the number may have a leading zero. It can't have more than one leading zero, because all...
```python import sys def solve(): n, = rv() works = 0 lastworks = -1 guesses = list() for i in range(n): a, b, c, = rv() acopy = a charcount = [0] * 10 for x in range(4): charcount[acopy % 10] += 1 acopy //= 10 guesses.append((tolist(a...
669_A. Little Artem and Presents
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem...
```python print((2*int(input())+1)//3) # Made By Mostafa_Khaled ```
690_D1. The Wall (easy)
"The zombies are lurking outside. Waiting. Moaning. And when they come..." "When they come?" "I hope the Wall is high enough." Zombie attacks have hit the Wall, our line of defense in the North. Its protection is failing, and cracks are showing. In places, gaps have appeared, splitting the wall into multiple segment...
```python # 690 D1 r,c = [int(i) for i in input().split()] for i in range(r-1): input() s = input() segs = 0 prev = '.' for x in s: if x=='B' and prev =='.': segs += 1 prev = x print(segs) ```
714_C. Sonya and Queries
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: 1. + ai — add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur...
```python # Problem : C. Sonya and Queries # Contest : Codeforces Round #371 (Div. 2) # URL : https://codeforces.com/contest/714/problem/C # Memory Limit : 256 MB # Time Limit : 1000 ms # Powered by CP Editor (https://github.com/cpeditor/cpeditor) """ // Author : snape_here - Susanta Mukherjee """ from __fut...
758_F. Geometrical Progression
For given n, l and r find the number of distinct geometrical progression, each of which contains n distinct integers not less than l and not greater than r. In other words, for each progression the following must hold: l ≤ ai ≤ r and ai ≠ aj , where a1, a2, ..., an is the geometrical progression, 1 ≤ i, j ≤ n and i ≠ j...
```python Primes = [2, 3, 5, 7] def check (a, b) : for pr in Primes : if a % pr == 0 and b % pr == 0 : return False while (b) : a %= b a ^= b b ^= a a ^= b return a == 1 n, l, r = map(int, input().split()) if n == 1 : ans = r - l + 1 elif n == 2 : ans = (r - l + 1) * (r - l) else : n -= 1 l -= 1 ...
803_C. Maximal GCD
You are given positive integer number n. You should create such strictly increasing sequence of k positive numbers a1, a2, ..., ak, that their sum is equal to n and greatest common divisor is maximal. Greatest common divisor of sequence is maximum of such numbers that every element of sequence is divisible by them. I...
```python from collections import deque from math import sqrt n,k = map(int, input().split()) sum_k = k*(k+1)/2 if(sum_k>n): print(-1) else: pos = deque() for x in range(int(sqrt(n)), 0, -1): if(n%x==0): pos.appendleft(x) if(x*x!= n): pos.append(int(n/x)) ...
828_A. Restaurant Tables
In a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater tabl...
```python _,o,d=map(int,input().split()) h=0 a=list(map(int,input().split())) n=0 for i in a: if i==1: if o>0: o-=1 elif d>0: d-=1 h+=1 elif h>0: h-=1 else: n+=1 elif i==2: if d>0: d-=1 else: ...
84_B. Magical Array
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical. Valera absolutel...
```python from sys import stdin, stdout from math import factorial n = int(stdin.readline()) values = list(map(int, stdin.readline().split())) ans = 0 cnt = 1 for i in range(1, n): if values[i] != values[i - 1]: ans += cnt * (cnt + 1) // 2 cnt = 1 else: cnt += 1 ans += cnt * (cnt + 1)...
898_D. Alarm Clock
Every evening Vitalya sets n alarm clocks to wake up tomorrow. Every alarm clock rings during exactly one minute and is characterized by one integer ai — number of minute after midnight in which it rings. Every alarm clock begins ringing at the beginning of the minute and rings during whole minute. Vitalya will defin...
```python n, m, k = map(int,input().split()) a = list(map(int,input().split())) a.sort() vis = [] for i in range(n): vis.append(0) ans = l = r = 0 cnt = 1 while(r < n): while(a[r]-a[l]+1 > m): if(vis[l] == 0): cnt -= 1 l += 1 if cnt >= k: ans += 1 vis[r] = 1; cnt -= 1...
919_E. Congruence Equation
Given an integer x. Your task is to find out how many positive integers n (1 ≤ n ≤ x) satisfy $$$n ⋅ a^n ≡ b (mod\;p), where a, b, p$$$ are all known constants. Input The only line contains four integers a,b,p,x (2 ≤ p ≤ 10^6+3, 1 ≤ a,b < p, 1 ≤ x ≤ 10^{12}). It is guaranteed that p is a prime. Output Print a sin...
```python import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write i...
946_D. Timetable
Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university. There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th ho...
```python n, m, k = map(int, input().split()) DATA = [input() for i in range(n)] #dp[n_day][used_cost] #ans = min(dp[n_day][used_cost] for used_cost in range(k + 1)) #dp[n_day][used_cost] := min(dp[n_day - 1][prev_cost] + cost(pay used_cost - prev_cost in n_day) for prev_cost in range(used_cost + 1)) INF = 1 << 60 dp ...
975_B. Mancala
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes. <image> Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in th...
```python A = [int(x) for x in input().split()] N = 14 result = 0 for i in range(N): B = A[:] to_distribute = B[i] B[i] = 0 for j in range(N): B[j] += to_distribute // N for j in range(1, to_distribute % N + 1): B[(i + j) % N] += 1 result = max(result, sum([x f...
995_A. Tesla
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be repre...
```python n, k = map(int, input().split()) grid = [ list(map(int, input().split())) for _ in range(4) ] possible = True if all(c != 0 for cars in (grid[1], grid[2]) for c in cars): if all(a != b for (a, b) in zip(grid[0], grid[1])): if all(a != b for (a, b) in zip(grid[3], grid[2])): ...
p02640 AtCoder Beginner Contest 170 - Crane and Turtle
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs. Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct. Constraints ...
```python x,y=list(map(int,input().split())) if 2*x<=y<=4*x and y%2==0: print("Yes") else: print("No") ```