name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p02925 AtCoder Beginner Contest 139 - League | N players will participate in a tennis tournament. We will call them Player 1, Player 2, \ldots, Player N.
The tournament is round-robin format, and there will be N(N-1)/2 matches in total. Is it possible to schedule these matches so that all of the following conditions are satisfied? If the answer is yes, also find t... | ```python
n=int(input());l=[list(map(int,input().split()))for i in[0]*n];a=[0]*n;d=1;k=n*(n-1)
while sum(a)<k and d<9999:
L=[0]*n;y=0;d+=1
for i in range(n):
if a[i]<n-1:
x=l[i][a[i]]-1
if l[x][a[x]]-1==i and L[x]+L[i]<1:
a[i]+=1;a[x]+=1;L[i]=L[x]=y=1
d*=y;print([k//2,d-1][d<9999])
``` |
p03060 AtCoder Beginner Contest 125 - Resale | There are N gems. The value of the i-th gem is V_i.
You will choose some of these gems, possibly all or none, and get them.
However, you need to pay a cost of C_i to get the i-th gem.
Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.
Find the maximum possible value of X-Y.
Co... | ```python
n = int(input())
Vi = map(int, input().split())
Ci = map(int, input().split())
print(sum([max(0, v-c) for (v, c) in zip(Vi, Ci)]))
``` |
p03351 AtCoder Beginner Contest 097 - Colorful Transceivers | Three people, A, B and C, are trying to communicate using transceivers. They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively. Two people can directly communicate when the distance between them is at most d meters. Determine if A and C can communicate, either ... | ```python
a,b,c,d = list(map(int,input().split()))
print('Yes' if (abs(a-b)<=d and abs(b-c)<=d) or abs(a-c)<=d else 'No')
``` |
p03511 Code Festival Team Relay (Parallel) - Coinage | You are given two strings s and t consisting of lowercase English letters and an integer L.
We will consider generating a string of length L by concatenating one or more copies of s and t. Here, it is allowed to use the same string more than once.
For example, when s = `at`, t = `code` and L = 6, the strings `atatat`... | ```python
L = int(input())
s = input()
t = input()
if not s+t <= t+s:
s, t = t, s
ls = len(s); lt = len(t)
for i in range(L // ls, -1, -1):
if (L - ls*i) % lt == 0:
ans = s * i + t * ((L - ls*i) // lt)
break
print(ans)
``` |
p03672 AtCoder Beginner Contest 066 - ss | We will call a string that can be obtained by concatenating two equal strings an even string. For example, `xyzxyz` and `aaaaaa` are even, while `ababab` and `xyzxy` are not.
You are given an even string S consisting of lowercase English letters. Find the length of the longest even string that can be obtained by delet... | ```python
n = input()
num = len(n)-2
for i in range(num,0,-2):
f = int(i/2)
if n[:f]==n[f:i]:
print(i)
break
``` |
p03827 AtCoder Beginner Contest 052 - Increment Decrement | You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | ```python
x = 0
_n = input()
s = input()
maxX = x
for c in s:
x = x + (1 if c == "I" else -1)
maxX = max(maxX, x)
print(maxX)
``` |
p03994 CODE FESTIVAL 2016 qual A - Next Letter | Mr. Takahashi has a string s consisting of lowercase English letters. He repeats the following operation on s exactly K times.
* Choose an arbitrary letter on s and change that letter to the next alphabet. Note that the next letter of `z` is `a`.
For example, if you perform an operation for the second letter on `aa... | ```python
def dist(c):
return (ord('z') - ord(c) + 1) % 26
s = list(input())
k = int(input())
i = 0
while 0 < k and i < len(s):
d = dist(s[i])
if d <= k:
k -= d
s[i] = 'a'
i += 1
s[-1] = chr((ord(s[-1]) + (k % 26)))
print(''.join(s))
``` |
p00082 Flying Jenny | <image>
You know the merry-go-round in the amusement park. Vehicles such as horses and carriages are fixed on a large disk, and it is a standard playset that the vehicle swings up and down at the same time as the disk rotates. A merry-go-round in an amusement park has two four-seater carriages, two two-seater cars, f... | ```python
from copy import copy
p = []
while(1):
try:
p = [int(i) for i in input().split()]
min_ = 10**10
point = 0
arrmin = []
arr = [4,1,4,1,2,1,2,1]
for _ in range(8):
temp = copy(arr[0])
repl = copy(arr[1:8])
arr[0:7] = repl
... |
p00214 Autumnal Illumination | In Square Town, where many people who love squares live, a festival is held to color the town with illuminations that combine square lightning boards. This electric board emits light when electricity is applied, and the plate in contact with the light emitting plate also emits light. Therefore, no matter how many elect... | ```python
def dot3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy)
def cross3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (by - oy) - (bx - ox) * (ay - oy)
def dist2(A, B):
ax, ay = A; bx, by = B
return (ax - bx) ** 2 + (ay - ... |
p00591 Advanced Algorithm Class | In the advanced algorithm class, n2 students sit in n rows and n columns. One day, a professor who teaches this subject comes into the class, asks the shortest student in each row to lift up his left hand, and the tallest student in each column to lift up his right hand. What is the height of the student whose both han... | ```python
import sys
while True:
n = int(sys.stdin.readline().rstrip())
if n == 0:
break;
students = []
for i in range(n):
students.append(list(map(int, sys.stdin.readline().rstrip().split(' '))))
s_list=[[min(row)==s for s in row] for row in students]
t_list=[[max(col)==s for s... |
p00728 ICPC Score Totalizer Software | <image>
The International Clown and Pierrot Competition (ICPC), is one of the most distinguished and also the most popular events on earth in the show business.
One of the unique features of this contest is the great number of judges that sometimes counts up to one hundred. The number of judges may differ from one co... | ```python
while 1:
n = int(input())
if n == 0:
break
s = [int(input()) for i in range(n)]
s.sort()
x = sum(s) - (s[0] + s[-1])
print(x // (n - 2))
``` |
p00999 Rental DVD Shop NEO | Problem
I started a part-time job at the rental DVD shop "NEO". First of all, I decided to study the fee system of this store.
There are three types of rental DVDs, old, semi-new, and new, and the rental fee for one DVD is a yen, b yen, and c yen, respectively. The set rental shown below can be applied multiple times... | ```python
# AOJ 1509 Rental DVD Shop NEO
# Python3 2018.7.13 bal4u
while True:
a, b, c, d, e = map(int, input().split())
if a == 0: break
na, nb, nc = map(int, input().split())
if nc >= d: ans = e*nc + b*nb + a*na
else:
ans = c*nc + b*nb + a*na
k = d-nc;
if k <= nb: nb -= k; k = 0
else: k -= nb; nb = 0
... |
p01131 Keitai Message | Alice wants to send an email to Miku on her mobile phone.
The only buttons that can be used for input on mobile phones are number buttons. Therefore, in order to input characters, the number buttons are pressed several times to input characters. The following characters are assigned to the number buttons of the mobile... | ```python
keylist = [
[],
['.', ',', '!', '?', ' '],
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r', 's'],
['t', 'u', 'v'],
['w', 'x', 'y', 'z']
]
for i in range(int(input())):
output = ''
for item in input().split('0'):
if i... |
p01270 Restrictive Filesystem | You are a programmer on the development team for new recording media. This recording medium can be randomly accessed for reading and erasing data. On the other hand, when writing data, access is always performed in order from the beginning, and only the first free space found can be written.
You have begun to build a ... | ```python
from bisect import bisect_right
while True:
N = int(input())
if N==0:
break
mem = [] # (l, r, id)
for _ in range(N):
command = input().split()
if command[0]=="W":
Id, S = map(int, command[1:])
subS = S
idx_mem = 0
idx = ... |
p01886 Share the Ruins Preservation | Example
Input
8
-10 0
-10 5
-5 5
-5 0
10 0
10 -5
5 -5
5 0
Output
50 | ```python
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def cross3(p0, p1, p2):
return (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p1[1] - p0[1]) * (p2[0] - p0[0])
def solve():
N = int(readline())
mp = defaultdict(list)
for i in range(N):
x, y = ... |
p02023 Ravage | I: Ravage
Santa Claus was caught in the illuminations of the city and broke it.
There are N light bulbs in the illumination, and the $ i $ th light bulb only comes on when the voltage is above $ A_i $ and below $ B_i $.
The voltage should be the same everywhere in the illumination.
Find out how many light bulbs can... | ```python
n=int(input())
l=[]
for _ in [0]*n:
a,b=map(int,input().split())
l.extend([(a,1),(b+1,-1)])
l.sort()
c = 0
a = 0
for _,v in l:
c+=v
a=max(a,c)
print(a)
``` |
p02306 Incircle of a Triangle | Write a program which prints the central coordinate ($cx$,$cy$) and the radius $r$ of a incircle of a triangle which is constructed by three points ($x_1$, $y_1$), ($x_2$, $y_2$) and ($x_3$, $y_3$) on the plane surface.
Constraints
* $-10000 \leq x_i, y_i \leq 10000$
* The three points are not on the same straight li... | ```python
import math
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
#3辺の長さ
a = math.sqrt(((x1-x2)**2)+((y1-y2)**2))
b = math.sqrt(((x3-x2)**2)+((y3-y2)**2))
c = math.sqrt(((x1-x3)**2)+((y1-y3)**2))
s = (a+b+c)/2
r = math.sqrt(s*(s-a)*(s-b)*(s-c))/s #ヘロンの公式
x... |
p02453 Lower Bound | For a given sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, find the lower bound for a specific value $k$ given as a query.
* lower bound: the place pointing to the first element greater than or equal to a specific value, or $n$ if there is no such element.
Constraints
* $1 \leq n \le... | ```python
import sys
from bisect import bisect_left
n = int(input())
a = tuple(map(int,sys.stdin.readline().split()))
q = int(input())
l = len(a)
for k in sys.stdin:
k = int(k.strip())
if k > a[-1]:print(l)
else:
print(bisect_left(a,k))
``` |
1009_E. Intercity Travelling | Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.
The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance betwe... | ```python
from sys import stdin, stdout
def main():
p = 998244353 # Constante brindada por el problema
n = int(stdin.readline())
a = list(readline())
answer = a[-1]
pow_ = 1 # Potencia de 2
for i in range(n - 1, 0, -1): # Se analizan todas las dificultades
answer = (answer + a[i - 1... |
1032_B. Personalized Cup | At many competitions that have a word «cup» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner.
The nameplate is to be rectangular an... | ```python
def print2d(a):
for i in range(len(a)):
print(''.join(list(map(str, a[i]))))
st = input()
for i in range(1, 5 + 1):
vst = len(st) // i
ost = len(st) % i
if vst + min(ost, 1) > 20:
continue
a = [0] * i
ind = 0
f = 0
for j in range(len(a)):
a[j] = []
... |
1077_A. Frog Jumping | A frog is currently at the point 0 on a coordinate axis Ox. It jumps by the following algorithm: the first jump is a units to the right, the second jump is b units to the left, the third jump is a units to the right, the fourth jump is b units to the left, and so on.
Formally:
* if the frog has jumped an even numb... | ```python
t=int(input())
while(t):
l=[]
l=[int(x) for x in input().split()]
a=l[0]
b=l[1]
k=l[2]
p=int(k/2)
if k%2==0:
y=(p*a)-(p*b)
else:
y=(p*a)-(p*b)+a
print(y)
t=t-1
``` |
1119_A. Ilya and a Colorful Walk | Ilya lives in a beautiful city of Chordalsk.
There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring.
The ho... | ```python
import math
from decimal import Decimal
import heapq
def na():
n = int(input())
b = [int(x) for x in input().split()]
return n,b
def nab():
n = int(input())
b = [int(x) for x in input().split()]
c = [int(x) for x in input().split()]
return n,b,c
def dv():
n, m = map(int, input().split())
retu... |
1145_E. Fourier Doodles | In this problem you have to solve a simple classification task: given an image, determine whether it depicts a Fourier doodle.
You are given a set of 50 images with ids 1 through 50. You are also given a text file labels.txt containing the labels for images with ids 1 through 20, which comprise the learning data set.... | ```python
for id in range(21, 51):
print(((min(id, 25) + id) % (2 + id % 3)) > 0 and 1 or 0)
``` |
1166_D. Cute Sequences | Given a positive integer m, we say that a sequence x_1, x_2, ..., x_n of positive integers is m-cute if for every index i such that 2 ≤ i ≤ n it holds that x_i = x_{i - 1} + x_{i - 2} + ... + x_1 + r_i for some positive integer r_i satisfying 1 ≤ r_i ≤ m.
You will be given q queries consisting of three positive intege... | ```python
for _ in range(int(input())):
a,b,m=map(int,input().split())
if a==b:
print(1,a)
continue
for k in range(2,51):
pw=1<<(k-2)
mn=pw*(a+1)
mx=pw*(a+m)
if mn<=b<=mx:
r=[0]*(k+1)
add=b-mn
r[1]=a
for i in ran... |
1185_B. Email from Polycarp | Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | ```python
def f():
a=input()
i=0
p=a[i]
l=[]
while(i<len(a)):
temp=1
t=[p]
i+=1
while(i<len(a)):
if a[i]!=p:
p=a[i]
break
p=a[i]
t.append(p)
i+=1
if i==len(a):
... |
1203_F1. Complete the Projects (easy version) | The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version.
Polycarp is a very famous freelancer. His current rating is r units.
Some very rich customers asked him to complete some projects for their companies. To complete ... | ```python
n,r = map(int,(input().split()))
plus=[]
minn=[]
for i in range (0,n):
temp = list(map(int,input().split()))
if temp[1] <=0:
temp.append(temp[0]+temp[1])
minn.append(temp)
else:
plus.append(temp)
plus.sort()
minn.sort(reverse=True,key = lambda x: x[2])
flag = True
for ... |
1220_D. Alex and Julian | Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer n... | ```python
import sys
input=sys.stdin.readline
import copy
from math import *
n=int(input())
a=[int(x) for x in input().split()]
d=[0 for i in range(70)]
for i in range(n):
d[int(log(a[i]&(-a[i]),2))]+=1
print(n-max(d))
r=d.index(max(d))
for i in range(n):
if int(log(a[i]&(-a[i]),2))!=r:
print(a[i],end="... |
1245_F. Daniel and Spring Cleaning | While doing some spring cleaning, Daniel found an old calculator that he loves so much. However, it seems like it is broken. When he tries to compute 1 + 3 using the calculator, he gets 2 instead of 4. But when he tries computing 1 + 4, he gets the correct answer, 5. Puzzled by this mystery, he opened up his calculator... | ```python
def g( a , b ):
cur = 1
res = 0
ze = 0
while cur <= b:
if b & cur:
b ^= cur
if a & b == 0:
res += ( 1 << ze )
if a & cur == 0:
ze = ze + 1
cur <<= 1
return res
def f( a , b ):
res = 0
if a == b:
r... |
1265_D. Beautiful Sequence | An integer sequence is called beautiful if the difference between any two consecutive numbers is equal to 1. More formally, a sequence s_1, s_2, …, s_{n} is beautiful if |s_i - s_{i+1}| = 1 for all 1 ≤ i ≤ n - 1.
Trans has a numbers 0, b numbers 1, c numbers 2 and d numbers 3. He wants to construct a beautiful sequenc... | ```python
_count = list(map(int, input().split()))
num = '0 1 2 3'.split()
for pos in range(4):
count = _count[:]
ans = []
for i in range(sum(count)):
ans.append(num[pos])
count[pos] -= 1
if pos == 1:
if count[0] > 0:
pos = 0
else:
... |
1370_C. Number Game | Ashishgup and FastestFinger play a game.
They start with a number n and play in turns. In each turn, a player can make any one of the following moves:
* Divide n by any of its odd divisors greater than 1.
* Subtract 1 from n if n is greater than 1.
Divisors of a number include the number itself.
The player... | ```python
import math
def isPrime(n) :
# Corner cases
if (n <= 1) :
return False
if (n <= 3) :
return True
# This is checked so that we can skip
# middle five numbers in below loop
if (n % 2 == 0 or n % 3 == 0) :
return False
i = 5
while(i * i <... |
1392_H. ZS Shuffles Cards | zscoder has a deck of n+m custom-made cards, which consists of n cards labelled from 1 to n and m jokers. Since zscoder is lonely, he wants to play a game with himself using those cards.
Initially, the deck is shuffled uniformly randomly and placed on the table. zscoder has a set S which is initially empty.
Every s... | ```python
def modInverse(a, m) :
m0 = m; y = 0; x = 1
if (m == 1): return 0
while (a > 1):
q = a // m; t = m; m = a % m; a = t; t = y; y = x - q * y; x = t
if (x < 0): x = x + m0
return x
prime = 998244353
n, m = map(int, input().split())
z = 0
for i in range(1, n+1): z += modInverse(i, ... |
1417_D. Make Them Equal | You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times:
1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9);
2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i.
After each operation, all elements of the array s... | ```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... |
1434_B. Shurikens | Tenten runs a weapon shop for ninjas. Today she is willing to sell n shurikens which cost 1, 2, ..., n ryo (local currency). During a day, Tenten will place the shurikens onto the showcase, which is empty at the beginning of the day. Her job is fairly simple: sometimes Tenten places another shuriken (from the available... | ```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.... |
1459_B. Move and Turn | A robot is standing at the origin of the infinite two-dimensional plane. Each second the robot moves exactly 1 meter in one of the four cardinal directions: north, south, west, and east. For the first step the robot can choose any of the four directions, but then at the end of every second it has to turn 90 degrees lef... | ```python
def calculate(n):
res = 0
if (n%2 == 1):
for i in range(2, n+2, 2):
res += i
return res * 2
else:
if (n%4 == 0):
for i in range(1, int(n/2) + 1):
res += i
res *= 2
res += n/2 + 1
return int(res)
... |
1485_B. Replace and Keep Sorted | Given a positive integer k, two arrays are called k-similar if:
* they are strictly increasing;
* they have the same length;
* all their elements are positive integers between 1 and k (inclusive);
* they differ in exactly one position.
You are given an integer k, a strictly increasing array a and q quer... | ```python
n, q, k = map(int, input().split())
a = list(map(int, input().split()))
b, c = [], [0]
if n > 1:
for i in range(n):
if i == 0:
b.append(a[i+1] - 3)
elif i == (n-1):
b.append(k - a[i-1] - 2)
else:
b.append(a[i+1] - a[i-1] - 2)
for i in range(n):
c.append(c[i] + b[i])
for i in range(q):
if... |
1509_C. The Sports Festival | The student council is preparing for the relay race at the sports festival.
The council consists of n members. They will run one after the other in the race, the speed of member i is s_i. The discrepancy d_i of the i-th stage is the difference between the maximum and the minimum running speed among the first i members... | ```python
n = int(input())
s = list(map(int, input().split()))
s.sort()
dp = [0]*n
for i in range(1, n):
for j in range(n-i):
dp[j] = s[i+j] - s[j] + min(dp[j], dp[j+1])
print(dp[0])
``` |
1535_D. Playoff Tournament | 2^k teams participate in a playoff tournament. The tournament consists of 2^k - 1 games. They are held as follows: first of all, the teams are split into pairs: team 1 plays against team 2, team 3 plays against team 4 (exactly in this order), and so on (so, 2^{k-1} games are played in that phase). When a team loses a g... | ```python
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
def solve(z, dp, s):
n = len(dp)
while 1:
dp[z] = 0
if s[z] == '?':
if 2 * z + 1 < n:
dp[z] += dp[2 * z + 1]
else:
... |
22_D. Segments | You are given n segments on the Ox-axis. You can drive a nail in any integer point on the Ox-axis line nail so, that all segments containing this point, are considered nailed down. If the nail passes through endpoint of some segment, this segment is considered to be nailed too. What is the smallest number of nails need... | ```python
n = int(input())
lis = list()
cou = 1
arr = list()
for i in range(n):
a, b = map(int, input().split())
if a > b:
lis.append([b, a])
else:
lis.append([a, b])
lis = sorted(lis, key=lambda l: l[1])
i = 0
j = 1
arr.append(lis[i][1])
while(i < n and j < n):
if lis[i][1] < lis[j][0]:... |
255_C. Almost Arithmetical Progression | Gena loves sequences of numbers. Recently, he has discovered a new type of sequences which he called an almost arithmetical progression. A sequence is an almost arithmetical progression, if its elements can be represented as:
* a1 = p, where p is some integer;
* ai = ai - 1 + ( - 1)i + 1·q (i > 1), where q is som... | ```python
import sys
from math import log2,floor,ceil,sqrt
# import bisect
# from collections import deque
Ri = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
d... |
279_C. Ladder | You've got an array, consisting of n integers a1, a2, ..., an. Also, you've got m queries, the i-th query is described by two integers li, ri. Numbers li, ri define a subsegment of the original array, that is, the sequence of numbers ali, ali + 1, ali + 2, ..., ari. For each query you should check whether the correspon... | ```python
n,q = map(int,input().split())
arr = [int(x) for x in input().split()]
inc = [-1] * n
dec = [-1] * n
inc[n-1] = n-1
for i in range(n-2, -1, -1):
if(arr[i]<=arr[i+1]):
inc[i] = inc[i+1]
else:
inc[i] = i
dec[n-1] = n-1
for i in range(n-2, -1, -1):
if(arr[i]>=arr[i+1]):
dec[i]... |
301_B. Yaroslav and Time | Yaroslav is playing a game called "Time". The game has a timer showing the lifespan he's got left. As soon as the timer shows 0, Yaroslav's character dies and the game ends. Also, the game has n clock stations, station number i is at point (xi, yi) of the plane. As the player visits station number i, he increases the c... | ```python
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n, dc = mints()
a = list(mints())
a.append(0)
x = [0]*n
y = [0]*n
for i in range(n):
x[i], y[i] = mints()
d = [1<<30]*n
d[0] = 0
was = [False]*n... |
34_A. Reconnaissance 2 | n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u... | ```python
n = int(input())
a = list(map(int, input().split()))
x = a[0]
for i in range(n-1):
a[i] = abs(a[i] - a[i+1])
a[-1] = abs(x - a[-1])
m = min(a)
ind = a.index(m)
p, q = ind+1, ind+2
if q > n:
q = 1
print(p,q)
``` |
373_B. Making Sequences is Fun | We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.
You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)·k to add the number n to the sequence.
You can spend a cost up... | ```python
from math import *
w, m, k = list(map(int, input().split()))
cnt = 0
add = 9*10**(-1) if m < 10 else 0
for i in range(int(log10(m)), int(1e10)):
v = (9 * 10**i - (m-1-9*10**(i-1)+add if i == int(log10(m)) else 0)) * (i+1) * k
if w - v < 0:
cnt += w//((i+1)*k)
break
w -= v
cnt ... |
394_D. Physical Education and Buns | The Physical education teacher at SESC is a sort of mathematician too. His most favorite topic in mathematics is progressions. That is why the teacher wants the students lined up in non-decreasing height form an arithmetic progression.
To achieve the goal, the gym teacher ordered a lot of magical buns from the dining ... | ```python
q = 10001
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(40000 // (n - 1) + 1):
b = [a[j] - j * i for j in range(n)]
u, v = max(b), min(b)
p = (u - v + 1) // 2
if p < q: q, s, d = p, v + p, i
print(q)
print(s, d)
``` |
417_E. Square Table | While resting on the ship after the "Russian Code Cup" a boy named Misha invented an interesting game. He promised to give his quadrocopter to whoever will be the first one to make a rectangular table of size n × m, consisting of positive integers such that the sum of the squares of numbers for each row and each column... | ```python
"""
Codeforces Round 241 Div 1 Problem E
Author : chaotic_iak
Language: Python 3.3.4
"""
class InputHandlerObject(object):
inputs = []
def getInput(self, n = 0):
res = ""
inputs = self.inputs
if not inputs: inputs.extend(input().split(" "))
if n == 0:
re... |
466_D. Increase Sequence | Peter has a sequence of integers a1, a2, ..., an. Peter wants all numbers in the sequence to equal h. He can perform the operation of "adding one on the segment [l, r]": add one to all elements of the sequence with indices from l to r (inclusive). At that, Peter never chooses any element as the beginning of the segment... | ```python
n,h = map(int,input().split())
a = list(map(int,input().split()))
a = [h-i for i in a]
if min(a) < 0 or a[0] > 1 or a[-1] > 1:
print(0)
else:
t = 1
for i in range(1,n):
dif = a[i-1]-a[i]
if dif >1 or dif <-1:t = 0
else:
if dif == 0:t*=(a[i-1]+1)
elif... |
48_B. Land Lot | Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving ... | ```python
n, m = map(int, input().split())
t = [[0] * (m + 1)] + [[] for i in range(n)]
t[1] = [0] + list(map(int, input().split()))
for j in range(2, m + 1): t[1][j] += t[1][j - 1]
for i in range(2, n + 1):
t[i] = [0] + list(map(int, input().split()))
for j in range(2, m + 1): t[i][j] += t[i][j - 1]
for j ... |
567_B. Berland National Library | Berland National Library has recently been built in the capital of Berland. In addition, in the library you can take any of the collected works of Berland leaders, the library has a reading room.
Today was the pilot launch of an automated reading room visitors' accounting system! The scanner of the system is installed... | ```python
'''input
2
+ 1
- 1
'''
m, p = 0, []
for _ in range(int(input())):
i = input().split()
if i[0] == "+":
p.append(i[1])
else:
if i[1] in p:
p.remove(i[1])
else:
m += 1
m = max(m, len(p))
print(m)
``` |
610_A. Pasha and Stick | Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | ```python
x=int(input())
print((x%2==0)*((x//2-1)//2))
#fueaijskrgd/t
``` |
630_K. Indivisibility | IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible ... | ```python
def precalc(st, end):
count = 0
for i in range(st, end + 1):
if not any(i % k == 0 for k in [2,3,5,7]):
count += 1
return count
n = int(input())
buckets = 2*3*4*5*6*7
c = int(n / buckets)
res = c * precalc(1, buckets) + precalc(c * buckets+1, n)
print(res)
``` |
659_C. Tanya and Toys | In Berland recently a new collection of toys went on sale. This collection consists of 109 types of toys, numbered with integers from 1 to 109. A toy from the new collection of the i-th type costs i bourles.
Tania has managed to collect n different types of toys a1, a2, ..., an from the new collection. Today is Tanya'... | ```python
n, m = map(int, input().split())
a = set(map(int, input().split()))
s, z, k = "", 1, 0
while m >= z:
if z not in a:
m -= z
k += 1
s+=(str(z)+" ")
z += 1
print(k)
print(s)
``` |
727_B. Bill Total Value | Vasily exited from a store and now he wants to recheck the total price of all purchases in his bill. The bill is a string in which the names of the purchases and their prices are printed in a row without any spaces. Check has the format "name1price1name2price2...namenpricen", where namei (name of the i-th purchase) is ... | ```python
import re
def spnum(s):
a = s.split(".")
if len(a[-1]) == 2:
a.append(a[-1])
a[-2] = '.'
return eval("".join(a))
s = input()
dollars = re.findall(r"[.0-9]+", s)
for i in range(len(dollars)):
if "." in dollars[i]:
dollars[i] = spnum(dollars[i])
else:
dollar... |
748_C. Santa Claus and Robot | Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please not... | ```python
n = int(input())
line = input()
moves = 'UDLR'
used = dict()
opp = dict()
opp['U'] = 'D'
opp['D'] = 'U'
opp['L'] = 'R'
opp['R'] = 'L'
for i in moves:
used[i] = 0
i = len(line) - 1
ans = 0
while i >= 0:
ans += 1
for j in moves:
used[j] = 0
while i >= 0 and not used[opp[line[i]]]:
... |
771_B. Bear and Different Names | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names... | ```python
l=['Aa','Ab','Ac','Ad','Ae','Af','Ag','Ah','Ai','Aj','Ak','Al','Am','An','Ao','Ap','Aq','Ar','As','At','Au','Av','Aw','Ax','Ay','Az','Aaa','Abb','Acc','Add','Aee','Aff','Agg','Ahh','Aii','Ajj','Akk','All','Amm','Ann','Aoo','App','Aqq','Arr','Ass','Att','Auu','Avv','Aww','Axx','Ayy']
n,k=map(int,input().split(... |
796_B. Find The Bone | Zane the wizard is going to perform a magic show shuffling the cups.
There are n cups, numbered from 1 to n, placed along the x-axis on a table that has m holes on it. More precisely, cup i is on the table at the position x = i.
The problematic bone is initially at the position x = 1. Zane will confuse the audience b... | ```python
n , m , k = list(map(int,input().split()))
h = list(map(int,input().split()))
used = [0] * int(1e7)
for x in h:
used[x] = 1
t = 1
for i in range(k):
u , v = list(map(int,input().split()))
if used[t]:
print(t)
exit(0)
elif u == t:
if used[v] == 1:
print(v)
exit(0)
t = v
elif v == t... |
816_C. Karen and Game | On the way to school, Karen became fixated on the puzzle game on her phone!
<image>
The game is played as follows. In each level, you have a grid with n rows and m columns. Each cell originally contains the number 0.
One move consists of choosing one row or column, and adding 1 to all of the cells in that row or col... | ```python
n, m = [int(i) for i in input().split(' ')]
g = []
c, f = 0, 0
ans = ''
def row():
global n, m, g, c, ans
for i in range(n):
t = min(g[i])
c += t
ans += ('row %d\n' % (i+1))*t
for j in range(m):
g[i][j] -= t
def col():
global n, m, g, c, ans
for ... |
841_C. Leha and Function | Leha like all kinds of strange things. Recently he liked the function F(n, k). Consider all possible k-element subsets of the set [1, 2, ..., n]. For subset find minimal element in it. F(n, k) — mathematical expectation of the minimal element among all k-element subsets.
But only function does not interest him. He wan... | ```python
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a.sort()
a.reverse()
j=[]
for i in range(n):
j.append([b[i],i])
j.sort()
ans=[0]*n
for i in range(n):
ans[j[i][1]]=str(a[i])
print(' '.join(ans))
``` |
888_B. Buggy Robot | Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0, 0). The robot can process commands. There are four types of commands it can perform:
* U — move from the cell (x, y) to (x, y + 1);
* D — move from (x, y) to (x, y - 1);
* L — move from (x, y) to (x... | ```python
n=input()
s=input()
print((min(s.count('L'),s.count('R'))+min(s.count('D'),s.count('U')))*2)
``` |
910_C. Minimum Sum | Petya has n positive integers a1, a2, ..., an.
His friend Vasya decided to joke and replaced all digits in Petya's numbers with a letters. He used the lowercase letters of the Latin alphabet from 'a' to 'j' and replaced all digits 0 with one letter, all digits 1 with another letter and so on. For any two different di... | ```python
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
import threading
from collections import defaultdict
BUFSIZE = 8192
... |
932_E. Team Work | You have a team of N people. For a particular task, you can pick any non-empty subset of people. The cost of having x people for the task is xk.
Output the sum of costs over all non-empty subsets of people.
Input
Only line of input contains two integers N (1 ≤ N ≤ 109) representing total number of people and k (1 ≤... | ```python
# ############################## import
# def stirling2_list(n, mod=10 ** 9 + 7):
# if not n:
# return [0]
# res = [0, 1]
# for i in range(n - 1):
# res = [0, 1] + [(res[j - 1] + j * res[j]) % mod for j in range(2, 2 + i)] + [1]
# return res
# Explain:
# ans = \sum_{i=1}^{n} \... |
p02584 AtCoder Beginner Contest 175 - Walking Takahashi | Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination wil... | ```python
x,k,d=map(int,input().split())
x=abs(x)
m=min(k,x//d)
x-=d*m
k-=m
k%=2
x-=d*k
print(abs(x))
``` |
p02715 AtCoder Beginner Contest 162 - Sum of gcd of Tuples (Hard) | Consider sequences \\{A_1,...,A_N\\} of length N consisting of integers between 1 and K (inclusive).
There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them.
Since this sum can be enormous, print the value modulo (10^9+7).
Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1... | ```python
mod = 10 ** 9 + 7
N, K = map(int, input().split())
A = [0] + [pow(K // x, N, mod) for x in range(1, K + 1)]
for x in reversed(range(1, K + 1)):
for i in range(2, K // x + 1):
A[x] -= A[i * x]
print(sum(i * a for i, a in enumerate(A)) % mod)
``` |
p02844 Sumitomo Mitsui Trust Bank Programming Contest 2019 - Lucky PIN | AtCoder Inc. has decided to lock the door of its office with a 3-digit PIN code.
The company has an N-digit lucky number, S. Takahashi, the president, will erase N-3 digits from S and concatenate the remaining 3 digits without changing the order to set the PIN code.
How many different PIN codes can he set this way?
... | ```python
N = int(input())
S = input()
ans = 0
for i in range(1000):
cnt = 0
n = str(i).zfill(3)
for c in S:
if c == n[cnt]:
cnt += 1
if cnt == 3:
ans += 1
break
print(ans)
``` |
p02981 AtCoder Beginner Contest 133 - T or T | N of us are going on a trip, by train or taxi.
The train will cost each of us A yen (the currency of Japan).
The taxi will cost us a total of B yen.
How much is our minimum total travel expense?
Constraints
* All values in input are integers.
* 1 \leq N \leq 20
* 1 \leq A \leq 50
* 1 \leq B \leq 50
Input
Input i... | ```python
n,a,b = map(int,input().split())
print(min(b,a*n))
``` |
p03264 AtCoder Beginner Contest 108 - Pair | Find the number of ways to choose a pair of an even number and an odd number from the positive integers between 1 and K (inclusive). The order does not matter.
Constraints
* 2\leq K\leq 100
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the number of ways to... | ```python
K = int(input())
print((K//2)*(-(-K//2)))
``` |
p03422 AtCoder Regular Contest 091 - Strange Nim | Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
* Choose a pile. If the i-th pile is selected and th... | ```python
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ i... |
p03580 CODE FESTIVAL 2017 qual B - 101 to 010 | N cells are arranged in a row. Some of them may contain tokens. You are given a string s that consists of `0`s and `1`s. If the i-th character of s is `1`, the i-th cell (from left) contains a token. Otherwise, it doesn't contain a token.
Snuke wants to perform the following operation as many times as possible. In eac... | ```python
import sys
readline = sys.stdin.readline
INF = 10**9+7
class Segtree:
def __init__(self, A, intv, initialize = True, segf = max):
self.N = len(A)
self.N0 = 2**(self.N-1).bit_length()
self.intv = intv
self.segf = segf
if initialize:
self.data = [intv]*se... |
p03737 AtCoder Beginner Contest 059 - Three-letter acronym | You are given three words s_1, s_2 and s_3, each composed of lowercase English letters, with spaces in between. Print the acronym formed from the uppercased initial letters of the words.
Constraints
* s_1, s_2 and s_3 are composed of lowercase English letters.
* 1 ≤ |s_i| ≤ 10 (1≤i≤3)
Input
Input is given from Stan... | ```python
l=input().split()
r=''
for i in l:
r+=i[0].upper()
print(r)
``` |
p03899 CODE FESTIVAL 2016 Tournament Round 3 (Parallel) - Struck Out | There are N panels arranged in a row in Takahashi's house, numbered 1 through N. The i-th panel has a number A_i written on it. Takahashi is playing by throwing balls at these panels.
Takahashi threw a ball K times. Let the panel hit by a boll in the i-th throw be panel p_i. He set the score for the i-th throw as i \t... | ```python
from collections import deque
N, M, K = map(int, input().split())
A = list(map(int, input().split()))
#dp[i][j]: i番目の的をj回目にあてた時のpointの最大値
dp = [0] * (N + 1)
for j in range(K):
newDP = [0] * (N + 1)
que = deque() # val, index
for i in range(j, N - K + j + 1):
while que and que[-1][0] < dp... |
p00005 GCD and LCM | Write a program which computes the greatest common divisor (GCD) and the least common multiple (LCM) of given a and b.
Constraints
* 0 < a, b ≤ 2,000,000,000
* LCM(a, b) ≤ 2,000,000,000
* The number of data sets ≤ 50
Input
Input consists of several data sets. Each data set contains a and b separated by a single spa... | ```python
def gcd(a,b):
a,b=max(a,b),min(a,b)
while b!=0:
a,b=b,a%b
return a
def lcm(a,b):
return a*b//gcd(a,b)
while True:
try:
x,y=map(int,input().split())
print(gcd(x,y),lcm(x,y))
except EOFError:
break
``` |
p00137 Middle-Square Method | Create a program of the square picking method, which is one of the classical random number generation methods. The square harvesting method was proposed by von Neumann in the mid-1940s.
In the square picking method, when the number of digits of the generated random number is n, the square of the initial value s is cal... | ```python
def method(s):
count=0
ans=[]
while count!=10:
s=str(s**2).zfill(8)
s=int(s[2]+s[3]+s[4]+s[5])
ans.append(s)
count +=1
return ans
N=int(input())
for i in range(N):
s=int(input())
print("Case %d:"%(i+1))
for j in range(10):
print(method(s)[j])... |
p00270 Railroad | We have decided to introduce an automatic ticket gate to the railway network of a certain country. One of the difficult issues to implement is determining whether a given ticket can move between designated stations. Each ticket has a boarding station and a getting-off station. With this ticket, you can not only "get on... | ```python
from heapq import heappush, heappop
s, r = map(int, input().split())
edges = [[] for _ in range(s)]
for _ in range(r):
u, v, w = map(int, input().split())
u -= 1
v -= 1
edges[u].append((v, w))
edges[v].append((u, w))
a, b, q = map(int, input().split())
a -= 1
b -= 1
def dijkstra(start)... |
p00458 Crossing Black Ice | problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided ... | ```python
def solve():
while True:
m, n = int(input()), int(input())
if not m:
break
ices = [[0] + list(map(int,input().split())) + [0] for _ in range(n)]
ices.insert(0, [0] * (m + 2),)
ices.append([0] * (m + 2))
score = [[0] * (m + 2) for _ in range(n + 2)]
for x in range(1, n... |
p00648 Watchin' TVA | Animation is one of methods for making movies and in Japan, it is popular to broadcast as a television program or perform as a movie. Many people, especially the young, love one. And here is an anime lover called Jack. We say he is an mysterious guy with uncertain age. He likes anime which are broadcasted in midnight a... | ```python
# AOJ 1063: Watchin' TVA
# Python3 2018.7.8 bal4u
while True:
n = int(input())
if n == 0: break
dic, tbl = {}, []
for i in range(n):
nm, w, s = input().split()
w, s = int(w), int(s)
h, m = s//100, s%100
s = (1440*w + h*60 + m) % 10080
e = s + 30;
tbl.append([s, e, 0, nm])
dic[nm] = i
for i... |
p00924 Bit String Reordering | Example
Input
6 3
1 0 0 1 0 1
1 3 2
Output
1 | ```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 = 998244353
dd = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x i... |
p01942 Taiyaki-Master and Eater | E: Taiyaki-Master and Eater
story
Tsuta is very good at making Taiyaki. Ebi-chan loves Taiyaki made by Tsuta-san. The two are happy to make and eat Taiyaki every week, but Tsuta-san's recent worries are that Ebi-chan, who is in the middle of eating, eats the food while making Taiyaki.
Mr. Tsuta, who decided to make ... | ```python
from heapq import heappush, heappop
H, W, T, Q = map(int, input().split())
que = []
state = [[0]*(W+1) for i in range(H+1)]
data1 = [[0]*(W+1) for i in range(H+1)]
data2 = [[0]*(W+1) for i in range(H+1)]
def get(data, h, w):
s = 0
while h:
w0 = w
el = data[h]
while w0:
... |
p02223 String Set | Problem statement
Of the string set $ S $ that meets the following conditions, configure $ 1 $ with the largest number of elements.
* The length of the string contained in $ S $ is $ 1 $ or more and $ N $ or less.
* The lengths of the strings contained in $ S $ are different.
* The string contained in $ S $ consists ... | ```python
N = int(input())
if N==1:
print(1)
print(0)
elif N==2:
print(2)
print(0)
print(11)
else:
print(N-1)
for i in range(N-1):
print('0' + '1'*i + '0')
``` |
p02375 Range Query on a Tree II | Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ t... | ```python
#!/usr/bin/env python3
# GRL_5_E: Tree - Range Query on Tree 2
# Undirected Graph
class Edge:
__slots__ = ('v', 'w')
def __init__(self, v, w):
self.v = v
self.w = w
def either(self):
return self.v
def other(self, v):
if v == self.v:
return self.... |
1042_B. Vitamins | Berland shop sells n kinds of juices. Each juice has its price c_i. Each juice includes some set of vitamins in it. There are three types of vitamins: vitamin "A", vitamin "B" and vitamin "C". Each juice can contain one, two or all three types of vitamins in it.
Petya knows that he needs all three types of vitamins to... | ```python
n = int(input())
a = [1000000,1000000,1000000,1000000,1000000,1000000,1000000]
for i in range(n):
s = input()
k = s.split(" ")
q = int(k[0])
p = k[1]
p = sorted(p)
p = "".join(p)
if(p=='A' or p=='B' or p=='C'):
a[int(ord(p[0])-ord('A'))] = min(a[int(ord(p[0])-ord... |
1065_A. Vasya and Chocolate | There is a special offer in Vasya's favourite supermarket: if the customer buys a chocolate bars, he or she may take b additional bars for free. This special offer can be used any number of times.
Vasya currently has s roubles, and he wants to get as many chocolate bars for free. Each chocolate bar costs c roubles. He... | ```python
n = int(input())
for i in range(n):
a,b,c,d = map(int,input().split())
z = a//d
x = z//b
v = x*c
print(z+v)
``` |
1133_F1. Spanning Tree with Maximum Degree | You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degre... | ```python
def dfs(s):
stk,cnt=[],[]
stk.append(s)
cnt.append(0)
while (len(stk)>0):
s=stk[-1]
ll=cnt[-1]
visit[s]=1
flag=1
for j in range(ll,len(adj[s]),1):
if visit[adj[s][j]]==0:
cnt[-1]=j+1
stk.append(adj[s][j])
cnt.append(0)
flag=0
break
if flag:
stk.pop()
cnt.pop()
n,m... |
1154_C. Gourmet Cat | Polycarp has a cat and his cat is a real gourmet! Dependent on a day of the week he eats certain type of food:
* on Mondays, Thursdays and Sundays he eats fish food;
* on Tuesdays and Saturdays he eats rabbit stew;
* on other days of week he eats chicken stake.
Polycarp plans to go on a trip and already pa... | ```python
import copy
nums = [0, 1, 2, 0, 2, 1, 0]
asdf = [3, 2, 2]
things = list(map(int, input().split(' ')))
max_idx = 0
for i in range(7):
stuff = copy.deepcopy(things)
idx = i
while stuff[0] >= 0 and stuff[1] >= 0 and stuff[2] >= 0 and idx < 7:
stuff[nums[idx % 7]] -= 1
idx += 1
num... |
1176_A. Divide it! | You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | ```python
nq=int(input())
q=[int(input()) for i in range(nq)]
def check3(number):
l=list(str(number))
s=0
for i in l:
s+=int(i)
if s%3==0 :
return 'yes'
else:
return 'no'
def check5(number):
if number%10==5 or number%10==0:
return 'yes'
else:
return 'no... |
1234_B2. Social Network (hard version) | The only difference between easy and hard versions are constraints on n and k.
You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0... | ```python
#!/usr/bin/env python3
'''
https://github.com/dhruvildave
http://codeforces.com/contest/1234/problem/B1
'''
from collections import deque
def soln() -> None:
'''Driver code'''
def logic() -> None:
'''Logic'''
n, k = [int(x) for x in input().split()]
arr = [int(x) for x in in... |
1253_A. Single Push | You're given two arrays a[1 ... n] and b[1 ... n], both of the same length n.
In order to perform a push operation, you have to choose three integers l, r, k satisfying 1 ≤ l ≤ r ≤ n and k > 0. Then, you will add k to elements a_l, a_{l+1}, …, a_r.
For example, if a = [3, 7, 1, 4, 1, 2] and you choose (l = 3, r = 5, ... | ```python
T=int(input())
s=[]
for t in range(T):
dif=0;h=0
n=int(input())
a=[int(k) for k in input().split()]
b =[int(k) for k in input().split()]
for i in range (n):
if(a[i]==b[i]):
continue
else:
dif=b[i]-a[i]
h=i
break
if(dif<0):... |
1296_F. Berland Beauty | There are n railway stations in Berland. They are connected to each other by n-1 railway sections. The railway network is connected, i.e. can be represented as an undirected tree.
You have a map of that network, so for each railway section you know which stations it connects.
Each of the n-1 sections has some integer... | ```python
import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
from collections import deque
n = int(input())
G = [[] for i in range(n)]
edges = []
for i in range(n-1):
a,b = map(int, input().split())
a,b = a-1,b-1
G[a].append(b)
G[b].append(a)
edges.append((a,b))
dep = [0]... |
1320_A. Journey Planning | Tanya wants to go on a journey across the cities of Berland. There are n cities situated along the main railroad line of Berland, and these cities are numbered from 1 to n.
Tanya plans her journey as follows. First of all, she will choose some city c_1 to start her journey. She will visit it, and after that go to som... | ```python
n = int(input())
a = input().split()
a = [int(x) for x in a]
a = [a[i]-i for i in range(n)]
d = {}
for i in range(n):
if (a[i] not in d):
d[a[i]] = 0
d[a[i]] += a[i]+i
m = 0
for k in d:
m = max(m,d[k])
print(m)
``` |
1339_D. Edge Weight Assignment | You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_... | ```python
import sys
lines = sys.stdin.readlines()
n = int(lines[0].strip())
edges = {}
for i in range(1,n):
(u, v) = map(int, lines[i].strip().split(" "))
if u not in edges: edges[u] = []
if v not in edges: edges[v] = []
edges[u].append(v)
edges[v].append(u)
leaves = []
parLeave = {}
for u in edge... |
1360_H. Binary Median | Consider all binary strings of length m (1 ≤ m ≤ 60). A binary string is a string that consists of the characters 0 and 1 only. For example, 0110 is a binary string, and 012aba is not. Obviously, there are exactly 2^m such strings in total.
The string s is lexicographically smaller than the string t (both have the sam... | ```python
for nt in range(int(input())):
n,m = map(int,input().split())
r = []
for i in range(n):
r.append(int(input(),2))
r.sort()
left = 2**m-n
med = (left-1)//2
for i in range(n):
if r[i]<=med:
med+=1
ans = bin(med)[2:]
ans = "0"*(m-len(ans))+ans
print (ans)
``` |
1381_A2. 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
import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict
from bisect import bisect_left as bl, bisect_right as br
from collections import Counter
from collections import deque
ip = lambda : int(stdin.readline())
inp ... |
1401_B. Ternary Sequence | You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | ```python
def checkKey(dict, key):
if key in dict:
return True
return False
# def helper(s):
# l=len(s)
# if (l==1):
# l=[]
# l.append(s)
# return l
# ch=s[0]
# recresult=helper(s[1:])
# myresult=[]
# myresult.append(ch)
# for st in recresult:
# myresult.append(st)
# ts=ch+st
# myresult.append(t... |
1424_I. Bubble Cup hypothesis | The Bubble Cup hypothesis stood unsolved for 130 years. Who ever proves the hypothesis will be regarded as one of the greatest mathematicians of our time! A famous mathematician Jerry Mao managed to reduce the hypothesis to this problem:
Given a number m, how many polynomials P with coefficients in set {\{0,1,2,3,4,5,... | ```python
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from hea... |
1496_A. Split it! | Kawashiro Nitori is a girl who loves competitive programming.
One day she found a string and an integer. As an advanced problem setter, she quickly thought of a problem.
Given a string s and a parameter k, you need to check if there exist k+1 non-empty strings a_1,a_2...,a_{k+1}, such that $$$s=a_1+a_2+… +a_k+a_{k+1}... | ```python
from os import path
import sys,time
# mod = int(1e9 + 7)
# import re
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque
from itertools import combinations ,accumulate
# from string import ascii_lowercase ,ascii_uppercase
from bisect imp... |
1519_D. Maximum Sum of Products | You are given two integer arrays a and b of length n.
You can reverse at most one subarray (continuous subsegment) of the array a.
Your task is to reverse such a subarray that the sum ∑_{i=1}^n a_i ⋅ b_i is maximized.
Input
The first line contains one integer n (1 ≤ n ≤ 5000).
The second line contains n integers ... | ```python
import random
from datetime import datetime
def test(n, a, b):
def testOdd(k):
result = base_sum
curr_sum = base_sum
for i in range(1, n):
i1 = k - i
i2 = k + i
if i1 < 0 or i2 >=n:
break
curr_sum = curr_sum - (a[i1... |
1546_D. AquaMoon and Chess | Cirno gave AquaMoon a chessboard of size 1 × n. Its cells are numbered with integers from 1 to n from left to right. In the beginning, some of the cells are occupied with at most one pawn, and other cells are unoccupied.
In each operation, AquaMoon can choose a cell i with a pawn, and do either of the following (if po... | ```python
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import ... |
194_A. Exams | One day the Codeforces round author sat exams. He had n exams and he needed to get an integer from 2 to 5 for each exam. He will have to re-sit each failed exam, i.e. the exam that gets mark 2.
The author would need to spend too much time and effort to make the sum of his marks strictly more than k. That could have s... | ```python
n, k = map(int, input().split())
q = k // n
r = k % n
if q > 2:
print(0)
else:
print(n - r)
``` |
218_A. Mountain Scenery | Little Bolek has found a picture with n mountain peaks painted on it. The n painted peaks are represented by a non-closed polyline, consisting of 2n segments. The segments go through 2n + 1 points with coordinates (1, y1), (2, y2), ..., (2n + 1, y2n + 1), with the i-th segment connecting the point (i, yi) and the point... | ```python
n, k = map(int, input().split())
tab = [int(x) for x in input().split()]
i = 1
while k > 0:
if tab[i - 1] < tab[i] - 1 and tab[i + 1] < tab[i] - 1:
tab[i] -= 1
k -= 1
i += 2
print(' '.join(map(str, tab)))
``` |
241_E. Flights | LiLand is a country, consisting of n cities. The cities are numbered from 1 to n. The country is well known because it has a very strange transportation system. There are many one-way flights that make it possible to travel between the cities, but the flights are arranged in a way that once you leave a city you will ne... | ```python
#Flights
from queue import Queue
def BFS(node ,mk,G):
q = Queue()
q.put(node)
mk[node] = True
while not q.empty():
top = q.get()
for ady in G[top]:
if not mk[ady]:
mk[ady] = True
q.put(ady)
def InitValue(n,m):
G1 = [[]for _ in... |
28_D. Don't fear, DravDe is kind | A motorcade of n trucks, driving from city «Z» to city «З», has approached a tunnel, known as Tunnel of Horror. Among truck drivers there were rumours about monster DravDe, who hunts for drivers in that tunnel. Some drivers fear to go first, others - to be the last, but let's consider the general case. Each truck is de... | ```python
n = int(input())
v = n*[-1]
c = n*[-1]
L = n*[-1]
R = n*[-1]
for i in range(n):
v[i], c[i], L[i], R[i] = map(int, input().split())
index = [i for i in range(n)]
index.sort(key = lambda i: (c[i]+L[i]+R[i], i))
prev = n*[-1]
best_res = 0
best_last = -1
ii = 0
while ii < n:
i = index[ii]
jj = ii
... |
315_D. Sereja and Periods | Let's introduce the designation <image>, where x is a string, n is a positive integer and operation " + " is the string concatenation operation. For example, [abc, 2] = abcabc.
We'll say that string s can be obtained from string t, if we can remove some characters from string t and obtain string s. For example, string... | ```python
b, p = map(int, input().split())
s1 = input()
s2 = input()
cnt = [0] * len(s2)
nxt = [0] * len(s2)
for i in range(len(s2)):
pos = i
for j in range(len(s1)):
if s1[j] == s2[pos]:
pos += 1
if pos == len(s2):
cnt[i] += 1
pos = 0
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.