name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
1446_D1. Frequency Problem (Easy Version)
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the...
```python import sys from collections import defaultdict, Counter import sys import os from io import BytesIO, IOBase #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file....
1470_D. Strange Housing
Students of Winter Informatics School are going to live in a set of houses connected by underground passages. Teachers are also going to live in some of these houses, but they can not be accommodated randomly. For safety reasons, the following must hold: * All passages between two houses will be closed, if there are...
```python import io import os from collections import deque def solve(N, M, edges): graph = [[] for i in range(N)] for u, v in edges: graph[u].append(v) graph[v].append(u) source = 0 q = deque([source]) isTeacher = {} while q: node = q.popleft() if node in is...
1497_C2. k-LCM (hard version)
It is the hard version of the problem. The only difference is that in this version 3 ≤ k ≤ n. You are given a positive integer n. Find k positive integers a_1, a_2, …, a_k, such that: * a_1 + a_2 + … + a_k = n * LCM(a_1, a_2, …, a_k) ≤ n/2 Here LCM is the [least common multiple](https://en.wikipedia.org/wiki...
```python for nt in range(int(input())): n, k = map(int,input().split()) ans = [1]*(k-3) n -= (k-3) if n%2: ans.extend([1, n//2, n//2]) else: if n//2%2: ans.extend([2, n//2-1, n//2-1]) else: ans.extend([n//2, n//4, n//4]) print (*ans) ```
151_B. Phone Numbers
Winters are just damn freezing cold in Nvodsk! That's why a group of n friends prefers to take a taxi, order a pizza and call girls. The phone numbers in the city consist of three pairs of digits (for example, 12-34-56). Each friend has a phonebook of size si (that's the number of phone numbers). We know that taxi numb...
```python def num_type(h): if h.count(h[0]) == 6: return 0 for i in range(1,6): if h[i] >= h[i-1]: return 2 return 1 def pri(g,ind,p): [maxx,st]=[0,[]] for i in range(len(p)): if p[i][ind] == maxx: st.append(p[i][-1]) elif p[i][ind] > maxx: ...
1547_B. Alphabetical Strings
A string s of length n (1 ≤ n ≤ 26) is called alphabetical if it can be obtained using the following algorithm: * first, write an empty string to s (i.e. perform the assignment s := ""); * then perform the next step n times; * at the i-th step take i-th lowercase letter of the Latin alphabet and write it eithe...
```python t = int(input()) for amp in range(t): s = input() n = len(s) y = -1 for i in range(n): if s[i] == "a" : y = i break sol = "YES" if y == -1 : sol = "NO" else: val = ord(s[y]) l = z = y q = 1 while ...
194_E. Hamming Distance
Hamming distance between strings a and b of equal length (denoted by h(a, b)) is equal to the number of distinct integers i (1 ≤ i ≤ |a|), such that ai ≠ bi, where ai is the i-th symbol of string a, bi is the i-th symbol of string b. For example, the Hamming distance between strings "aba" and "bba" equals 1, they have ...
```python h = [[0 in range(10)] for j in range(10)] for i in range(1, 4): h[i] = [0 for j in range(i + 1)] + list(map(int, input().split())) #for i in range(1, 4): # print(" ".join(map(str, h[i][1:5]))) if (h[1][2] + h[1][3] < h[2][3] or (h[1][2] + h[1][3] - h[2][3]) % 2 == 1): print("-1") exit(0) BB = ...
242_B. Big Segment
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want...
```python n = int(input()) segments = [] minl = 10**9 maxr = 1 for i in range(n): a, b = map(int, input().split()) segments.append((a, b)) if a<minl: minl = a if b>maxr: maxr = b if (minl, maxr) in segments: print(segments.index((minl, maxr))+1) else: print(-1) ...
290_C. WTF?
HAI I HAS A TUX GIMMEH TUX I HAS A FOO ITS 0 I HAS A BAR ITS 0 I HAS A BAZ ITS 0 I HAS A QUZ ITS 1 TUX IS NOW A NUMBR IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0 I HAS A PUR GIMMEH PUR PUR IS NOW A NUMBR FOO R SUM OF FOO AN PUR ...
```python """ IM IN YR LOOP NERFIN YR TUX TIL BOTH SAEM TUX AN 0 I HAS A PUR GIMMEH PUR PUR IS NOW A NUMBR FOO R SUM OF FOO AN PUR BAR R SUM OF BAR AN 1 BOTH SAEM BIGGR OF PRODUKT OF FOO AN QUZ AN PRODUKT OF BAR BAZ AN PRODUKT OF FOO AN QUZ O RLY? YA RLY BAZ R FOO QUZ R BAR OIC IM OUTTA YR LOOP BAZ IS NOW A NUMBAR VISI...
316_B1. EKG
In the rush of modern life, people often forget how beautiful the world is. The time to enjoy those around them is so little that some even stand in queues to several rooms at the same time in the clinic, running from one queue to another. (Cultural note: standing in huge and disorganized queues for hours is a native ...
```python def f(x, p): q = [] while x: q.append(x) x = p[x] return q from collections import defaultdict n, k = map(int, input().split()) t = list(map(int, input().split())) p = [0] * (n + 1) for i, j in enumerate(t, 1): p[j] = i p = [f(i, p) for i, j in enumerate(t, 1) if j == 0] s = de...
361_B. Levko and Permutation
Levko loves permutations very much. A permutation of length n is a sequence of distinct positive integers, each is at most n. Let’s assume that value gcd(a, b) shows the greatest common divisor of numbers a and b. Levko assumes that element pi of permutation p1, p2, ... , pn is good if gcd(i, pi) > 1. Levko considers ...
```python from sys import stdin,stdout n,k=map(int ,stdin.readline().strip().split()) if n==k: print(-1) else: result=[0]*n for i in range(n-k,n): result[i]=i+1 for i in range(1,n-k): result[i]=i result[0]=n-k print(*result,sep=' ') ```
405_D. Toy Sum
Little Chris is very keen on his toy blocks. His teacher, however, wants Chris to solve more problems, so he decided to play a trick on Chris. There are exactly s blocks in Chris's set, each block has a unique number from 1 to s. Chris's teacher picks a subset of blocks X and keeps it to himself. He will give them bac...
```python import sys from math import gcd,sqrt,ceil from collections import defaultdict,Counter,deque import math # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') import os import sys from io import BytesIO, IO...
432_E. Square Tiling
You have an n × m rectangle table, its cells are not initially painted. Your task is to paint all cells of the table. The resulting picture should be a tiling of the table with squares. More formally: * each cell must be painted some color (the colors are marked by uppercase Latin letters); * we will assume that ...
```python import sys input = sys.stdin.readline n,m=map(int,input().split()) ANS=[[-1]*m for i in range(n)] for i in range(n): for j in range(m): if ANS[i][j]==-1: for koma in ["A","B","C","D","E","F"]: for k,l in [(i-1,j),(i,j-1),(i+1,j),(i,j+1)]: if 0<=k<...
455_B. A Lot of Games
Andrew, Fedor and Alex are inventive guys. Now they invent the game with strings for two players. Given a group of n non-empty strings. During the game two players build the word together, initially the word is empty. The players move in turns. On his step player must add a single letter in the end of the word, the re...
```python """ Codeforces Contest 260 Div 1 Problem B Author : chaotic_iak Language: Python 3.3.4 """ def main(): n,k = read() s = set() for i in range(n): s.add(read(0)) s = list(s) s.sort() s = treeify(s) res = solve(s) if res == 0: # neither: second player win print("Second"...
500_B. New Year Permutation
User ainta has a permutation p1, p2, ..., pn. As the New Year is coming, he wants to make his permutation as pretty as possible. Permutation a1, a2, ..., an is prettier than permutation b1, b2, ..., bn, if and only if there exists an integer k (1 ≤ k ≤ n) where a1 = b1, a2 = b2, ..., ak - 1 = bk - 1 and ak < bk all ho...
```python import sys n=int(input()) a=list(map(lambda x:int(x),sys.stdin.readline().split())) matrix=[] for _ in range(n): row=input() row=list(row) row=list(map(lambda x:int(x),row)) matrix.append(row) class DisjSet: def __init__(self, n): # Constructor to create and # initialize ...
525_E. Anya and Cubes
Anya loves to fold and stick. Today she decided to do just that. Anya has n cubes lying in a line and numbered from 1 to n from left to right, with natural numbers written on them. She also has k stickers with exclamation marks. We know that the number of stickers does not exceed the number of cubes. Anya can stick a...
```python fact = [ 1 ] for i in range( 1, 20, 1 ): fact.append( fact[ i - 1 ] * i ) from collections import defaultdict N, K, S = map( int, input().split() ) A = list( map( int, input().split() ) ) ldp = [ [ defaultdict( int ) for i in range( K + 1 ) ] for j in range( 2 ) ] ldp[ 0 ][ 0 ][ 0 ] = 1 for i in range( N...
551_A. GukiZ and Contest
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
```python n,x=int(input()),list(map(int, input().split(" "))) tmp=sorted(x,reverse=True) for i in x: print(tmp.index(i)+1) ```
578_B. "Or" Game
You are given n numbers a1, a2, ..., an. You can perform at most k operations. For each operation you can multiply one of the numbers by x. We want to make <image> as large as possible, where <image> denotes the bitwise OR. Find the maximum possible value of <image> after performing at most k operations optimally. I...
```python def main(): n, k, x = map(int, input().split()) aa = list(map(int, input().split())) x, lo, u = x ** k, [0] * n, 0 for i, a in enumerate(aa): lo[i] = u u |= a hi, u = [], 0 for a in reversed(aa): hi.append(u) u |= a hi.reverse() for i, u, a, v in...
59_E. Shortest Path
In Ancient Berland there were n cities and m two-way roads of equal length. The cities are numbered with integers from 1 to n inclusively. According to an ancient superstition, if a traveller visits three cities ai, bi, ci in row, without visiting other cities between them, a great disaster awaits him. Overall there ar...
```python #https://codeforces.com/contest/59/problem/E class Pathclass: def __init__(self,node_number,nextnode): self.number = node_number self.next = nextnode import collections lis = input().split() n,m,k = int(lis[0]),int(lis[1]),int(lis[2]) adjlis = [collections.deque([]) for i in range(n)] for i in range(m):...
621_C. Wet Shark and Flowers
There are n sharks who grow flowers for Wet Shark. They are all sitting around the table, such that sharks i and i + 1 are neighbours for all i from 1 to n - 1. Sharks n and 1 are neighbours too. Each shark will grow some number of flowers si. For i-th shark value si is random integer equiprobably chosen in range from...
```python import math def numberOfMultiples(n, z): return n // z if __name__ == "__main__": n, p = map(int, input().split()) f = [0] * n g = [0] * n for i in range(n): l, r = map(int, input().split()) #print((r - l + 1) - len([i for i in range(l, r + 1) if i % p == 0])) f...
643_A. Bear and Colors
Bear Limak has n colored balls, arranged in one long row. Balls are numbered 1 through n, from left to right. There are n possible colors, also numbered 1 through n. The i-th ball has color ti. For a fixed interval (set of consecutive elements) of balls we can define a dominant color. It's a color occurring the bigges...
```python # n=int(input()) # n,k=map(int,input().split()) '''l=0 r=10**13 while l+1<r: mid=(l+r)//2 val=(max(0,b_b*mid-b)*rb+max(0,b_s*mid-s)*rs+max(0,b_c*mid-b)*rc) if val>money: r=mid if val<=money: l=mid''' # arr=list(map(int,input().split())) # n=int(input()) #if all([size%ele==0 for...
670_A. Holidays
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. Input The first line of the input contains a ...
```python n = int(input()) if n % 7 == 0: print(n // 7 * 2, n // 7 * 2) else: x = (n // 7 + 1) * 7 if x - n == 6: print((n // 7) * 2, (n // 7) * 2 + 1) else: if x - n == 1: print((n // 7) * 2 + 1, (n // 7) * 2 + 2) else: print((n // 7) * 2, (n // 7) * 2 +...
691_C. Exponential notation
You are given a positive decimal number x. Your task is to convert it to the "simple exponential notation". Let x = a·10b, where 1 ≤ a < 10, then in general case the "simple exponential notation" looks like "aEb". If b equals to zero, the part "Eb" should be skipped. If a is an integer, it should be written without d...
```python import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_(...
716_C. Plus and Square Root
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1. When ZS the Coder is at level k, he can : 1. Pr...
```python n=int(input()) print(2) for lvl in range(2,n+1): print(lvl*(lvl+1)*(lvl+1)-(lvl-1)) ```
784_A. Numbers Joke
Input The input contains a single integer a (1 ≤ a ≤ 30). Output Output a single integer. Example Input 3 Output 27
```python ls = [0, 4, 22, 27, 58, 85, 94, 121, 166, 202, 265, 274, 319, 346, 355, 378, 382, 391, 438, 454, 483, 517, 526, 535, 562, 576, 588, 627, 634, 636, 645, 648, 654, 663, 666, 690, 706, 728, 729, 762, 778, 825, ] print(ls[int(input())]) ```
851_A. Arpa and a research in Mexican wave
Arpa is researching the Mexican wave. There are n spectators in the stadium, labeled from 1 to n. They start the Mexican wave at time 0. * At time 1, the first spectator stands. * At time 2, the second spectator stands. * ... * At time k, the k-th spectator stands. * At time k + 1, the (k + 1)-th specta...
```python import math,itertools,fractions,heapq,collections,bisect,sys,queue,copy sys.setrecursionlimit(10**7) inf=10**20 mod=10**9+7 dd=[(-1,0),(0,1),(1,0),(0,-1)] ddn=[(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] # def LF(): return [float(x) ...
875_C. National Property
You all know that the Library of Bookland is the largest library in the world. There are dozens of thousands of books in the library. Some long and uninteresting story was removed... The alphabet of Bookland is so large that its letters are denoted by positive integers. Each letter can be small or large, the large ve...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(...
89_B. Widget Library
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on t...
```python n = int(input()) widgets = {} class Widget: def __init__(self, w, h): self.w = w self.h = h def calc_size(self): return (self.w, self.h) class Box: def __init__(self, direction): self.dir = direction self.packed = [] self.border = 0 self.s...
920_D. Tanks
Petya sometimes has to water his field. To water the field, Petya needs a tank with exactly V ml of water. Petya has got N tanks, i-th of them initially containing ai ml of water. The tanks are really large, any of them can contain any amount of water (no matter how large this amount is). Also Petya has got a scoop t...
```python import sys n, k, v = map(int, input().split()) a = list(map(int, input().split())) total = sum(a) if total < v: print('NO') exit() dp = [[0]*k for _ in range(n+1)] prev = [[-1]*(k+1) for _ in range(n+1)] dp[0][0] = 1 for i in range(n): for j in range(k): if not dp[i][j]: con...
949_B. A Leapfrog in the Array
Dima is a beginner programmer. During his working process, he regularly has to repeat the following operation again and again: to remove every second element from the array. One day he has been bored with easy solutions of this problem, and he has come up with the following extravagant algorithm. Let's consider that i...
```python import sys input=sys.stdin.readline n,q=list(map(int,input().split())) for i in range(q): a=int(input()) if a%2!=0: print((a+1)//2) else: b=a//2 while 1>0: a=a+(n-b) b=a//2 if a%2!=0: print((a+1)//2) break...
977_A. Wrong Subtraction
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
```python a, b = input().split(' ') a=int(a) for i in range(int(b)): if (a%10 != 0): a -= 1 else: a /= 10 print(int(a)) ```
996_E. Leaving the Bar
For a vector \vec{v} = (x, y), define |v| = √{x^2 + y^2}. Allen had a bit too much to drink at the bar, which is at the origin. There are n vectors \vec{v_1}, \vec{v_2}, ⋅⋅⋅, \vec{v_n}. Allen will make n moves. As Allen's sense of direction is impaired, during the i-th move he will either move in the direction \vec{v_...
```python # -*- coding: utf-8 -*- import bisect import heapq import math import random import sys from collections import Counter, defaultdict from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal from functools import lru_cache, reduce from itertools import combinations, combinations_with_replacement, product, per...
p02651 AtCoder Grand Contest 045 - Xor Battle
There are two persons, numbered 0 and 1, and a variable x whose initial value is 0. The two persons now play a game. The game is played in N rounds. The following should be done in the i-th round (1 \leq i \leq N): * Person S_i does one of the following: * Replace x with x \oplus A_i, where \oplus represents bitwise X...
```python def slv(n,a,s): base=[0] for i in range(n-1,-1,-1): v=a[i] for j in sorted(base,reverse=True): v=min(v,j^v) if v==0: pass else: if s[i]=='0':base.append(v) if s[i]=='1':return 1 if base:return 0 return 1 t=int(input()) n=[] a=[] s=[] for _ in range(t): n.appe...
p02780 AtCoder Beginner Contest 154 - Dice in Line
We have N dice arranged in a line from left to right. The i-th die from the left shows p_i numbers from 1 to p_i with equal probability when thrown. We will choose K adjacent dice, throw each of them independently, and compute the sum of the numbers shown. Find the maximum possible value of the expected value of this ...
```python n, k = map(int, input().split()) p = list(map(int, input().split())) s = sum(p[:k]) m = s for i in range(1, n-k+1): s = s-p[i-1]+p[i+k-1] if s > m: m = s print((m+k)/2) ```
p02915 AtCoder Beginner Contest 140 - Password
Takahashi is going to set a 3-character password. How many possible passwords are there if each of its characters must be a digit between 1 and N (inclusive)? Constraints * 1 \leq N \leq 9 * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the number of possibl...
```python x=int(input()) print(pow(x,3)) ```
p03051 diverta 2019 Programming Contest - XOR Partitioning
The beauty of a sequence a of length n is defined as a_1 \oplus \cdots \oplus a_n, where \oplus denotes the bitwise exclusive or (XOR). You are given a sequence A of length N. Snuke will insert zero or more partitions in A to divide it into some number of non-empty contiguous subsequences. There are 2^{N-1} possible ...
```python N = int(input()) A = [int(i) for i in input().split()] mod = 10**9 + 7 b = [0]*N b[0] = A[0] for n in range(1,N): b[n] = A[n] ^ b[n-1] #print('累積論理和',b) m = max(b) dp = [[0]*(m+1) for j in range(2)] dp[0] = [1]*(m+1) cnt = [0]*(m+1) z = 0 for i in range(N): if b[i] == 0: z +=1 dp[0][b[...
p03192 CADDi 2018 for Beginners - 12/22
You are given an integer N that has exactly four digits in base ten. How many times does `2` occur in the base-ten representation of N? Constraints * 1000 \leq N \leq 9999 Input Input is given from Standard Input in the following format: N Output Print the answer. Examples Input 1222 Output 3 Input 34...
```python a=str(input()) b=0 for i in range(4): if(a[i]=="2"): b+=1 print(b) ```
p03341 AtCoder Regular Contest 098 - Attention
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`. You will appoint one of the N people as the leader, then command the rest of the...
```python N = input() s = input() #累積和 前処理 Eの数を集計 count = s.count('E') ans = count #左端1番目からリーダーをずらしながらチェック。 for ch in s: if ch == 'E': count -= 1 ans = min(count,ans) else: count += 1 print(ans) ```
p03502 AtCoder Beginner Contest 080 - Harshad Number
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10. Given an integer N, determine whether it is a Harshad number. Constraints * 1?N?10^8 * N is an integer. Input Input is given from Standard Input in the following format: N Output...
```python #2019/09/26 N = input() print("Yes" if int(N) % sum(map(int, N)) == 0 else "No") ```
p03662 AtCoder Regular Contest 078 - Fennec VS. Snuke
Fennec and Snuke are playing a board game. On the board, there are N cells numbered 1 through N, and N-1 roads, each connecting two cells. Cell a_i is adjacent to Cell b_i through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the g...
```python from collections import deque def bfs(start): queue = deque([start]) visited = [] while queue: label = queue.pop() #if label not in visited: visited.append(label) for v in d[label]: if tekazu[v] == float("inf"): tekazu[v] = tekazu[lab...
p03816 AtCoder Beginner Contest 053 - Card Eater
Snuke has decided to play a game using cards. He has a deck consisting of N cards. On the i-th card from the top, an integer A_i is written. He will perform the operation described below zero or more times, so that the values written on the remaining cards will be pairwise distinct. Find the maximum possible number of...
```python N = int(input()) A_arr = [int(x) for x in input().split()] A_set = set(A_arr) ans = len(A_set) if ans%2 == 0: ans -= 1 print(ans) ```
p03985 Kyoto University Programming Contest 2016 - Hundred Eyes Monster
Two circles A, B are given on a two-dimensional plane. The coordinate of the center and radius of circle A is (x_A, y_A) and r_A respectively. The coordinate of the center and radius of circle B is (x_B, y_B) and r_B respectively. These two circles have no intersection inside. Here, we consider a set of circles S that ...
```python import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 7) import math # 反転で同心円に帰着する T = int(input()) query = [[int(x) for x in input().split()] for _ in range(T)] def solve_2_eq(a,b,c): return (-b + (b*b-4*a*c)**.5) / (2*a) def F(r,R,d): # 複比 ratio = ((d+r+R)*(d-R-r)) / (4*r*R) ...
p00073 Surface Area of Quadrangular Pyramid
Create a program that outputs the surface area S of a square cone with a height of h, with a square with one side x as the base. However, assume that the line segment connecting the apex and the center of the base is orthogonal to the base. Also, x and h are positive integers less than or equal to 100. Input Given mu...
```python from math import sqrt while True: x, h = int(input()), int(input()) if x==h==0: break sh = sqrt((x/2)**2 + h**2) print((x*x) + sum([sh*x*0.5 for _ in range(4)])) ```
p00205 Rock
I decided to play rock-paper-scissors with a group of five good friends. Rock-paper-scissors has three hands: goo, choki, and par. If the game between goo and choki is a match between goo and choki, goo is "winning" and choki is "losing". , Par and Goo have the rule that Par is "winning" and Goo is "losing". If everyon...
```python d = {1:2, 2:3, 3:1} while True: h = int(input()) if h == 0: break h = [h] + [int(input()) for _ in range(4)] if len(set(h)) == 3 or len(set(h)) == 1: print(*[3]*5, sep='\n') continue for c in h: print([2, 1][d[c] in h]) ```
p00364 Bange Hills Tower
A project is underway to build a new viewing tower in Bange town called “Bange Hills Tower” whose selling point will be the gorgeous view of the entire main keep of Wakamatsu Castle from top to bottom. Therefore, the view line from the top of the tower must reach the bottom of the keep without being hindered by any of ...
```python n, t = map(int, input().split()) min_height = 0 for _ in range(n): x, h = map(int, input().split()) min_height = max(min_height, h / x * t) print(min_height) ```
p00719 Traveling by Stagecoach
Once upon a time, there was a traveler. He plans to travel using stagecoaches (horse wagons). His starting point and destination are fixed, but he cannot determine his route. Your job in this problem is to write a program which determines the route for him. There are several cities in the country, and a road network ...
```python INF = 10 ** 20 def search(rest, now, goal, dp, edges): if now == goal: return 0 if rest == (): if now == goal: return 0 else: return INF if (rest, now) in dp: return dp[(rest, now)] ret = INF for i, t in enumerate(rest): for dist, to in edges[now]: ret = min(...
p00859 Slim Span
Given an undirected weighted graph G, you should find one of spanning trees specified as follows. The graph G is an ordered pair (V, E), where V is a set of vertices {v1, v2, ... , vn} and E is a set of undirected edges {e1, e2, ... , em}. Each edge e ∈ E has its weight w(e). A spanning tree T is a tree (a connected ...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p00990 ID
At University A, there were many mistakes in entering IDs. Therefore, University A decided to issue a new ID to prevent typos. There is a way to check if the new ID is correct to prevent typos. ・ Calculate the sum of all digits. ・ However, the number of even-numbered digits is doubled, with the rightmost digit as th...
```python import itertools n = int(input()) id = input()[::-1] count = 0 a = [] odd, even = 0 , 0 tmp = 0 for i in range(1,n+1): if id[i-1] == "*": if i % 2: odd += 1 else: even += 1 elif i % 2 == 0: x = int(id[i-1]) if x >= 5: tmp += (x * 2 -...
p01421 Reverse Roads
ICP city has an express company whose trucks run from the crossing S to the crossing T. The president of the company is feeling upset because all the roads in the city are one-way, and are severely congested. So, he planned to improve the maximum flow (edge disjoint paths) from the crossing S to the crossing T by rever...
```python # AOJ 2304 Reverse Roads # Python3 2018.7.21 bal4u # ******************************************* # Dinic's Max Flow Algorithm # ******************************************* INF = 0x7fffffff class Donic: def __init__(self, V): self.V = V self.level = [0] * V self.iter = [0] * V ...
p02156 Ghost
Problem Ghosts line up in a straight line from left to right with $ N $ people. At first, the $ i $ th ghost from the left is facing left if $ U_i $ is'L', and facing right if it is'R'. They are so timid that I don't want to see scary ghosts as much as possible. You can instruct each ghost to look back. It's scary t...
```python from collections import deque N,M = map(int,input().split()) U = input() A = list(map(int,input().split())) src = [tuple(map(int,input().split())) for i in range(M)] edges = {} for s,t,b in src: s,t = s-1,t-1 if s>t: s,t = t,s if (s,t) in edges: edges[(s,t)] += b else: edges[...
p02297 Area
For a given polygon g, computes the area of the polygon. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of g. The line segment connecting pn and p1 is also a side of the polygon. Note that the polygon is not necessarily convex. Constraints ...
```python x=range(int(input())) P=[] for _ in reversed(x):P+=[[int(i) for i in input().split()]] P+=[P[0]] for j in x:_+=P[j+1][1]*P[j][0]-P[j][1]*P[j+1][0] print(_*0.5) ```
p02444 Rotate
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and rotate specified elements by a list of the following operation: * rotate($b, m, e$): For each integer $k$ ($0 \leq k < (e - b)$), move element $b + k$ to the place of element $b + ((k + (e - m)) \mod (e - b))$. Constraints * $1...
```python input() a = list(map(int, input().split())) for _ in range(int(input())): b,m,e = map(int, input().split()) x=a[m:e] a[b+e-m:e]=a[b:m] a[b:b+e-m]=x print(" ".join(list(map(str,a)))) ```
1023_A. Single Wildcard Pattern Matching
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m. The wildcard character '*' in the string s (if any) can be replace...
```python #Stanley Tantysco - 2201814670 #Problem B - Wild Card def str_limit(n): if (n >= 1 and n <= 200000): return True else: return False def wild_counter(s): count=0 for i in s: if i == '*': count += 1 if count <= 1: return True else: re...
1044_B. Intersecting Subtrees
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree. You and Li Chen each chose a subtree (i.e., a connected su...
```python import sys from collections import deque t=int(sys.stdin.readline()) for i in range(t): n=int(sys.stdin.readline())#node EDGE=[list(map(int,sys.stdin.readline().split())) for i in range(n-1)] k1=int(sys.stdin.readline()) X=list(map(int,sys.stdin.readline().split())) k2=int(sys.stdin....
1067_A. Array Without Local Maximums
Ivan unexpectedly saw a present from one of his previous birthdays. It is array of n numbers from 1 to 200. Array is old and some numbers are hard to read. Ivan remembers that for all elements at least one of its neighbours ls not less than it, more formally: a_{1} ≤ a_{2}, a_{n} ≤ a_{n-1} and a_{i} ≤ max(a_{i-1}, ...
```python import os from io import BytesIO input = BytesIO(os.read(0, os.fstat(0).st_size)).readline MOD = 998244353 MODF = 1.0*MOD from math import trunc def quickmod(a): return a-MODF*trunc(a/MODF) def main(): n = int(input()) a = [int(i) for i in input().split()] f0, f1 = [1.0] * 201, [0.0] * 201...
1108_E1. Array and Segments (Easy version)
The only difference between easy and hard versions is a number of elements in the array. You are given an array a consisting of n integers. The value of the i-th element of the array is a_i. You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n. You can choose some subset of...
```python n,m=map(int, input().split()) a=list(map(int,input().split())) i=0 l1=[] l2=[] while i<m: e,f=map(int,input().split()) l1.append(e) l2.append(f) i+=1 i=0 j=0 ans=-1 s=[] while i<n: j=0 while j<n: k=0 l=a[j]-a[i] m1=[] while k<m: if l1[k]<=i+1...
1138_A. Sushi for Two
Arkady invited Anna for a dinner to a sushi restaurant. The restaurant is a bit unusual: it offers n pieces of sushi aligned in a row, and a customer has to choose a continuous subsegment of these sushi to buy. The pieces of sushi are of two types: either with tuna or with eel. Let's denote the type of the i-th from t...
```python n = int(input()) a = [int(s) for s in input().split()] i = 0 j = 0 cur1 = 0 cur = 0 res = 0 b = a[0] prev = 0 while j < n and a[j] == b: j+=1 cur1 += 1 cur += 1 while i < n and j < n: if b == 1: b = 2 else: b = 1 prev = cur cur = 0 while j < n and a[j] == b: ...
1156_C. Match Points
You are given a set of points x_1, x_2, ..., x_n on the number line. Two points i and j can be matched with each other if the following conditions hold: * neither i nor j is matched with any other point; * |x_i - x_j| ≥ z. What is the maximum number of pairs of points you can match with each other? Input T...
```python n,z=(int(i) for i in input().split()) k=0 x=sorted([int(i) for i in input().split()]) i,j=0,n//2 while i<n//2 and j<n: if x[j]-x[i]>=z: i+=1 k+=1 j+=1 print(k) ```
1178_F1. Short Colorful Strip
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one. There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centime...
```python class SparseTable(): """区間取得クエリをO(1)で答えるデータ構造をO(NlogN)で構築する query(l, r): 区間[l, r)に対するクエリに答える """ def __init__(self, array, n): n = len(array) self.row_size = n.bit_length() # log_tableを構築する # log_table = [0, 0, 1, 1, 2, 2, 2, 2, ...] self.log_table = [0...
1196_E. Connected Component on a Chessboard
You are given two integers b and w. You have a chessboard of size 10^9 × 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white. Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s...
```python ''' CODED WITH LOVE BY SATYAM KUMAR ''' from sys import stdin, stdout import cProfile, math from collections import Counter,defaultdict,deque from bisect import bisect_left,bisect,bisect_right import itertools from copy import deepcopy from fractions import Fraction import sys, threading import operator as o...
1213_G. Path Queries
You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. You are given m queries. The i-th query is given as an integer q_i. In this query you need to calculate the number of pairs of vertices (u, v) (...
```python n,m=map(int,input().split()) """L=[] for i in range(n): s=[] L.append(s)""" dp=[] for i in range(n-1): u,v,w=map(int,input().split()) #L[u-1].append(v-1) #L[v-1].append(u-1) dp.append((w,u-1,v-1)) dp=sorted(dp) q=[int(x) for x in input().split()] pos=[] for i in range(m): pos.app...
1237_C1. Balanced Removals (Easier)
This is an easier version of the problem. In this version, n ≤ 2000. There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even. You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remove...
```python def d(le): for i in range(0,len(le),2): # if le[i][3]==29 and le[i+1][3]==38: # print(me) # return '' print(le[i][3],le[i+1][3]) def dd(it): global do # print(it) tt={} ddd=[] it.sort(key=lambda x:x[1]) l=list(set([i[1] for i in it])) l....
1255_B. Fridge Lockers
Hanh lives in a shared apartment. There are n people (including Hanh) living there, each has a private fridge. n fridges are secured by several steel chains. Each steel chain connects two different fridges and is protected by a digital lock. The owner of a fridge knows passcodes of all chains connected to it. A fridg...
```python t = int(input()) for i in range(t): n, m = map(int, input().split()) dop = list(map(int, input().split())) suma = sum(dop) mas = [] for i in range(n): mas.append([dop[i], i]) if m < n or n == 2: print (-1) continue mas.sort() print(suma * 2 + (mas[0][0] + mas[1][0]) * (m - n)) for i in range(1,...
1279_A. New Year Garland
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands. The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them ...
```python n = int(input()) for i in range(n): l = [int(k) for k in input().split()] l.sort() if l[2] <= l[1]+l[0]+1 : print("YES") else : print("NO") ```
1322_B. Present
Catherine received an array of integers as a gift for March 8. Eventually she grew bored with it, and she started calculated various useless characteristics for it. She succeeded to do it for each one she came up with. But when she came up with another one — xor of all pairwise sums of elements in the array, she realiz...
```python import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().split())) L = max(A).bit_length()+1 ans = 0 for l in range(L+1): A1 = [] A2 = [] for a in A: if a&(1<<l): A1.append(a) else: A2.append(a) A = A2 + A1 D = 1<<(l+1) ...
1341_A. Nastya and Rice
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
```python def main(): T = int(input()) for t in range(T): n,a,b,c,d = list(map(int,input().split())) pos = True if((a-b)*n>(c+d)): pos = False elif((a-b)*n < (c-d)) and ((c-d)-(a-b)*n) > 2*b*n: pos = False print("YES") if pos else print("NO") ...
1363_A. Odd Selection
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct. Tell him whether he can do so. Input The first line of the input contains a single integer t (1≤ t ≤...
```python from sys import stdin,stdout lis=lambda:list(map(int,input().split())) Ma=lambda:map(int,input().split()) inte=lambda:int(input()) st=lambda:input() import math from collections import Counter for i in range(inte()): n,x=Ma() a=lis() o=0;e=0 for i in a: if i%2==0: e+=1 ...
1404_C. Fixed Point Removal
Let a_1, …, a_n be an array of n positive integers. In one operation, you can choose an index i such that a_i = i, and remove a_i from the array (after the removal, the remaining parts are concatenated). The weight of a is defined as the maximum number of elements you can remove. You must answer q independent queries...
```python '''explained excellently in editorial''' mod = 1000000007 eps = 10**-9 def main(): import sys input = sys.stdin.readline class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0...
1447_F1. Frequency Problem (Easy Version)
This is the easy version of the problem. The difference between the versions is in the constraints on the array elements. You can make hacks only if all versions of the problem are solved. You are given an array [a_1, a_2, ..., a_n]. Your goal is to find the length of the longest subarray of this array such that the...
```python n=int(input()) arr=list(map(int,input().split())) freq=[0]*(101) for i in arr:freq[i]+=1 maxx=max(freq) amtOFmaxx=freq.count(maxx) if amtOFmaxx>=2:print(n) else: must_apper=freq.index(maxx) ans=0 for j in range(1,101): if j==must_apper: continue first_index=[10**6]*(n+1) first_index[0]...
1472_F. New Year's Puzzle
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle. Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need...
```python import sys def solve(): sys.stdin.readline() n, m = map(int,sys.stdin.readline().split()) dudes = [] for i in range(m): r, c = map(int,sys.stdin.readline().split()) dudes.append((c,r)) dudes.sort() dudes.reverse() cells = [] while dudes: if not cells or cells[-1][0]!=dudes[-1][0]: cells.appe...
1499_A. Domino on Windowsill
You have a board represented as a grid with 2 × n cells. The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black. You have w white dominoes (2 × 1 tiles, both cells are colored in white) and b black dominoes (2 × 1 tiles, both cells are col...
```python for _ in range(int(input())): n,k1,k2=[int(x) for x in input().split()] w,b=[int(x) for x in input().split()] if k1>k2: if w<=k2+((k1-k2)//2) and b<=n-k1+((k1-k2)//2): print("YES") else: print("NO") else: if w<=k1+((k2-k1)//2) and b<=n-k2+((k2-k1)//2): print("YES") el...
1520_F2. Guess the K-th Zero (Hard version)
This is an interactive problem. This is a hard version of the problem. The difference from the easy version is that in the hard version 1 ≤ t ≤ min(n, 10^4) and the total number of queries is limited to 6 ⋅ 10^4. Polycarp is playing a computer game. In this game, an array consisting of zeros and ones is hidden. Polyc...
```python n, t = map(int, input().split()) mem = {} for _ in range(t): k = int(input()) left, right = 1, n while right > left: mid = (left + right) // 2 if (left, mid) not in mem: print(f'? {left} {mid}') mem[(left, mid)] = mid - left + 1 - int(input()) nu...
154_D. Flatland Fencing
The King of Flatland will organize a knights' tournament! The winner will get half the kingdom and the favor of the princess of legendary beauty and wisdom. The final test of the applicants' courage and strength will be a fencing tournament. The tournament is held by the following rules: the participants fight one on o...
```python x1, x2, a, b = map(int, input().split()) if a <= 0 <= b: if x1 < x2: if x2 - x1 <= b: print("FIRST") print(x2) else: print("DRAW") else: if x1 - x2 <= -a: print("FIRST") print(x2) else: print("DRAW"...
176_B. Word Cut
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation...
```python # ------------------- 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...
21_D. Traveling Graph
You are given undirected weighted graph. Find the length of the shortest cycle which starts from the vertex 1 and passes throught all the edges at least once. Graph may contain multiply edges between a pair of vertices and loops (edges from the vertex to itself). Input The first line of the input contains two integer...
```python import math N = 15 mat = 0 inf = 1000000000 answer = inf def Get_Cycle_Length(v,graph): global mat global answer if len(v) == 0: answer = min(answer,mat) return end = v.pop() i = 0 while i<len(v): se = v.pop(i) mat += graph[se][end] Ge...
244_A. Dividing Orange
One day Ms Swan bought an orange in a shop. The orange consisted of n·k segments, numbered with integers from 1 to n·k. There were k children waiting for Ms Swan at home. The children have recently learned about the orange and they decided to divide it between them. For that each child took a piece of paper and wrote...
```python ar = [] for i in input().split(): ar.append(int(i)) ar2 = [] for i in input().split(): ar2.append(int(i)) temp = list(set(range(1, ar[0]*ar[1]+1))-set(ar2)) for i in range(len(ar2)): res = [] res.append(ar2[i]) while (len(res) != ar[0]): res.append(temp[0]) temp.pop(0) ...
292_A. SMSC
Some large corporation where Polycarpus works has its own short message service center (SMSC). The center's task is to send all sorts of crucial information. Polycarpus decided to check the efficiency of the SMSC. For that, he asked to give him the statistics of the performance of the SMSC for some period of time. In...
```python import re import itertools from collections import Counter, deque class Task: tasks = [] answer = "" def getData(self): numberOfTasks = int(input()) for i in range(0, numberOfTasks): self.tasks += [[int(x) for x in input().split(' ')]] #inFile = open('input....
363_A. Soroban
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about ...
```python def answer(n): if n==0: print('O-|-OOOO') while n!=0: i=n%10 if i<5: x=4-i print("O-|",end="") while i>0: print("O", end="") i=i-1 print("-", end="") while x>0: ...
386_D. Game with Points
You are playing the following game. There are n points on a plane. They are the vertices of a regular n-polygon. Points are labeled with integer numbers from 1 to n. Each pair of distinct points is connected by a diagonal, which is colored in one of 26 colors. Points are denoted by lowercase English letters. There are ...
```python from collections import deque __author__ = 'asmn' n = int(input()) end = tuple(sorted(map(lambda x: int(x) - 1, input().split()))) st = (0, 1, 2) mat = [input() for i in range(n)] v = set([st]) path = {} dist = {st: 0} queue = deque([st]) while end not in v and len(queue) > 0: p = queue.popleft() ...
457_A. Golden System
Piegirl got bored with binary, decimal and other integer based counting systems. Recently she discovered some interesting properties about number <image>, in particular that q2 = q + 1, and she thinks it would make a good base for her new unique system. She called it "golden system". In golden system the number is a no...
```python from sys import stdin s=list(stdin.readline().strip()[::-1]) s1=list(stdin.readline().strip()[::-1]) def trans(s): s.append("0") i=len(s)-1 while i>1: while i>=len(s): s.append("0") if s[i-1]=="1" and s[i-2]=="1": s[i]="1" s[i-1]="0" ...
479_D. Long Jumps
Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long jumps, and Valery has lost his favorite ruler! However, there is no reason for disappointment, as Valery has found another ruler, its length is l centimeters. The ruler already has n marks, with which he can make measure...
```python n,l,x,y = map(int, input().split()) a = list(map(int, input().split())) i = 0 j = 1 tot = 0 can_measure_a = False while j < n: if a[j] - a[i] == x: can_measure_a = True break elif a[j] - a[i] > x: i += 1 else: j += 1 i = 0 j = 1 can_measure_b = False w...
501_D. Misha and Permutations Summation
Let's define the sum of two permutations p and q of numbers 0, 1, ..., (n - 1) as permutation <image>, where Perm(x) is the x-th lexicographically permutation of numbers 0, 1, ..., (n - 1) (counting from zero), and Ord(p) is the number of permutation p in the lexicographical order. For example, Perm(0) = (0, 1, ..., n...
```python import sys class SegmTree(): def __init__(self, array=None): size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) for i in range(size): self.tree[i+self.N] = array[i] self.build() def b...
527_B. Error Correct System
Ford Prefect got a job as a web developer for a small company that makes towels. His current work task is to create a search engine for the website of the company. During the development process, he needs to write a subroutine for comparing strings S and T of equal length to be "similar". After a brief search on the In...
```python num=int(input()) a=input() b=input() dic={} lis=[] ham=0 swap1=-1 swap2=-1 p=False q=False for i in range(num): if a[i]!=b[i]: ham+=1 lis.append(i) dic[b[i]]=i for i in lis: if a[i] in dic: p=True swap1=i+1 f=dic[a[i]] swap2=f+1 if a[f]==...
552_E. Vanya and Brackets
Vanya is doing his maths homework. He has an expression of form <image>, where x1, x2, ..., xn are digits from 1 to 9, and sign <image> represents either a plus '+' or the multiplication sign '*'. Vanya needs to add one pair of brackets in this expression so that to maximize the value of the resulting expression. Inpu...
```python def find_best(s): best = eval(s) for i in range(0, len(s), 2): if i > 0 and s[i - 1] == '*' or i == 0: for j in range(i + 2, len(s), 2): if j < len(s) - 1 and s[j + 1] == '*' or j == len(s) - 1: sp = s[:i] + '(' + s[i:j + 1] + ')' + s[j + 1:] ...
579_E. Weakness and Poorness
You are given a sequence of n integers a1, a2, ..., an. Determine a real number x such that the weakness of the sequence a1 - x, a2 - x, ..., an - x is as small as possible. The weakness of a sequence is defined as the maximum value of the poorness over all segments (contiguous subsequences) of a sequence. The poor...
```python def main(): input() a = list(map(int, input().split())) def f(a): maxend = maxnow = 0 for x in a: maxend = max(0, maxend + x) maxnow = max(maxnow, maxend) return maxnow f1 = lambda x: f(i - x for i in a) f2 = lambda x: f(x - i for i in a) Max = max(abs(i) for i in a)...
600_D. Area of Two Circles' Intersection
You are given two circles. Find the area of their intersection. Input The first line contains three integers x1, y1, r1 ( - 109 ≤ x1, y1 ≤ 109, 1 ≤ r1 ≤ 109) — the position of the center and the radius of the first circle. The second line contains three integers x2, y2, r2 ( - 109 ≤ x2, y2 ≤ 109, 1 ≤ r2 ≤ 109) — the...
```python import math from decimal import Decimal from decimal import getcontext from math import acos pi = Decimal('3.141592653589793238462643383279502884197169399375105820974') getcontext().prec=5000 eps = 2e-7 def _acos(x): if 1 - eps > abs(x) > eps: return Decimal(acos(x)) if x < 0: re...
623_A. Graph and String
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties: * G has exactly n vertices, numbered from 1 to...
```python def dfs(v, used, g): used[v] = True for x in g[v]: if not used[x]: dfs(x, used, g) from collections import defaultdict, Counter n, m = map(int, input().split()) g = defaultdict(set) p = Counter() for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 g[a...
644_C. Hostname Aliases
There are some websites that are accessible through several different addresses. For example, for a long time Codeforces was accessible with two hostnames codeforces.com and codeforces.ru. You are given a list of page addresses being queried. For simplicity we consider all addresses to have the form http://<hostname>[...
```python from sys import stdin from collections import defaultdict def main(): s, d = input(), defaultdict(set) for s in stdin.read().splitlines(): i = s.find('/', 8) if i == -1: d[s].add('') else: d[s[:i]].add(s[i:]) e = defaultdict(list) for s, v in d...
717_G. Underfail
You have recently fallen through a hole and, after several hours of unconsciousness, have realized you are in an underground city. On one of your regular, daily walks through the unknown, you have encountered two unusually looking skeletons called Sanz and P’pairus, who decided to accompany you and give you some puzzle...
```python import sys from heapq import heappop, heappush class Edge: def __init__(self, u, v, cap, flow, cost, rev): self.u = u self.v = v self.cap = cap self.flow = flow self.cost = cost self.rev = rev def add_edge(adj, u, v, capv, flowv, costv): adj[u].append(...
762_B. USB vs. PS/2
Due to the increase in the number of students of Berland State University it was decided to equip a new computer room. You were given the task of buying mouses, and you have to spend as little as possible. After all, the country is in crisis! The computers bought for the room were different. Some of them had only USB ...
```python from sys import stdin as fin a,b,c = [int(i) for i in input().split()] n = int(input()) usb = [] ps2 = [] for i in range(n): a1,a2 =fin.readline().strip().split() if a2=='USB': usb.append(int(a1)) else: ps2.append(int(a1)) usb = sorted(usb) ps2 = sorted(ps2) n1 = len(usb) n2...
785_C. Anton and Fairy Tale
Anton likes to listen to fairy tales, especially when Danik, Anton's best friend, tells them. Right now Danik tells Anton a fairy tale: "Once upon a time, there lived an emperor. He was very rich and had much grain. One day he ordered to build a huge barn to put there all his grain. Best builders were building that ba...
```python def binary_search_first_true(predicate, from_inclusive, to_inclusive): lo = from_inclusive - 1 hi = to_inclusive + 1 while hi - lo > 1: mid = (lo + hi) // 2 if not predicate(mid): lo = mid else: hi = mid return hi def tri(n): return n*(n+1)//2 ...
807_C. Success Rate
You are an experienced Codeforces user. Today you found out that during your activity on Codeforces you have made y submissions, out of which x have been successful. Thus, your current success rate on Codeforces is equal to x / y. Your favorite rational number in the [0;1] range is p / q. Now you wonder: what is the s...
```python for _ in range(int(input())): x,y,p,q=map(int,input().split()) l,r,res=0,10**18,-1 while l<=r: mid=(l+r)//2 a,b=p*mid-x,q*mid-y if a<=b and a>-1 and b>-1:res=b;r=mid-1 else :l=mid+1 print(res) ```
831_D. Office Keys
There are n people and k keys on a straight line. Every person wants to get to the office which is located on the line as well. To do that, he needs to reach some point with a key, take the key and then go to the office. Once a key is taken by somebody, it couldn't be taken by anybody else. You are to determine the mi...
```python def list_input(): return list(map(int,input().split())) def map_input(): return map(int,input().split()) def map_string(): return input().split() n,k,p = map_input() a = list_input() b = list_input() a.sort() b.sort() ans = 1000000000000000000 for i in range(k-n+1): cur = 0 c1 = 0 ...
852_E. Casinos and travel
John has just bought a new car and is planning a journey around the country. Country has N cities, some of which are connected by bidirectional roads. There are N - 1 roads and every city is reachable from any other city. Cities are labeled from 1 to N. John first has to select from which city he will start his journe...
```python n=int(input()) a=[0]*n for i in range(n-1): for j in input().split(): a[int(j)-1]+=1 l=a.count(1) print((l*2**(n-l+1)+(n-l)*2**(n-l))%1000000007) ```
876_F. High Cry
Disclaimer: there are lots of untranslateable puns in the Russian version of the statement, so there is one more reason for you to learn Russian :) Rick and Morty like to go to the ridge High Cry for crying loudly — there is an extraordinary echo. Recently they discovered an interesting acoustic characteristic of this...
```python import os,io,sys input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n=int(input()) a=list(map(int,input().split())) left=[] right=[] for i in range(31): left.append([-1]*n) right.append([n]*n) for i in range(n): for j in range(31): if 1<<j&a[i]: left[j][i]=i else: if i>0: ...
900_A. Find Extra One
You have n distinct points on a plane, none of them lie on OY axis. Check that there is a point after removal of which the remaining points are located on one side of the OY axis. Input The first line contains a single positive integer n (2 ≤ n ≤ 105). The following n lines contain coordinates of the points. The i-t...
```python foo = int(input()) gr = 0 lo = 0 for i in range(foo): bar = int((input().split(' '))[0]) if bar < 0: lo += 1 else: gr += 1 if lo > 1 and gr > 1: print('No') break else: print('Yes') ```
950_A. Left-handers, Right-handers and Ambidexters
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl...
```python l, r, a = map(int, input().split()) while a != 0: if l < r: l += 1 else: r += 1 a -= 1 print(min(l, r)*2) ```
978_D. Almost Arithmetic Progression
Polycarp likes arithmetic progressions. A sequence [a_1, a_2, ..., a_n] is called an arithmetic progression if for each i (1 ≤ i < n) the value a_{i+1} - a_i is the same. For example, the sequences [42], [5, 5, 5], [2, 11, 20, 29] and [3, 2, 1, 0] are arithmetic progressions, but [1, 0, 1], [1, 3, 9] and [2, 3, 1] are ...
```python import math import sys import collections import bisect import time import random from itertools import permutations def get_ints():return map(int, sys.stdin.readline().strip().split()) def get_list():return list(map(int, sys.stdin.readline().strip().split())) def get_string():return sys.stdin.readline().stri...
998_C. Convert to Ones
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
```python n,x,y=map(int,input().split()) s=input() c=0 for i in range(1,n): if s[i]=='1' and s[i-1]=='0': c+=1 if s[-1]=='0': c+=1 if c==0: print(0) elif x>=y: print(c*y) else: print((c-1)*x+y) ```
p02660 AtCoder Beginner Contest 169 - Div Game
Given is a positive integer N. Consider repeatedly applying the operation below on N: * First, choose a positive integer z satisfying all of the conditions below: * z can be represented as z=p^e, where p is a prime number and e is a positive integer; * z divides N; * z is different from all integers chosen in previous...
```python def f(n): p=[] if n%2==0: c=0 while n%2==0: c+=1 n/=2 p.append(c) for i in range(3,int(n**0.5)+1,2): if n%i==0: c=0 while n%i==0: c+=1 n/=i p.append(c) if n!=1: p.append(1) return p N=int(input()) p=f(N) r=0 while p: r+=int(((8*p...
p02789 AtCoder Beginner Contest 152 - AC or WA
Takahashi is participating in a programming contest, AXC001. He has just submitted his code to Problem A. The problem has N test cases, all of which must be passed to get an AC verdict. Takahashi's submission has passed M cases out of the N test cases. Determine whether Takahashi's submission gets an AC. Constraints ...
```python N,M=map(int,input().split());print(["No","Yes"][N==M]) ```