name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p02296 Distance
For given two segments s1 and s2, print the distance between them. s1 is formed by end points p0 and p1, and s2 is formed by end points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st query 2nd query ... qth...
```python def dot(a, b): return a.real * b.real + a.imag * b.imag def cross(a, b): return a.real * b.imag - a.imag * b.real def ccw(p0, p1, p2): a = p1-p0 b = p2-p0 if cross(a,b) > 0: return 1 #couner_clockwise elif cross(a,b) <0: return -1 #clockwise elif dot(a,b) < 0: return 2 #online_back...
p02443 Reverse
Write a program which reads a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ and reverse specified elements by a list of the following operation: * reverse($b, e$): reverse the order of $a_b, a_{b+1}, ..., a_{e-1}$ Constraints * $1 \leq n \leq 1,000$ * $-1,000,000,000 \leq a_i \leq 1,000,000,000$ * $1 \leq ...
```python n = int(input()) a = list(map(int, input().split(' '))) q = int(input()) for i in range(q): b, e = list(map(int, input().split(' '))) a[b:e] = a[b:e][::-1] print(' '.join(list(map(str, a)))) ```
1020_A. New Building for SIS
You are looking at the floor plan of the Summer Informatics School's new building. You were tasked with SIS logistics, so you really care about travel time between different locations: it is important to know how long it would take to get from the lecture room to the canteen, or from the gym to the server room. The bu...
```python t,f,lw,hw,q = map(int,input().split()) while(q): t1,f1,t2,f2=map(int,input().split()) if(t1==t2): print(abs(f1-f2)) else: ans=abs(t1-t2) if((f1>=lw and f1<=hw) or (f2>=lw and f2<=hw)): ans+=abs(f1-f2) print(ans) elif(f1<lw and f2 <lw) : ans+=(abs(lw-f1)+abs(lw-f2)) ...
1043_D. Mysterious Crime
Acingel is a small town. There was only one doctor here — Miss Ada. She was very friendly and nobody has ever said something bad about her, so who could've expected that Ada will be found dead in her house? Mr Gawry, world-famous detective, is appointed to find the criminal. He asked m neighbours of Ada about clients w...
```python n, m = map(int, input().split()) a = [] for i in range(m): a.append(list(map(int, input().split()))) b = [set([]) for i in range(n)] for i in range(n): for j in range(m): ya = a[j][i] if i == n-1: b[ya-1].add(100000000) else: b[ya-1].add(a[j][i+1]) class UnionFind(): def __init...
1066_B. Heaters
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0. Each heater has a va...
```python n,r=[int(x) for x in input().split()] a=[int(x) for x in input().split()] i=ans=0 while i<n: pointer=i f=0 while pointer<n: if pointer-r+1>i: break if a[pointer]==1: j=pointer f=1 pointer+=1 if f==0: pointer=i-1 whil...
1107_G. Vasya and Maximum Profit
Vasya got really tired of these credits (from problem F) and now wants to earn the money himself! He decided to make a contest to gain a profit. Vasya has n problems to choose from. They are numbered from 1 to n. The difficulty of the i-th problem is d_i. Moreover, the problems are given in the increasing order by the...
```python import sys it = iter(sys.stdin.readlines()) input = it.__next__ n, k = map(int, input().split()) d, c = [0] * n, [0] * n for i in range(n): a, b = map(int, input().split()) d[i], c[i] = a, k - b p, r, pre, suf, sm, mx = list(range(n)), [0] * n, c[:], c[:], c[:], c[:] def find(x): if x != p[x]: ...
1137_B. Camp Schedule
The new camp by widely-known over the country Spring Programming Camp is going to start soon. Hence, all the team of friendly curators and teachers started composing the camp's schedule. After some continuous discussion, they came up with a schedule s, which can be represented as a binary string, in which the i-th symb...
```python def findNeedSubstring(s): n = len(s) rst = '' tmp = 0 for i in range(1, n-1, 1): if(s[0:i] == s[n-i:n]): rst = s[0:i] # this is the longest substring that prefix = suffix tmp = i return s[tmp: n] def polyHash(s): rst = [0] * (len(s) + 1) ...
1155_D. Beautiful Array
You are given an array a consisting of n integers. Beauty of array is the maximum sum of some consecutive subarray of this array (this subarray may be empty). For example, the beauty of the array [10, -5, 10, -4, 1] is 15, and the beauty of the array [-3, -5, -1] is 0. You may choose at most one consecutive subarray o...
```python import sys #Library Info(ACL for Python/Pypy) -> https://github.com/not522/ac-library-python def input(): return sys.stdin.readline().rstrip() DXY = [(0, -1), (1,0), (0, 1), (-1,0)] #L,D,R,Uの順番 INF = 1 << 64 def main(): n,x = map(int,input().split()) a = list(map(int,input().split())) A =...
1178_A. Prime Minister
Alice is the leader of the State Refactoring Party, and she is about to become the prime minister. The elections have just taken place. There are n parties, numbered from 1 to n. The i-th party has received a_i seats in the parliament. Alice's party has number 1. In order to become the prime minister, she needs to b...
```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) ...
1196_A. Three Piles of Candies
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
```python for z in range (int(input())): a=list(map(int,input().split())) print(sum(a)//2) ```
1213_C. Book Reading
Polycarp is reading a book consisting of n pages numbered from 1 to n. Every time he finishes the page with the number divisible by m, he writes down the last digit of this page number. For example, if n=15 and m=5, pages divisible by m are 5, 10, 15. Their last digits are 5, 0, 5 correspondingly, their sum is 10. You...
```python q = int(input()) for i in range(q): n, m = input().split(" ") n = int(n) m = int(m) if n == m: print(m%10) continue inicial = m aux = (m%10) m += inicial while (m%10) != (inicial%10) and m <= n: aux += (m%10) m += inicial m = m-ini...
1236_D. Alice and the Doll
Alice got a new doll these days. It can even walk! Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column. However, the d...
```python from sys import stdout printn = lambda x: stdout.write(x) inn = lambda : int(input()) inl = lambda: list(map(int, input().split())) inm = lambda: map(int, input().split()) DBG = True and False BIG = 999999999 R = 10**9 + 7 def ddprint(x): if DBG: print(x) n,m,k = inm() hx = {} hy = {} cnt ...
1254_B2. Send Boxes to Alice (Hard Version)
This is the harder version of the problem. In this version, 1 ≤ n ≤ 10^6 and 0 ≤ a_i ≤ 10^6. You can hack this problem if you locked it. But you can hack the previous problem only if you locked both problems Christmas is coming, and our protagonist, Bob, is preparing a spectacular present for his long-time best friend...
```python # 素因数分解 def prime_decomposition(n): i = 2 table = [] while i * i <= n: while n % i == 0: n //= i table.append(i) i += 1 if n > 1: table.append(n) return table import sys input = sys.stdin.readline N = int(input()) A = list(map(int, input().sp...
1278_B. A and B
You are given two integers a and b. You can perform a sequence of operations: during the first operation you choose one of these numbers and increase it by 1; during the second operation you choose one of these numbers and increase it by 2, and so on. You choose the number of these operations yourself. For example, if...
```python cum_sum = [0]*47000 cum_sum[1]=1 for i in range(2,47000): cum_sum[i] = cum_sum[i-1]+i n = int(input()) for i in range(n): a,b = map(int,input().split()) delta = max(a,b) - min(a,b) cnt = cum_sum.index([el for el in cum_sum if el <= delta][-1]) eq = a+b+cum_sum[cnt] while (eq%2!=0 ...
1321_C. Remove Adjacent
You are given a string s consisting of lowercase Latin letters. Let the length of s be |s|. You may perform several operations on this string. In one operation, you can choose some index i and remove the i-th character of s (s_i) if at least one of its adjacent characters is the previous letter in the Latin alphabet f...
```python t=int(input()) s=input() ans='' count=0 while(True): flag=True j=-1 ch=0 for i in range(len(s)): if (i!=0 and ord(s[i-1])-ord(s[i])==-1) or (i!=len(s)-1 and ord(s[i+1])-ord(s[i])==-1): if j==-1 or ord(ch)<ord(s[i]): ch=s[i] j=i ...
1340_B. Nastya and Scoreboard
Denis, after buying flowers and sweets (you will learn about this story in the next task), went to a date with Nastya to ask her to become a couple. Now, they are sitting in the cafe and finally... Denis asks her to be together, but ... Nastya doesn't give any answer. The poor boy was very upset because of that. He w...
```python import sys def f(): n, k = map(int, input().split())#2000, 2000 ch = {0:'1110111',1:'0010010',2:'1011101',3:'1011011',4:'0111010',5:'1101011',6:'1101111',7:'1010010',8:'1111111',9:'1111011'} l = [] for _ in range(n): l.append(sys.stdin.readline().rstrip()) def tr(s1, s2): ...
1362_B. Johnny and His Hobbies
Among Johnny's numerous hobbies, there are two seemingly harmless ones: applying bitwise operations and sneaking into his dad's office. As it is usually the case with small children, Johnny is unaware that combining these two activities can get him in a lot of trouble. There is a set S containing very important number...
```python t=int(input()) for T in range(t): n=int(input()) lista=[int(x) for x in input().split()] ma=max(lista) mi=min(lista) listb=[0]*n ans=0 for k in range(1,2*ma+1): temp=0 for i in range(n): listb[i]=lista[i]^k tk=0 if(listb[i] not in lista): temp=1 break if(temp==0): ans=1 pri...
1382_C2. Prefix Flip (Hard Version)
This is the hard version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved. There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ...
```python t=int(input()) for _ in range(t): n=int(input()) arr=list(input().rstrip("\n")) arr1=list(input().rstrip("\n")) arr=[int(x) for x in arr] arr1=[int(x) for x in arr1] #print(arr,n) result=[] if arr == arr1: print(0) else: if n == 1: print("1 1") ...
1447_A. Add Candies
There are n bags with candies, initially the i-th bag contains i candies. You want all the bags to contain an equal amount of candies in the end. To achieve this, you will: * Choose m such that 1 ≤ m ≤ 1000 * Perform m operations. In the j-th operation, you will pick one bag and add j candies to all bags apart ...
```python a=int(input()) for i in range(a): b=int(input()) arr=[str(i) for i in range(b,1,-1)] arr=arr[::-1] print(len(arr)) print(' '.join(arr)) ```
1471_B. Strange List
You have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer q/x to the end of the array, and moves on to the next element. Note ...
```python t=int(input()) for _ in range(t): n,x=[int(z) for z in input().split()] a=[int(x) for x in input().split()] minCycles=float('inf') minCycIdx=-1 for i,z in enumerate(a): nCycles=0 while z%x==0: nCycles+=1 z//=x if nCycles<minCycles: ...
1498_B. Box Fitting
You are given n rectangles, each of height 1. Each rectangle's width is a power of 2 (i. e. it can be represented as 2^x for some non-negative integer x). You are also given a two-dimensional box of width W. Note that W may or may not be a power of 2. Moreover, W is at least as large as the width of the largest recta...
```python from sys import stdin from math import log2 input = lambda: stdin.readline().strip() t = int(input()) for _ in range(t): n, W = map(int, input().split()) ls = list(map(int, input().split())) d = [] for i in range(20): d.append(0) for i in ls: d[int(log2(i))]+=1 result ...
1520_A. Do Not Be Distracted!
Polycarp has 26 tasks. Each task is designated by a capital letter of the Latin alphabet. The teacher asked Polycarp to solve tasks in the following way: if Polycarp began to solve some task, then he must solve it to the end, without being distracted by another task. After switching to another task, Polycarp cannot re...
```python def solve(task): unique = set(task) segments = 0 prev = ' ' for letter in task: if letter != prev: segments+=1 prev = letter return "YES" if len(unique) == segments else "NO" if __name__ == '__main__': T = int(input().strip()) for _ in range(T): ...
1547_F. Array Stabilization (GCD version)
You are given an array of positive integers a = [a_0, a_1, ..., a_{n - 1}] (n ≥ 2). In one step, the array a is replaced with another array of length n, in which each element is the [greatest common divisor (GCD)](http://tiny.cc/tuy9uz) of two neighboring elements (the element itself and its right neighbor; consider t...
```python #!/usr/bin/env python #from __future__ import division, print_function import math import os import sys #from fractions import * from sys import * from decimal import * from io import BytesIO, IOBase from itertools import accumulate,combinations,permutations,combinations_with_replacement,product from collecti...
175_C. Geometry Horse
Vasya plays the Geometry Horse. The game goal is to destroy geometric figures of the game world. A certain number of points is given for destroying each figure depending on the figure type and the current factor value. There are n types of geometric figures. The number of figures of type ki and figure cost ci is kno...
```python n = int(input()) figures = [] for _ in range(n): amount, cost = map(int, input().split()) figures += [(cost, amount)] figures.sort() t = int(input()) T = list(map(int, input().split())) result = 0 destructed = 0 i, j = 0, 0 while i < len(figures): if j < len(T) and destructed + figures[i][...
195_D. Analyzing Polyline
As Valeric and Valerko were watching one of the last Euro Championship games in a sports bar, they broke a mug. Of course, the guys paid for it but the barman said that he will let them watch football in his bar only if they help his son complete a programming task. The task goes like that. Let's consider a set of fun...
```python from sys import stdin from math import gcd n = int(stdin.readline()) iset = set() for _ in range(n): k,b = map(int,stdin.readline().split()) if k!=0: if b==0: iset.add((0,1)) else: x = gcd(k,b) if k*b>0: iset.add((abs(b//x),abs(k//x...
219_D. Choosing Capital for Treeland
The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one. The council of the elders has recently decided to ...
```python #More es mi pastor nada me faltara import sys from collections import defaultdict from typing import NamedTuple class EdgeNode(NamedTuple): vertex: int weight: int class Graph: def __init__(self, n): self.graph = d = {i: [] for i in range(n + 1)} self.distance = [0] * (n ...
243_A. The Brand New Function
Polycarpus has a sequence, consisting of n non-negative integers: a1, a2, ..., an. Let's define function f(l, r) (l, r are integer, 1 ≤ l ≤ r ≤ n) for sequence a as an operation of bitwise OR of all the sequence elements with indexes from l to r. Formally: f(l, r) = al | al + 1 | ... | ar. Polycarpus took a piece of...
```python n, a, b = input(), set(), set() for i in map(int, input().split()): b = set(i | j for j in b) b.add(i) a.update(b) print(len(a)) ```
291_A. Spyke Talks
Polycarpus is the director of a large corporation. There are n secretaries working for the corporation, each of them corresponds via the famous Spyke VoIP system during the day. We know that when two people call each other via Spyke, the Spyke network assigns a unique ID to this call, a positive integer session number....
```python n=int(input()) l=list(map(int,input().split())) ans=0 repeat={} for i in l: if i in repeat: repeat[i]+=1 if i==0: pass elif repeat[i]>2: ans=-1 break else: ans+=1 else: repeat[i]=1 print(ans) ```
316_D1. PE Lesson
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning....
```python m = 1000000007 n = int(input()) a = map(int, input().split()) t1, t2 = 0, 0 for i in a: if i == 1: t1 += 1 else: t2 += 1 a = [1, 2] for i in range(3, t1+1): a = a[::-1] a[1] = (a[0]+(i-1)*a[1])%m if not t1 or t1 == 1: a[1] = 1 for i in range(t1+1, n+1): a[1] = a[1]*i%m print(a[1]) ```
339_D. Xenia and Bit Operations
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a. Namely, it takes several iterations to calculate value v. At the first iteration, Xeni...
```python from operator import or_, xor import sys greg=1 #Stolen from tchr to test Xenia and Bit Operations speed. n, m = map(int, input().split()) t = [list(map(int, input().split()))] for i in range(n): t += [[(or_, xor)[i & 1](*t[i][j: j + 2]) for j in range(0, len(t[i]), 2)]] for s in sys.stdin: p, b =...
362_A. Two Semiknights Meet
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the le...
```python t = int(input()) for _ in range(t): s = [input() for i in range(8)] oh = True flag = True for i in range(8): for j in range(8): if(s[i][j] == 'K'): if(flag): pos1x = i pos1y = j flag = False ...
406_C. Graph Cutting
Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partiti...
```python import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) ...
456_A. Laptops
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
```python n = int(input()) for _ in range(n): a,b = map(int,input().split()) if a!=b: print ('Happy Alex') exit() print ('Poor Alex') ```
478_D. Red-Green Towers
There are r red and g green blocks for construction of the red-green tower. Red-green tower can be built following next rules: * Red-green tower is consisting of some number of levels; * Let the red-green tower consist of n levels, then the first level of this tower should consist of n blocks, second level — of n...
```python """ #If FastIO not needed, used this and don't forget to strip #import sys, math #input = sys.stdin.readline """ import os import sys from io import BytesIO, IOBase import heapq as h import bisect from types import GeneratorType BUFSIZE = 8192 class SortedList: def __init__(self, iterable=[], _load=...
5_D. Follow Traffic Rules
Everybody knows that the capital of Berland is connected to Bercouver (the Olympic capital) by a direct road. To improve the road's traffic capacity, there was placed just one traffic sign, limiting the maximum speed. Traffic signs in Berland are a bit peculiar, because they limit the speed only at that point on the ro...
```python """ Codeforces 5D - Follow Traffic Rules http://codeforces.com/contest/5/problem/D Héctor González Belver ../07/2018 """ import sys def time_distance(v0, a, d): #quadratic equation. Time is positive ==> root with (+discriminant) in quadratic formula #d = v0*t + (a/2)*t^2 return (-v0 + (v0**2 + 2*a*d)*...
622_B. The Time
You are given the current time in 24-hour format hh:mm. Find and print the time after a minutes. Note that you should find only the time after a minutes, see the examples to clarify the problem statement. You can read more about 24-hour format here <https://en.wikipedia.org/wiki/24-hour_clock>. Input The first line...
```python #!/usr/bin/env python3 import datetime def main(args): hh, mm = list(map(int, input().split(':'))) a = int(input()) mm += a hh += (mm // 60) mm %= 60 hh %= 24 print(f"{hh:02d}:{mm:02d}") return 0 if __name__ == '__main__': import sys sys.exit(main(sys.argv)) ```
670_D2. Magic Powder - 2
The term of this problem is the same as the previous one, the only exception — increased restrictions. Input The first line contains two positive integers n and k (1 ≤ n ≤ 100 000, 1 ≤ k ≤ 109) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ...,...
```python n, k = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) l = 0 r = 10 ** 10 while r - l > 1: m = (r + l) // 2 poroshok = 0 for i in range(n): tr = A[i] * m - B[i] poroshok += max(tr, 0) if poroshok > k: r = m else: ...
696_A. Lorenzo Von Matterhorn
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two...
```python def find_path(x,y): p1,p2 = [],[] while x!=0: p1.append(x) x = x//2 while y!=0: p2.append(y) y = y//2 p1 = p1[::-1] p2 = p2[::-1] # print (p1,p2) for i in range(min(len(p1),len(p2))): if p1[i]==p2[i]: ind = i else: break path = [] for i in range(ind,len(p1)): path.append(p1[i]) p...
717_B. R3D3’s Summer Adventure
R3D3 spent some time on an internship in MDCS. After earning enough money, he decided to go on a holiday somewhere far, far away. He enjoyed suntanning, drinking alcohol-free cocktails and going to concerts of popular local bands. While listening to "The White Buttons" and their hit song "Dacan the Baker", he met anoth...
```python import sys,heapq #sys.stdin=open("data.txt") input=sys.stdin.readline n,a,b=map(int,input().split()) if a<b: a,b=b,a if b==0: # 1 01 001 0001 ... is optimal, plus a long series of 0's print((n-1)*a) else: # pascal's triangle thing pascal=[[1]*20005] for i in range(20004): ...
761_C. Dasha and Password
After overcoming the stairs Dasha came to classes. She needed to write a password to begin her classes. The password is a string of length n which satisfies the following requirements: * There is at least one digit in the string, * There is at least one lowercase (small) letter of the Latin alphabet in the string...
```python n,m=map(int,input().split()) m1,m2,m3=[m+1]*n,[m+1]*n,[m+1]*n for i in range(n): s=input() for j, c in enumerate(s): z=min(j, m-j) if c>='0' and c<='9': m1[i]=min(m1[i],z) else: if c>='a' and c<='z': m2[i]=min(m2[i],z) else: ...
784_E. Twisted Circuit
<image> Input The input consists of four lines, each line containing a single digit 0 or 1. Output Output a single digit, 0 or 1. Example Input 0 1 1 0 Output 0
```python import collections as col import itertools as its import sys import operator from bisect import bisect_left, bisect_right from copy import copy, deepcopy class Solver: def __init__(self): pass def solve(self): a = int(input()) b = int(input()) c = int(input()) ...
805_D. Minimum number of steps
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7...
```python def mess(): String=input() count_it=0 Counter=0 for i in String: if i=='a': count_it = (count_it * 2) % Modulo count_it+=1 elif i=='b': Counter+=count_it #count_it =(count_it* 2)%Modulo return Counter if __name__ == "__main...
830_D. Singer House
It is known that passages in Singer house are complex and intertwined. Let's define a Singer k-house as a graph built by the following process: take complete binary tree of height k and add edges from each vertex to all its successors, if they are not yet present. <image> Singer 4-house Count the number of non-empty ...
```python print([0,1,9,245,126565,54326037,321837880,323252721,754868154,328083248,838314395,220816781,893672292,166441208,251255697,114256285,118775501,482714697,11784725,460862131,550384565,106742050,425241115,626692854,674266678,320014275,345949512,527320049,897822749,137190263,491039182,810384961,482023334,65809986...
876_A. Trip For Meal
Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is a meters, between Rabbit's an...
```python # 876A def main(): n, a, b, c = int(input()), int(input()), int(input()), int(input()) if n == 1: return 0 n -= 1 count = 0 state = 0 while n: if state == 0: if a > b: count += b state = 2 else: count += a state = 1 elif state == 1: if a > c: count += c state = 2 ...
8_A. Train and Peter
Peter likes to travel by train. He likes it so much that on the train he falls asleep. Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour. The boy start...
```python import re I = input s, first, second = I(), I(), I() forward = re.fullmatch('\w*' + first + '\w*' + second + '\w*', s) backward = re.fullmatch('\w*' + first + '\w*' + second + '\w*', s[::-1]) if forward: print('both' if backward else 'forward') else: print('backward' if backward else 'fantasy') ``...
94_A. Restoring Password
Igor K. always used to trust his favorite Kashpirovsky Antivirus. That is why he didn't hesitate to download the link one of his groupmates sent him via QIP Infinium. The link was said to contain "some real funny stuff about swine influenza". The antivirus had no objections and Igor K. run the flash application he had ...
```python s = input() a = [] for i in range(10): a.append(input()) p = 0 while(p < 80): for i in range(10): if a[i] == s[p:p+10]: print(i, end='') p += 10 break ```
977_E. Cyclic Components
You are given an undirected graph consisting of n vertices and m edges. Your task is to find the number of connected components which are cycles. Here are some definitions of graph theory. An undirected graph consists of two sets: set of nodes (called vertices) and set of edges. Each edge connects a pair of vertices....
```python from sys import stdin from collections import deque def bfs(x): vis[x] = True q = deque([x]) ans = 1 while q: cur = q.popleft() ans &= len(g[cur]) == 2 for x in g[cur]: if not vis[x]: vis[x] = True q.append(x) return ans...
p02655 AtCoder Grand Contest 045 - Fragile Balls
We have N boxes numbered 1 to N, and M balls numbered 1 to M. Currently, Ball i is in Box A_i. You can do the following operation: * Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box. Since the balls are very easy to break, you cannot move Ball i more th...
```python import sys from bisect import bisect_left from collections import defaultdict from itertools import accumulate class UnionFind: def __init__(self, n): self.table = [-1] * n def _root(self, x): stack = [] tbl = self.table while tbl[x] >= 0: stack.append(x...
p02784 AtCoder Beginner Contest 153 - Common Raccoon vs Monster
Raccoon is fighting with a monster. The health of the monster is H. Raccoon can use N kinds of special moves. Using the i-th move decreases the monster's health by A_i. There is no other way to decrease the monster's health. Raccoon wins when the monster's health becomes 0 or below. If Raccoon can win without using...
```python h,n = map(int,input().split()) AS = list(map(int,input().split())) print('Yes' if h <= sum(AS) else 'No') ```
p02919 AtCoder Beginner Contest 140 - Second Sum
Given is a permutation P of \\{1, 2, \ldots, N\\}. For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R. Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}. Constraints * 2 \le N \le 10^5 * 1 \le P_i \le N * P_i \neq P_j (i \neq j) * All values...
```python # 区間ではなく各要素を独立に考える典型のやつ # ある値について条件を満たすようにしたいとき # その値より大きいものだけ探せば良い # 具体的には自分より大きい値を1つだけ含むような区間が条件を満たす # 愚直にやると各値について, その左右を近い方から順に見ていかなければならず間に合わない # 自分より大きい値だけ知りたいので, 要素の大きい順に見ていくことで計算量が減る # 普通にやったのが下のコードでAC+TLE(恐らく合ってる) def main(): import sys input = sys.stdin.readline sys.setrecursionlimit...
p03055 AtCoder Grand Contest 033 - Removing Coins
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i. At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation: * Choose a vertex ...
```python import sys from collections import deque sys.setrecursionlimit(10 ** 7) rl = sys.stdin.readline def solve(): N = int(rl()) graph = [[] for _ in range(N)] for _ in range(N - 1): a, b = map(lambda x: int(x) - 1, rl().split()) graph[a].append(b) graph[b].append(a) ...
p03199 CADDi 2018 - Square
Takahashi has an N \times N grid. The square at the i-th row and the j-th column of the grid is denoted by (i,j). Particularly, the top-left square of the grid is (1,1), and the bottom-right square is (N,N). An integer, 0 or 1, is written on M of the squares in the Takahashi's grid. Three integers a_i,b_i and c_i desc...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines """ ・適当な部分空間なので、達成可能でありさえすれば数え上げは簡単 ・対角成分に関して向かい側はまとめる。「必ず0」「必ず1」「free」 ・対角から遠いところについては調整不可能。「必ず1」がここにあると死亡 ・そうでない場合、対角~対角+2までを矛盾なく作れれば勝ち """ import itertools MOD = 998244353 N,M = map(int,r...
p03346 AtCoder Grand Contest 024 - Backfront
You are given a sequence (P_1,P_2,...,P_N) which is a permutation of the integers from 1 through N. You would like to sort this sequence in ascending order by repeating the following operation: * Choose an element in the sequence and move it to the beginning or the end of the sequence. Find the minimum number of op...
```python N = int(input()) P = [int(input()) for _ in range(N)] L = [1]*(N+1) for i in range(N): if P[i] < N and L[P[i]+1] == 1: L[P[i]+1] = L[P[i]]+1 if L[P[i]] == 1: L[P[i]] = 0 ans = N-max(L) print(ans) ```
p03506 Code Festival Team Relay (Parallel) - Evergrowing Tree
You are given an integer N. Consider an infinite N-ary tree as shown below: <image> Figure: an infinite N-ary tree for the case N = 3 As shown in the figure, each vertex is indexed with a unique positive integer, and for every positive integer there is a vertex indexed with it. The root of the tree has the index 1. ...
```python N, Q = map(int, input().split()) vws = [tuple(map(int, input().split())) for _ in range(Q)] anss = [] if N == 1: anss = [min(v, w) for v, w in vws] else: for v, w in vws: v, w = v-1, w-1 while v != w: if v > w: v = (v-1)//N else: ...
p03667 AtCoder Grand Contest 017 - Snuke and Spells
There are N balls in a row. Initially, the i-th ball from the left has the integer A_i written on it. When Snuke cast a spell, the following happens: * Let the current number of balls be k. All the balls with k written on them disappear at the same time. Snuke's objective is to vanish all the balls by casting the ...
```python from collections import Counter n, m = map(int, input().split()) an = list(map(int, input().split())) ac_ = Counter(an) ac = {i: ac_[i] if i in ac_ else 0 for i in range(1, n + 1)} ad = [0] * n for a, c in ac.items(): for i in range(max(0, a - c), a): ad[i] += 1 ans = ad.count(0) anss = [] for x...
p03822 AtCoder Grand Contest 009 - Tournament
N contestants participated in a competition. The total of N-1 matches were played in a knockout tournament. For some reasons, the tournament may not be "fair" for all the contestants. That is, the number of the matches that must be played in order to win the championship may be different for each contestant. The struct...
```python import sys sys.setrecursionlimit(10**5) n = int(input()) dic = {} for i in range(n+1): if i <= 1: continue ai = int(input()) if ai in dic: dic[ai].append(i) else: dic[ai] = [i] def dfs(nxt): lst = [] if nxt in dic: while dic[nxt] != []: child = dic...
p03989 AtCoder Grand Contest 005 - ~K Perm Counting
Snuke loves permutations. He is making a permutation of length N. Since he hates the integer K, his permutation will satisfy the following: * Let the permutation be a_1, a_2, ..., a_N. For each i = 1,2,...,N, |a_i - i| \neq K. Among the N! permutations of length N, how many satisfies this condition? Since the ans...
```python from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil,...
p00077 Run Length
If the strings are consecutive, you can replace the characters with a rule to shorten the string. For example, for the string AAAA, the expression @ 4A will compress one character. Create a program that restores the character string compressed by this rule to the original character string. However, it is assumed that t...
```python while True: try: s = input() except EOFError: break r = '' n = 1 for c in s: if n < 0: n = int(c) elif c == '@': n = -1 else: r += c * n n = 1 print(r) ```
p00209 Scene in a Picture
Mr. A came to Aizu for sightseeing. You can overlook the Aizu Basin from the window of the hotel where you stayed. As I was looking at the scenery, I noticed a piece of the photo on the floor. Apparently I took the outside view from the window. "Which area did you take?" A asked, holding the photo so that the view outs...
```python from sys import stdin readline = stdin.readline from itertools import product from operator import itemgetter from math import isinf def scrap_top_left(picture): for py, px in product(range(len(picture)), repeat=2): if picture[py][px] != -1: return px, py def is_match(window, pic...
p00369 Paper Fortune
If you visit Aizu Akabeko shrine, you will find a unique paper fortune on which a number with more than one digit is written. Each digit ranges from 1 to 9 (zero is avoided because it is considered a bad omen in this shrine). Using this string of numeric values, you can predict how many years it will take before your ...
```python def sub(maxs, mins): for i in range(len(maxs)): if maxs[i] != mins[i]: if i == len(maxs)-1: return int(maxs[i]) - int(mins[i]) if i == len(maxs)-2: return int(maxs[i:i+2]) - int(mins[i:i+2]) return 10 return 0 def checkEqual(...
p00586 A + B Problem
Compute A + B. Constraints * -1000 ≤ A, B ≤ 1000 Input The input will consist of a series of pairs of integers A and B separated by a space, one pair of integers per line. The input will be terminated by EOF. Output For each pair of input integers A and B, you must output the sum of A and B in one line. Example ...
```python ans="" while True: try: info=input() except: break if ans!="": ans+="\n" info_2=info.split() ans+=str(int(info_2[0])+int(info_2[1])) print(ans) ```
p00723 Organize Your Train part II
RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1. <image> Figure B-1: Layout of the exchange lines A freight train consists of 2 to 72 freight cars. There are 26 types of freight cars, which are d...
```python import itertools def main(): n = int(input()) for _ in range(n): s = input() ssum = set() for i in range(len(s)): l = s[:i] rl = l[::-1] r = s[i:] rr = r[::-1] ssum.add(l+r) ssum.add(r+l) ssum....
p01126 Amida
The mayor of Amida, the City of Miracle, is not elected like any other city. Once exhausted by long political struggles and catastrophes, the city has decided to leave the fate of all candidates to the lottery in order to choose all candidates fairly and to make those born under the lucky star the mayor. I did. It is a...
```python while True: n, m, a = map(int, input().split(' ')) if n == 0 and m == 0 and a == 0: break hl = [list(map(int, input().split(' '))) for i in range(m)] hl.sort(key=lambda x: x[0], reverse=True) vl = a for l in hl: if l[1] == vl: vl = l[2] elif l[2] == ...
p01425 White Bird
Angry Birds is a mobile game of a big craze all over the world. You were convinced that it was a waste of time to play the game, so you decided to create an automatic solver. <image> You are describing a routine that optimizes the white bird's strategy to defeat a pig (enemy) by hitting an egg bomb. The white bird fo...
```python # aoj 2308 import sys input = sys.stdin.readline def calc_y(vy, t): return vy*t - g/2*t*t def loc(y, b, t): if y < b+eps: return -1 if y > t-eps: return 1 return 0 def can_hit(x, y): if x == 0: return False a = g*g/4 b = g*y-V*V c = x*x+y*y D =...
p01741 Manhattan
In Manhattan, roads run where the x or y coordinate is an integer. Both Sunuke-kun's house and Sumeke-kun's house are on the road, and the straight line distance (Euclidean distance) is just d. Find the maximum value that can be considered as the shortest distance when traveling along the road from Sunuke-kun's house t...
```python #!/usr/bin/env python3 d = float(input()) ans = max(2**0.5 * d, int(d) + 1) print(ans) ```
p01881 Help the Princess!
Example Input 2 4 %.@\$ ..\$\$ Output Yes
```python import queue di = [0,1,0,-1] dj = [1,0,-1,0] h, w = map(int, input().split()) field = [input() for i in range(h)] pdist = [[1000]*w for i in range(h)] sdist = [[1000]*w for i in range(h)] pque = queue.Queue() sque = queue.Queue() for i,row in enumerate(field): for j in range(w): if row[j] is '@...
p02018 Surmise
D: Sontaku (Surmise) Some twins like even numbers. Count how many even numbers are in $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $. input The integer $ N $ is given on the first line. On the second line, $ N $ integers $ A_1, A_2, A_3, \ dots, A_N $ are given, separated by blanks. output Output an even number. ...
```python N = int(input()) A = [int(x)%2 for x in input().split()] ans = N - sum(A) print(ans) ```
p02301 Diameter of a Convex Polygon
Find the diameter of a convex polygon g. In other words, find a pair of points that have maximum distance between them. Constraints * 3 ≤ n ≤ 80000 * -100 ≤ xi, yi ≤ 100 * No point in the g will occur more than once. Input n x1 y1 x2 y2 : xn yn The first integer n is the number of points in g. In the following ...
```python #!/usr/bin/python3 import array from fractions import Fraction import functools import itertools import math import os import sys def main(): N = read_int() P = [] for _ in range(N): x, y = [Fraction(s) for s in inp().split()] P.append(Vec(x, y)) print(solve(N, P)) def lcm...
p02448 Sorting Tuples
Write a program which reads $n$ items and sorts them. Each item has attributes $\\{value, weight, type, date, name\\}$ and they are represented by $\\{$ integer, integer, upper-case letter, integer, string $\\}$ respectively. Sort the items based on the following priorities. 1. first by value (ascending) 2. in case of...
```python # AOJ ITP2_5_B: Sorting Tuples # Python3 2018.6.24 bal4u tbl = [] n = int(input()) for i in range(n): a = input().split() tbl.append((int(a[0]), int(a[1]), a[2], int(a[3]), a[4])) tbl.sort() for i in tbl: print(*i) ```
1005_C. Summarize to the Power of Two
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d). For example, the following sequences are good: * [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum ...
```python from collections import* input() arr = Counter(map(int,input().split())) binpow = [2**i for i in range(31)] deleted = 0 for item in list(arr.elements()): flag = True for bp in binpow: if (arr.get(bp - item) != None): if (bp - item == item): if (arr.get(bp - item) > ...
1029_A. Many Equal Substrings
You are given a string t consisting of n lowercase Latin letters and an integer number k. Let's define a substring of some string s with indices from l to r as s[l ... r]. Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other...
```python n, k = map(int, input().split()) s = input() ans = None for i in range(1, n): prefix = s[0:n-i] suffix = s[i:n] if prefix == suffix: ans = prefix ans += s[n-i:n] * k break if ans is None: ans = s * k print (ans) ```
1071_A. Cram Time
In a galaxy far, far away Lesha the student has just got to know that he has an exam in two days. As always, he hasn't attended any single class during the previous year, so he decided to spend the remaining time wisely. Lesha knows that today he can study for at most a hours, and he will have b hours to study tomorro...
```python def get_out(list): print(len(list)) out=' '.join(list) print(out) arr = input().split() a = int(arr[0]) b = int(arr[1]) s=a+b temp=0 i=0 while(temp<=s): i+=1 temp+=i i-=1 list_a=[] list_b=[] for x in range(i,0,-1): if(a-x>=0): a-=x list_a.append(str(x...
1093_C. Mishka and the Last Exam
Mishka is trying really hard to avoid being kicked out of the university. In particular, he was doing absolutely nothing for the whole semester, miraculously passed some exams so that just one is left. There were n classes of that subject during the semester and on i-th class professor mentioned some non-negative inte...
```python n = int(input()) b = input().split() b = [int(x) for x in b] a = [0 for x in range(n)] a[0] = 0 a[n - 1] = b[0] for i in range(1, n//2): left = i right = n - i - 1 a[left] = 0 a[right] = b[i] if a[right] > a[right + 1]: diff = a[right] - a[right + 1] a[right] -= diff ...
1113_C. Sasha and a Bit of Relax
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
```python n = int(input()) a = [int(x) for x in input().split()] pref = [0] for i in range(n): pref.append(pref[-1] ^ a[i]) dp = [[0 for i in range(2**20 + 5)] for j in range(2)] ans = 0 for i in range(len(pref)): ans += dp[i % 2][pref[i]] dp[i % 2][pref[i]] += 1 #print(ans, pref[i]) print(ans) ```
1141_F1. Same Sum Blocks (Easy)
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
```python import time def index(key, item, index): if key in index: index[key].append(item) else: index[key] = [item] def schedule2(times): # print(times) result = [] a_min = 0 for s, e in times: if s >= a_min: result.append((s, e)) a_min = e ...
1182_E. Product Oriented Recurrence
Let f_{x} = c^{2x-6} ⋅ f_{x-1} ⋅ f_{x-2} ⋅ f_{x-3} for x ≥ 4. You have given integers n, f_{1}, f_{2}, f_{3}, and c. Find f_{n} mod (10^{9}+7). Input The only line contains five integers n, f_{1}, f_{2}, f_{3}, and c (4 ≤ n ≤ 10^{18}, 1 ≤ f_{1}, f_{2}, f_{3}, c ≤ 10^{9}). Output Print f_{n} mod (10^{9} + 7). Exam...
```python mod = 1000000007 X = [[1,1,1], [1,0,0], [0,1,0]] def mul(A, B): return [[sum(a*b for a,b in zip(X_row,Y_col)) % ( mod-1 ) for Y_col in zip(*B)] for X_row in A] def pow_n(A, n): if n == 1: return A A_ = pow_n(A, n // 2) if n % 2 == 0: return A_ * A_...
11_E. Forward, march!
Jack has become a soldier now. Unfortunately, he has trouble with the drill. Instead of marching beginning with the left foot and then changing legs with each step, as ordered, he keeps repeating a sequence of steps, in which he sometimes makes the wrong steps or — horror of horrors! — stops for a while. For example, i...
```python def solve(): original = input() temp = [original[0]] for i in range(1, len(original)): if original[i] == original[i - 1] != 'X': temp.append('X') temp.append(original[i]) augmented = ''.join(temp) answer = 0 if augmented[0] == augmented[-1] != 'X': a...
1283_A. Minutes Before the New Year
New Year is coming and you are excited to know how many minutes remain before the New Year. You know that currently the clock shows h hours and m minutes, where 0 ≤ hh < 24 and 0 ≤ mm < 60. We use 24-hour time format! Your task is to find the number of minutes before the New Year. You know that New Year comes when the...
```python for _ in range(int(input())): h,m = map(int,input().split()) print((24*60)-(h*60+m)) ```
1326_F1. Wise Men (Easy Version)
This is the easy version of the problem. The difference is constraints on the number of wise men and the time limit. You can make hacks only if all versions of this task are solved. n wise men live in a beautiful city. Some of them know each other. For each of the n! possible permutations p_1, p_2, …, p_n of the wise...
```python from sys import stdout n = int(input()) class Person: num = n - 1 def __init__(self, rel): self.relationship = int(rel, 2) def __getitem__(self, k): return (self.relationship >> Person.num - k) & 1 rel = [Person(input()) for _ in range(n)] dp = [[0] * n for _ in range(1 <<...
1345_F. Résumé Review
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you ha...
```python import sys import heapq as hq readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) eps = 10**-7 def solve(): n, k = nm() a = nl() ans = [0]*n ok = 10**9...
1367_E. Necklace Assembly
The store sells n beads. The color of each bead is described by a lowercase letter of the English alphabet ("a"–"z"). You want to buy some beads to assemble a necklace from them. A necklace is a set of beads connected in a circle. For example, if the store sells beads "a", "b", "c", "a", "c", "c", then you can assemb...
```python from collections import Counter from math import ceil, sqrt class DisjSet: def __init__(self, n): # Constructor to create and # initialize sets of n items self.rank = [1] * n self.parent = [i for i in range(n)] self.extra = [] # Finds set of given item x ...
1409_C. Yet Another Array Restoration
We have a secret array. You don't know this array and you have to restore it. However, you know some facts about this array: * The array consists of n distinct positive (greater than 0) integers. * The array contains two elements x and y (these elements are known for you) such that x < y. * If you sort the arr...
```python T = int(input()) for t in range(T): n, x, y = [int(i) for i in input().split()] found_flag = False for d in range(1,51): if (y-x) % d == 0: for a in range(1, x+1): if (x-a) % d == 0 and (y-a) % d == 0 and a + (n-1)* d >= y: ans = [a+i*d for i...
1430_A. Number of Apartments
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar...
```python for _ in range(int(input())): n = int(input()) if n%3==0:print(n//3,0,0) elif n%5==0:print(0,n//5,0) elif n%7==0:print(0,0,n//7) elif n%3==1 and n>7:print((n-7)//3,0,1) elif n%3==2 and n>7:print((n-5)//3,1,0) else:print(-1) ```
1453_C. Triangles
Gildong has a square board consisting of n rows and n columns of square cells, each consisting of a single digit (from 0 to 9). The cell at the j-th column of the i-th row can be represented as (i, j), and the length of the side of each cell is 1. Gildong likes big things, so for each digit d, he wants to find a triang...
```python import sys input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def getAns(d): #return answer for digit d ans=0 maxI=-1 minI=n smallestJForEachI=[None for _ in range(n)] largestJForEachI=...
1477_A. Nezzar and Board
n distinct integers x_1,x_2,…,x_n are written on the board. Nezzar can perform the following operation multiple times. * Select two integers x,y (not necessarily distinct) on the board, and write down 2x-y. Note that you don't remove selected numbers. Now, Nezzar wonders if it is possible to have his favorite nu...
```python import os import sys from io import BytesIO, IOBase from math import gcd BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "...
1503_E. 2-Coloring
There is a grid with n rows and m columns. Every cell of the grid should be colored either blue or yellow. A coloring of the grid is called stupid if every row has exactly one segment of blue cells and every column has exactly one segment of yellow cells. In other words, every row must have at least one blue cell, an...
```python M=998244353;N=4042 try: import __pypy__ int_add=__pypy__.intop.int_add int_sub=__pypy__.intop.int_sub int_mul=__pypy__.intop.int_mul def make_mod_mul(mod=M): fmod_inv=1.0/mod def mod_mul(a,b,c=0): res=int_sub( int_add(int_mul(a,b),c), ...
1527_C. Sequence Pair Weight
The weight of a sequence is defined as the number of unordered pairs of indexes (i,j) (here i < j) with same value (a_{i} = a_{j}). For example, the weight of sequence a = [1, 1, 2, 2, 1] is 4. The set of unordered pairs of indexes with same value are (1, 2), (1, 5), (2, 5), and (3, 4). You are given a sequence a of n...
```python def cal(n,ind_list): ind1_list = [ind+1 for ind in ind_list] red_list = [n-ind for ind in ind_list] pre_sum = [0] for ind1 in ind1_list: pre_sum.append(pre_sum[-1]+ind1) res = 0 for i in range(1,len(red_list)): res += red_list[i]*pre_sum[i] return res ...
159_B. Matchmaker
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a m...
```python def main(): from sys import stdin l = list(map(int, stdin.read().split())) n, yx = l[0] * 2, [[0] * 1001 for _ in range(1001)] cnt = yx[0] u = v = 0 for y, x in zip(l[3:n + 3:2], l[2:n + 2:2]): cnt[y] += 1 yx[y][x] += 1 ba, l = list(zip(l[n + 3::2], l[n + 2::2])), [...
178_D3. Magic Squares
The Smart Beaver from ABBYY loves puzzles. One of his favorite puzzles is the magic square. He has recently had an idea to automate the solution of this puzzle. The Beaver decided to offer this challenge to the ABBYY Cup contestants. The magic square is a matrix of size n × n. The elements of this matrix are integers....
```python import sys, random def f(b): global a a = [[0] * n for o in range(n)] for i in range(n): for j in range(n): a[i][j] = b[i * n + j] rez = 0 for i in range(n): ns = 0 for j in range(n): ns += a[i][j] rez += abs(su - ns) for j i...
24_B. F1 Champions
Formula One championship consists of series of races called Grand Prix. After every race drivers receive points according to their final position. Only the top 10 drivers receive points in the following order 25, 18, 15, 12, 10, 8, 6, 4, 2, 1. At the conclusion of the championship the driver with most points is the cha...
```python points = [25, 18, 15, 12, 10, 8, 6, 4, 2, 1] + [0] * 40 numRaces = int(input()) scores = {} for race in range(numRaces): numDrivers = int(input()) for d in range(numDrivers): driver = input() if not driver in scores: scores[driver] = [0] + [0] * 50 + [driver] scores[driver][0] += points...
320_C. Malek Dance Club
As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member o...
```python #!/usr/local/bin/python3.3 -tt import sys if __name__ == '__main__': for l in sys.stdin: s = l.strip() break n = len(s) d = 2 ** (n - 1) print(d * int(s, 2) % 1000000007) ```
391_A. Genetic Engineering
You will receive 3 points for solving this problem. Manao is designing the genetic code for a new type of algae to efficiently produce fuel. Specifically, Manao is focusing on a stretch of DNA that encodes one protein. The stretch of DNA is represented by a string containing only the characters 'A', 'T', 'G' and 'C'. ...
```python class CodeforcesTask391ASolution: def __init__(self): self.result = '' self.dna = '' def read_input(self): self.dna = input() def process_task(self): currc = '' count = 0 inserts = 0 for c in self.dna: if currc != c: ...
412_E. E-mail Addresses
One of the most important products of the R1 company is a popular @r1.com mail service. The R1 mailboxes receive and send millions of emails every day. Today, the online news thundered with terrible information. The R1 database crashed and almost no data could be saved except for one big string. The developers assume ...
```python from sys import stdin, stdout, setrecursionlimit input = stdin.readline # setrecursionlimit(int(1e6)) inf = float('inf') from functools import cmp_to_key from collections import defaultdict as dd from collections import Counter, deque from heapq import * import math from math import floor, ceil, sqrt def geti...
43_B. Letter
Vasya decided to write an anonymous letter cutting the letters out of a newspaper heading. He knows heading s1 and text s2 that he wants to send. Vasya can use every single heading letter no more than once. Vasya doesn't have to cut the spaces out of the heading — he just leaves some blank space to mark them. Help him;...
```python s1 = ''.join(input().split()) s2 = ''.join(input().split()) for i in s2: if s2.count(i) > s1.count(i): print("NO") exit(0) print("YES") ```
485_C. Bits
Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and <image> is maximum possible. If there are multiple such numbers find the sma...
```python for i in range(int(input())): l,r=map(int,input().split()) L=list(bin(l)) R=list(bin(r)) L=L[2:] R=R[2:] w=0 c=0 L=['0']*(len(R)-len(L))+L #print(L,R) ans=0 if l==r: print(l) continue for i in range(len(R)): if L[i]!=R[i]: for...
509_C. Sums of Digits
Vasya had a strictly increasing sequence of positive integers a1, ..., an. Vasya used it to build a new sequence b1, ..., bn, where bi is the sum of digits of ai's decimal representation. Then sequence ai got lost and all that remained is sequence bi. Vasya wonders what the numbers ai could be like. Of all the possibl...
```python def fill9(x,u): k=x//9 for i in range(k): u[i]=9 if x%9: u[k]=x%9 return k+1 else: return k n=input() n=int(n) u=[0 for i in range(300//9*150+150)] k=1 for i in range(n): x=input() x=int(x) t=k-1 while t>=0: if u[t]+9*t<x: t=f...
533_E. Correcting Mistakes
Analyzing the mistakes people make while typing search queries is a complex and an interesting work. As there is no guaranteed way to determine what the user originally meant by typing some query, we have to use different sorts of heuristics. Polycarp needed to write a code that could, given two words, check whether t...
```python def aux(s, t): n = len(s) lpr = 0 for i in range(n): if s[i] != t[i]: break lpr += 1 lsf = 0 for i in range(n-1, -1, -1): if s[i] != t[i]: break lsf += 1 if(lpr == n): return 2 return (s[lpr:n-lsf-1] == t[lpr+1:n-ls...
558_D. Guess Your Way Out! II
Amr bought a new video game "Guess Your Way Out! II". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the nodes of the tree such tha...
```python h,q=map(int,input().split()) d=[(2**h,0),(2**(h-1),0)] for _ in range(q): i,l,r,a=map(int,input().split()) l,r=l*2**(h-i),(r+1)*2**(h-i) d.extend([[(l,1),(r,-1)],[(0,1),(l,-1),(r,1)]][a]) s=0 l=0 d=sorted(d) for (a,x),(b,_) in zip(d,d[1:]): s+=x if a!=b and s==0:q=a;l+=b-a print(("Game che...
584_B. Kolya and Tanya
Kolya loves putting gnomes at the circle table and giving them coins, and Tanya loves studying triplets of gnomes, sitting in the vertexes of an equilateral triangle. More formally, there are 3n gnomes sitting in a circle. Each gnome can have from 1 to 3 coins. Let's number the places in the order they occur in the ci...
```python n = int(input()) print((27 ** n - 7 ** n) % (10 ** 9 + 7)) ```
606_B. Testing Robots
The Cybernetics Failures (CF) organisation made a prototype of a bomb technician robot. To find the possible problems it was decided to carry out a series of tests. At the beginning of each test the robot prototype will be placed in cell (x0, y0) of a rectangular squared field of size x × y, after that a mine will be i...
```python q,b,c,d = map(int,input().split()) s = input() x,y =c,d l = 1 print(1,end = ' ') a = set() a.add((c,d)) for i in range(len(s)-1): item = s[i] if (item == 'U'): if(x == 1 or (x-1,y) in a): print(0,end = ' ') if(x-1,y) in a: x-=1 else: ...