name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
313_C. Ilya and Matrix | Ilya is a very good-natured lion. He likes maths. Of all mathematical objects, his favourite one is matrices. Now he's faced a complicated matrix problem he needs to solve.
He's got a square 2n × 2n-sized matrix and 4n integers. You need to arrange all these numbers in the matrix (put each number in a single individua... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.wri... |
335_F. Buy One, Get One Free | A nearby pie shop is having a special sale. For each pie you pay full price for, you may select one pie of a strictly lesser value to get for free. Given the prices of all the pies you wish to acquire, determine the minimum total amount you must pay for all of the pies.
Input
Input will begin with an integer n (1 ≤ n... | ```python
#https://codeforces.com/problemset/problem/335/F
h = [i for i in range(500001)]
t = [i for i in range(500001)]
ans = 0
len = 0
nw = 0
tot = 0
cnt = 0
a = []
def work(x):
y = x >> 1
while y and h[y] > h[x]:
tmp = h[x]
h[x] = h[y]
h[y] = tmp
x = y
y = x >> 1
de... |
359_A. Table | Simon has a rectangular table consisting of n rows and m columns. Simon numbered the rows of the table from top to bottom starting from one and the columns — from left to right starting from one. We'll represent the cell on the x-th row and the y-th column as a pair of numbers (x, y). The table corners are cells: (1, 1... | ```python
n,m=map(int,input().split())
l=[list(map(int,input().split())) for _ in range(n)]
for i in range(n):
if (i==0 or i==n-1) and sum(l[i]): print(2); break
elif l[i][0]==1 or l[i][-1]==1: print(2); break
else: print(4)
``` |
452_C. Magic Trick | Alex enjoys performing magic tricks. He has a trick that requires a deck of n cards. He has m identical decks of n different cards each, which have been mixed together. When Alex wishes to perform the trick, he grabs n cards at random and performs the trick with those. The resulting deck looks like a normal deck, but m... | ```python
import sys
import os
n,m = map(float, sys.stdin.readline().split())
res = 0
if (n == 1):
res = 1
else:
res = (1+(n-1)*(m-1)/(n*m-1))/n
print(res)
``` |
475_A. Bayan Bus | The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
<image>
The event coordinator has a list of k participants who should be picked up at the airport.... | ```python
def main():
n = int(input())
print("+------------------------+")
b1 = 0
if n == 0:
b1 = 0
elif 1 <= n <= 4:
b1 = 1
else:
b1 = (n + 1) // 3
if 0 <= n <= 1:
b2 = 0
elif 2 <= n <= 5:
b2 = 1
else:
b2 = n // 3
b3 = 0
if n <... |
499_A. Watching a movie | You have decided to watch the best moments of some movie. There are two buttons on your player:
1. Watch the current minute of the movie. By pressing this button, you watch the current minute of the movie and the player automatically proceeds to the next minute of the movie.
2. Skip exactly x minutes of the movi... | ```python
class CodeforcesTask499ASolution:
def __init__(self):
self.result = ''
self.n_x = []
self.best_moments = []
def read_input(self):
self.n_x = [int(x) for x in input().split(" ")]
for x in range(self.n_x[0]):
self.best_moments.append([int(j) for j in ... |
522_B. Photo to Remember | One day n friends met at a party, they hadn't seen each other for a long time and so they decided to make a group photo together.
Simply speaking, the process of taking photos can be described as follows. On the photo, each photographed friend occupies a rectangle of pixels: the i-th of them occupies the rectangle of... | ```python
h,w=[],[]
n=int(input())
for i in range(n):
a,b=map(int,input().split())
w.append(a)
h.append(b)
maxh=max(h)
maxh2=-1
if h.count(maxh)>1: maxh2=maxh
else:
for i in h:
if i<maxh:
maxh2=max(maxh2,i)
sumw=sum(w)
for i in range(n):
W=sumw-w[i]
if h[i]==maxh: H=maxh2
... |
549_D. Haar Features | The first algorithm for detecting a face on the image working in realtime was developed by Paul Viola and Michael Jones in 2001. A part of the algorithm is a procedure that computes Haar features. As part of this task, we consider a simplified model of this concept.
Let's consider a rectangular image that is represent... | ```python
n,m=map(int,input().strip().split())
s=[]
for i in range(n):
s.append(input())
f=[[0 for i in range(m+1)] for j in range(n+1)]
ans=0
for k in range(n+m,1,-1):
for i in range(n,0,-1):
j=k-i
if (j>m or j<1):
continue
#print(str(i)+" "+str(j)+s[i-1][j-1])
tmp=0... |
598_A. Tricky Sum | In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | ```python
t = int(input())
while(t):
n = int(input())
s = n*(n+1) // 2
k = len(format(n, "b"))
s_pair = 2**k - 1
print(s - 2*s_pair)
t-=1
``` |
667_A. Pouring Rain | A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition — when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything ... | ```python
from math import pi
d,h,v,e=map(int,input().split())
v=v/(pi*((d/2)**2))
d=h/(v-e)
if v-e>0 and d<=10000:
print('YES')
print(d)
else:
print('NO')
``` |
690_B2. Recover Polygon (medium) | Now that Heidi has made sure her Zombie Contamination level checker works, it's time to strike! This time, the zombie lair is a strictly convex polygon on the lattice. Each vertex of the polygon occupies a point on the lattice. For each cell of the lattice, Heidi knows the level of Zombie Contamination – the number of ... | ```python
import math
def lexComp(a, b):
if a[0] != b[0]:
return -1 if a[0] < b[0] else 1
if a[1] != b[1]:
return -1 if a[1] < b[1] else 1
return 0
def turn(a, b, c):
return (b[0] - a[0]) * (c[1] - b[1]) - (b[1] - a[1]) * (c[0] - b[0])
def dist2(a, b):
return (a[0] - b[0]) ** ... |
713_C. Sonya and Problem Wihtout a Legend | Sonya was unable to think of a story for this problem, so here comes the formal description.
You are given the array containing n positive integers. At one turn you can pick any element and increase or decrease it by 1. The goal is the make the array strictly increasing by making the minimum possible number of operati... | ```python
# Idea:
# convert the problem to making array a non decreasing by decreasing each ai by i
# Now we can argue that the optimal final array must have
# each element equal to some element of the array a.
# Proof is to assume optimal solution does not satisfy this then you can
# always increase or decrease one e... |
734_A. Anton and Danik | Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | ```python
n=int(input())
s=input()
c=0
c1=0
for i in s:
if i=="D":
c=c+1
else:
c1=c1+1
if c>c1:
print("Danik")
elif c<c1:
print("Anton")
else:
print("Friendship")
``` |
758_A. Holiday Of Equality | In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | ```python
n = int(input())
s = 0
mx = 0
a = list((map(int,input().split())))
for i in range(n):
s+=a[i]
mx = max(mx,a[i])
print(mx*n-s)
``` |
779_E. Bitwise Formula | Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game.
Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, ... | ```python
n, m = map(int, input().split())
v = [('?', '')]
temp = [(0, 1)]
d = {}
d['?'] = 0
mn, mx = '', ''
for i in range(n):
name, val = input().split(' := ')
v.append((name, val.split()))
temp.append((-1, -1))
d[name] = i + 1
def eval(expr, bit1, bit2):
if expr == 'OR':
return bit1 |... |
802_M. April Fools' Problem (easy) | The marmots have prepared a very easy problem for this year's HC2 – this one. It involves numbers n, k and a sequence of n positive integers a1, a2, ..., an. They also came up with a beautiful and riveting story for the problem statement. It explains what the input means, what the program should output, and it also rea... | ```python
n,k=map(int,input().split());print(sum(sorted(list(map(int,input().split())))[:k]))
``` |
827_B. High Load | Arkady needs your help again! This time he decided to build his own high-speed Internet exchange point. It should consist of n nodes connected with minimum possible number of wires into one network (a wire directly connects two nodes). Exactly k of the nodes should be exit-nodes, that means that each of them should be ... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if s... |
849_B. Tell Your World | Connect the countless points with lines, till we reach the faraway yonder.
There are n points on a coordinate plane, the i-th of which being (i, yi).
Determine whether it's possible to draw two parallel and non-overlapping lines, such that every point in the set lies on exactly one of them, and each of them passes th... | ```python
def run():
n = int(input())
a = [int(x) for x in input().split()]
_s = set(a)
if len(_s) == 1:
print('No')
return
if len(_s) == 2:
print('Yes')
return
def check(dy, base):
st = [False] * n
for i in range(n):
if (a[i] - a[ba... |
870_E. Points, Lines and Ready-made Titles | You are given n distinct points on a plane with integral coordinates. For each point you can either draw a vertical line through it, draw a horizontal line through it, or do nothing.
You consider several coinciding straight lines as a single one. How many distinct pictures you can get? Print the answer modulo 109 + 7.... | ```python
import sys
from math import *
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
n = mint()
p = [0]*n
x = dict()
y = dict()
for i in range(n):
a = tuple(mints())
p[i] = a
if a[0] in x:
x[a[0]].append(i)
else:
x[a[0]] = [i]... |
897_D. Ithea Plays With Chtholly | This is an interactive problem. Refer to the Interaction section below for better understanding.
Ithea and Chtholly want to play a game in order to determine who can use the kitchen tonight.
<image>
Initially, Ithea puts n clear sheets of paper in a line. They are numbered from 1 to n from left to right.
This game ... | ```python
import sys
n, m, c = map(int, input().split())
free = n
nums = [0] * n
for i in range(m):
pi = int(input())
if(pi > c//2):
current = n - 1
while(nums[current] > 0 and nums[current] >= pi and current >= 0):current -= 1
if(current == -1):current = 0
if(nums[current] == ... |
940_E. Cashback | Since you are the best Wraith King, Nizhniy Magazin «Mir» at the centre of Vinnytsia is offering you a discount.
You are given an array a of length n and an integer c.
The value of some array b of length k is the sum of its elements except for the <image> smallest. For example, the value of the array [3, 1, 6, 5, 2]... | ```python
from heapq import *
f = lambda: map(int, input().split())
n, c = f()
a = list(f()) + [0] * c
b = [0] * (n + c)
s = 0
h = [(0, -1)]
for i in range(n):
s += a[i] - a[i - c]
heappush(h, (a[i], i))
while h[0][1] <= i - c: heappop(h)
b[i] = min(b[i - 1] + a[i], b[i - c] + s - h[0][0])
print(b[n - 1... |
96_B. Lucky Numbers (easy) | Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. Fo... | ```python
gh=set()
def rep(n,four,seven):
global gh
if n>10000000000 :return
if (four==seven):gh|={n}
rep(n*10+4,four+1,seven)
rep(n*10+7,four,seven+1)
rep(0,0,0)
gh=sorted(gh)
def bin_s(a):
lo=0;hi=len(gh);ans=0
while lo<=hi:
mid=(lo+hi)//2
if gh[mid]>=a:ans=gh[mid];hi=mid-1... |
994_B. Knights of a Polygonal Table | Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no mo... | ```python
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
d={}
l=[]
for i in range(n):
x=a[i]
y=b[i]
l.append((x,y))
l.sort()
ans=[]
j=0
if k==0:
print(*b)
else:
for i in range(n):
if i<k:
ans.append(l[i][1])
ans.sort()
... |
p02634 AtCoder Grand Contest 046 - Extension | We have a grid with A horizontal rows and B vertical columns, with the squares painted white. On this grid, we will repeatedly apply the following operation:
* Assume that the grid currently has a horizontal rows and b vertical columns. Choose "vertical" or "horizontal".
* If we choose "vertical", insert one row at th... | ```python
a, b, c, d = map(int,input().split())
mod = 998244353
A = [[0] * (d+1) for i in range(c+1)]
A[a][b] = 1
for i in range(a, c+1):
for j in range(b, d+1):
A[i][j] = (A[i][j] + A[i][j-1] * i + A[i-1][j] * j ) % mod
if i!=a and j!=b:
A[i][j] = (A[i][j] - A[i-1][j-1] * (i-1)*(j-1))... |
p02765 AtCoder Beginner Contest 156 - Beginner | Takahashi is a member of a programming competition site, ButCoder.
Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating.
The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn... | ```python
N, R = map(int, input().split())
print(R + max(0, 100 * (10 - N)))
``` |
p02900 AtCoder Beginner Contest 142 - Disjoint Set of Common Divisors | Given are positive integers A and B.
Let us choose some number of positive common divisors of A and B.
Here, any two of the chosen divisors must be coprime.
At most, how many divisors can we choose?
Definition of common divisor
An integer d is said to be a common divisor of integers x and y when d divides both x a... | ```python
import fractions
a,b=map(int,input().split())
g=fractions.gcd(a,b)
#print(g)
ans=1
i=2
while i*i<=g:
if(g%i==0):
ans+=1
while g%i==0:
g/=i
i=i+1
if(g!=1):ans+=1
print(ans)
``` |
p03035 AtCoder Beginner Contest 127 - Ferris Wheel | Takahashi, who is A years old, is riding a Ferris wheel.
It costs B yen (B is an even number) to ride the Ferris wheel if you are 13 years old or older, but children between 6 and 12 years old (inclusive) can ride it for half the cost, and children who are 5 years old or younger are free of charge. (Yen is the currenc... | ```python
a,b = map(int,input().split())
if a > 12:
print(b)
elif a < 6:
print(0)
else:
print(b//2)
``` |
p03176 Educational DP Contest - Flowers | There are N flowers arranged in a row. For each i (1 \leq i \leq N), the height and the beauty of the i-th flower from the left is h_i and a_i, respectively. Here, h_1, h_2, \ldots, h_N are all distinct.
Taro is pulling out some flowers so that the following condition is met:
* The heights of the remaining flowers ar... | ```python
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
def sum(self, i):
s = 0
while i > 0:
s = max(s, self.tree[i])
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tre... |
p03324 AtCoder Beginner Contest 100 - Ringo's Favorite Numbers | Today, the memorable AtCoder Beginner Contest 100 takes place. On this occasion, Takahashi would like to give an integer to Ringo.
As the name of the contest is AtCoder Beginner Contest 100, Ringo would be happy if he is given a positive integer that can be divided by 100 exactly D times.
Find the N-th smallest intege... | ```python
D, N = map(int, input().split(" "))
print(((100**D)*(N+(N//100))))
``` |
p03478 AtCoder Beginner Contest 083 - Some Sums | Find the sum of the integers between 1 and N (inclusive), whose sum of digits written in base 10 is between A and B (inclusive).
Constraints
* 1 \leq N \leq 10^4
* 1 \leq A \leq B \leq 36
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print the s... | ```python
N, A, B = map(int, input().split())
print(sum(i for i in range(1, N+1) if A <= sum(int(c) for c in str(i)) <= B))
``` |
p03643 AtCoder Beginner Contest 068 - ABCxxx | This contest, AtCoder Beginner Contest, is abbreviated as ABC.
When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC.
What is the abbreviation for the N-th round of ABC? Write a program to output the answer.
Constraints
* 100 ≤ N ≤ 999
I... | ```python
S = input()
print("ABC"+S)
``` |
p03801 AtCoder Regular Contest 069 - Frequency | Snuke loves constructing integer sequences.
There are N piles of stones, numbered 1 through N. The pile numbered i consists of a_i stones.
Snuke will construct an integer sequence s of length Σa_i, as follows:
1. Among the piles with the largest number of stones remaining, let x be the index of the pile with the sma... | ```python
N = int(input())
As = list(map(int, input().split()))
sorted_iAs = sorted(map(tuple, enumerate(As)), key = lambda t: (t[1], t[0]), reverse = True)
#if As = 1 2 1 3 2 4 2 5 8 1
#then sorted_iAs is:
# i | 8 7 5 3 6 4 1 9 2 0
# A | 8 5 4 3 2 2 2 1 1 1
#I'll look at:
# x x x x x x
#where the n... |
p00058 Orthogonal | Read the coordinates of four different points on the plane, $ A (x_A, y_A) $, $ B (x_B, y_B) $, $ C (x_C, y_C) $, $ D (x_D, y_D) $, and straight line $ Create a program that outputs YES if AB $ and $ CD $ are orthogonal, and NO if they are not orthogonal. Here, "straight line" does not mean a line segment. Please refer... | ```python
E = 10 ** -10
while True:
try:
xa, ya, xb, yb, xc, yc, xd, yd = map(float, input().split())
vabx, vaby = xb - xa, yb - ya
vcdx, vcdy = xd - xc, yd - yc
print("YES" if abs(vabx * vcdx + vaby * vcdy) < E else "NO")
except EOFError:
break
``` |
p00189 Convenient Location | Mr. A, who will graduate next spring, decided to move when he got a job. The company that finds a job has offices in several towns, and the offices that go to work differ depending on the day. So Mr. A decided to live in a town where he had a short time to go to any office.
So you decided to find the most convenient t... | ```python
INF = 10 ** 10
while True:
n = int(input())
if n == 0:
break
costs = [[INF] * 10 for _ in range(10)]
for i in range(10):
costs[i][i] = 0
city = set()
for _ in range(n):
a, b, c = map(int, input().split())
city = city | {a, b}
costs[a][b] = c
costs[b][a] = c
city =... |
p00344 Cyclic Sugoroku | Yuki made a sugoroku so that everyone can play at the children's association event. In this sugoroku, squares are lined up in a ring, and each square has an integer of 1 or more written on it.
The player chooses a square as a starting point and places his piece. Advance the pieces clockwise by the number written on th... | ```python
import sys
sys.setrecursionlimit(1000000)
def dfs(x, order, edges, visited):
visited[x] = True
for e in edges[x]:
if not visited[e]:
dfs(e, order, edges, visited)
order.append(x)
def dfs_rev(x, rev_edges, visited):
visited[x] = True
ret = 0
for e in rev_edges[x]:
if not visited[e]:... |
p00843 Bingo | A Bingo game is played by one gamemaster and several players. At the beginning of a game, each player is given a card with M × M numbers in a matrix (See Figure 10).
<image>
As the game proceeds, the gamemaster announces a series of numbers one by one. Each player punches a hole in his card on the announced number, i... | ```python
def solve():
from itertools import product
from sys import stdin
f_i = stdin
while True:
P, M = map(int, f_i.readline().split())
if P == 0:
break
bingo = []
for i in range(P):
b = []
card = list(map(int, f_i.read... |
p01107 Go around the Labyrinth | Go around the Labyrinth
Explorer Taro got a floor plan of a labyrinth. The floor of this labyrinth is in the form of a two-dimensional grid. Each of the cells on the floor plan corresponds to a room and is indicated whether it can be entered or not. The labyrinth has only one entrance located at the northwest corner, ... | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import copy
def rdp_connect() -> bool:
global n, m, c
n, m = map(int, input().split())
if n == m == 0:
return False
c = [list(input()) for _ in range(n)]
return True
def rdp_check() -> bool:
DY = (0, 1, 0, -1)
DX = (1, 0, -1... |
p01560 Enumeration | Given n integers a1, a2,…, an and n integers p1, p2,…, pn, integer m. The operation of selecting the kth integer ak with a probability of pk [%] is performed for each k (1 ≤ k ≤ n), and 0 or more and n or less integers are selected. Find the expected number of integers between 1 and m that are divisible by at least one... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p01722 Fast Division | Ikta loves fast programs. Recently, I'm trying to speed up the division program. However, it doesn't get much faster, so I thought it would be better to make it faster only for "common sense and typical" inputs. The problem Ikta is trying to solve is as follows.
For a given non-negative integer n, divide p (n) − 1-dig... | ```python
# p(n) = 2^^n より大きい最小の素数 (ただし^^はクヌースの二重矢印記号) と定義したとき、
# x = (10^(p(n)-1)-1)/9 (mod p(n)) を求めよ
# 「フェルマーの小定理」
# pが素数ならば、a^p == a (mod p(n))
# とくに、aとpが互いに素 (gcd(a,p)=1) のとき
# a^p * a^-1 == a * a^-1 (mod p(n))
# a^(p-1) == 1 (mod p)
#
# 9とp(n)が互いに素ならば
# x * 9^-1 = 10^(p(n)-1)-1 (mod p(n))
# 10とp(n)が互いに素ならば
# 10^(... |
p01995 Palindromic Subsequences | G: Palindromic Subsequences
problem
Given a string S consisting only of lowercase letters, find out how many subsequences of this string S are not necessarily continuous and are palindromes.
Here, a subsequence that is not necessarily continuous with S is an arbitrary selection of one or more characters | S | charac... | ```python
def main():
from bisect import bisect_left as bl
from bisect import bisect_right as br
s=input()
alpha="abcdefghijklmnopqrstuvwxyz"
l=len(s)
alpha2={j:i for i,j in enumerate(alpha)}
memo=[[] for _ in [0]*26]
mod=10**9+7
for i in range(l):
memo[alpha2[s[i]]].append(i... |
p02141 Donut Hole | Problem
You brought a flat, holeless donut with a $ W $ horizontal $ H $ vertical $ H $ rectangle for ACPC.
Place this donut on the $ 2 $ dimension plane coordinate $ (0,0) $ with the center of the donut so that the side of length H and the $ y $ axis are parallel.
On the ACPC $ 1 $ day you ate a donut that was in t... | ```python
def inpl(): return list(map(int, input().split()))
W, H, w, h, x, y = inpl()
a = (min(W//2 , x + w//2) + max(-W//2, x-w//2))
b = (min(H//2 , y + h//2) + max(-H//2, y-h//2))
print(b/a)
``` |
p02282 Reconstruction of a Tree | Write a program which reads two sequences of nodes obtained by the preorder tree walk and the inorder tree walk on a binary tree respectively, and prints a sequence of the nodes obtained by the postorder tree walk on the binary tree.
Constraints
* $1 \leq n \leq 40$
Input
In the first line, an integer $n$, which is... | ```python
class BinaryTree:
class Node:
def __init__(self, nid, left, right):
self.id = nid
self.left = left
self.right = right
def has_left(self):
return self.left is not None
def has_right(self):
return self.right is not None
... |
p02429 Enumeration of Subsets III | You are given a set $T$, which is a subset of $S$. The set $S$ consists of $0, 1, ... n-1$. Print all subsets of $T$. Note that we represent $0, 1, ... n-1$ as 00...0001, 00...0010, 00...0100, ..., 10...0000 in binary respectively and the integer representation of a subset is calculated by bitwise OR of existing elemen... | ```python
n=int(input())
ind='0'+str(n)+'b'
t=list(map(int,input().split()))
k=t[0]
t.pop(0)
T=t
T.reverse()
ind='0'+str(k)+'b'
for i in range(2**k):
compare=[int(j) for j in format(i,ind)]
disp=[T[j] for j in range(k) if compare[j]==1]
disp.reverse()
if len(disp)==0:
print("0:")
else:
... |
1023_B. Pair of Toys | Tanechka is shopping in the toy shop. There are exactly n toys in the shop for sale, the cost of the i-th toy is i burles. She wants to choose two toys in such a way that their total cost is k burles. How many ways to do that does she have?
Each toy appears in the shop exactly once. Pairs (a, b) and (b, a) are conside... | ```python
n,k = [int(x) for x in input().split()]
if k>n:
if k>=2*n:
print(0)
else:
print((2*n-k+1)//2)
else:
if k%2==0:
k-=1
print(k//2)
``` |
1044_C. Optimal Polygon Perimeter | You are given n points on the plane. The polygon formed from all the n points is strictly convex, that is, the polygon is convex, and there are no three collinear points (i.e. lying in the same straight line). The points are numbered from 1 to n, in clockwise order.
We define the distance between two points p_1 = (x_1... | ```python
n = int(input())
north = -100000000
south = 100000000
east = -100000000
west = 100000000
ne = -200000000
nw = -200000000
se = -200000000
sw = -200000000
for i in range(n):
x,y = map(int,input().split())
north = max(north,y)
east = max(east,x)
south = min(south,y)
west = min(west,x)
ne ... |
1067_B. Multihedgehog | Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as fol... | ```python
from sys import stdin
from collections import deque
n, k = map(int, stdin.readline().split())
graph = [[] for _ in range(n)]
leaf = -1
for _ in range(n-1):
a,b = map(int,stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
def bfs(G, s):
# la cola comienza con e... |
1089_L. Lazyland | The kingdom of Lazyland is the home to n idlers. These idlers are incredibly lazy and create many problems to their ruler, the mighty King of Lazyland.
Today k important jobs for the kingdom (k ≤ n) should be performed. Every job should be done by one person and every person can do at most one job. The King allowed e... | ```python
n,k = map(int,input().split())
s = list(map(int,input().split()))
p = list(map(int,input().split()))
r = {}
r2 = []
for i in range(n):
if s[i] in r:
if r[s[i]]>p[i]:
r2.append(p[i])
else:
r2.append(r[s[i]])
r[s[i]] = p[i]
else:
r[s[i]] = p[i]... |
1108_E2. Array and Segments (Hard version) | The only difference between easy and hard versions is a number of elements in the array.
You are given an array a consisting of n integers. The value of the i-th element of the array is a_i.
You are also given a set of m segments. The j-th segment is [l_j; r_j], where 1 ≤ l_j ≤ r_j ≤ n.
You can choose some subset of... | ```python
def main():
n, m = map(int, input().split())
aa = list(map(int, input().split()))
res = max(aa) - min(aa)
ll, rr = [n + 1], [n + 1]
segments = res_segments = [False] * (m + 1)
bounds = {0, n, n + 1}
for _ in range(m):
l, r = map(int, input().split())
l -= 1
... |
1138_B. Circus | Polycarp is a head of a circus troupe. There are n — an even number — artists in the troupe. It is known whether the i-th artist can perform as a clown (if yes, then c_i = 1, otherwise c_i = 0), and whether they can perform as an acrobat (if yes, then a_i = 1, otherwise a_i = 0).
Split the artists into two performance... | ```python
import sys
import random
N = int(input())
C = list(map(int, input()))
A = list(map(int, input()))
# N = random.randint(20, 40) * 2
# C = [random.randint(0, 1) for i in range(N)]
# A = [random.randint(0, 1) for i in range(N)]
def build_solution(i, j, x, y):
I = (0, 0)
J = (0, 1)
X = (1, 0)
Y = (1, 1)
a... |
1156_D. 0-1-Tree | You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path fro... | ```python
import sys
input = sys.stdin.readline
class UnionFind:
def __init__(self, n):
self.parent = [-1] * n
self.cnt = n
def root(self, x):
if self.parent[x] < 0:
return x
else:
self.parent[x] = self.root(self.parent[x])
return self.paren... |
1196_F. K-th Path | You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where ... | ```python
import sys
input = sys.stdin.readline
N, M, K = map(int, input().split())
X = []
for _ in range(M):
x, y, w = map(int, input().split())
X.append([min(x,y), max(x,y), w])
X = (sorted(X, key = lambda x: x[2])+[[0, 0, 10**20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x: D[x*10**6+y] = w
fl... |
1214_A. Optimal Currency Exchange | Andrew was very excited to participate in Olympiad of Metropolises. Days flew by quickly, and Andrew is already at the airport, ready to go home. He has n rubles left, and would like to exchange them to euro and dollar bills. Andrew can mix dollar bills and euro bills in whatever way he wants. The price of one dollar i... | ```python
n=int(input())
d=int(input())
e=int(input())
arr=100
a,b=min(d,5*e),max(d,5*e)
for i in range(0,n//b+1):
arr=min(arr,(n-i*b)%a)
print(arr)
``` |
1237_C2. Balanced Removals (Harder) | This is a harder version of the problem. In this version, n ≤ 50 000.
There are n distinct points in three-dimensional space numbered from 1 to n. The i-th point has coordinates (x_i, y_i, z_i). The number of points n is even.
You'd like to remove all n points using a sequence of n/2 snaps. In one snap, you can remov... | ```python
def solve_z(points):
cur = None
d = {}
for p in points:
if p[0] not in d:
d[p[0]] = []
d[p[0]].append(p)
for k in d:
d[k] = sorted(d[k], key = lambda x: x[1])
for k in sorted(d.keys()):
n = len(d[k])
for ... |
1255_C. League of Leesins | Bob is an avid fan of the video game "League of Leesins", and today he celebrates as the League of Leesins World Championship comes to an end!
The tournament consisted of n (n ≥ 5) teams around the world. Before the tournament starts, Bob has made a prediction of the rankings of each team, from 1-st to n-th. After th... | ```python
def zip_sorted(a,b):
# sorted by a
a,b = zip(*sorted(zip(a,b)))
# sorted by b
sorted(zip(a, b), key=lambda x: x[1])
return a,b
def return_nxt(i,a,b):
visited.add(i)
c = (set(mem2[i])-set([a,b])).pop()
final.append(c)
if len(final)==n:
return -1,b,c
new_idx = ((set(mem1[b])-visited)&(se... |
1279_B. Verse For Santa | New Year is coming! Vasya has prepared a New Year's verse and wants to recite it in front of Santa Claus.
Vasya's verse contains n parts. It takes a_i seconds to recite the i-th part. Vasya can't change the order of parts in the verse: firstly he recites the part which takes a_1 seconds, secondly — the part which take... | ```python
import sys
input = sys.stdin.readline
t = int(input())
while t > 0:
n, s = map(int, input().split())
a = list(map(int, input().split()))
ans = 0
for i in range(n):
if a[ans] < a[i]:
ans = i
s -= a[i]
if (s < 0): break
if s >= 0:
ans = -1
... |
1322_C. Instant Noodles | Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left ha... | ```python
from sys import stdin
from math import gcd
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
values = list(map(int, input().split()))
neigh_values = [0]*n
y_neigh = [[] for i in range(n)]
di = [[] for i in rang... |
1341_B. Nastya and Door | On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k ≥ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains.
Mountains are described by a sequence of heights... | ```python
from sys import stdin, stdout
def find(A,N,K):
arr=[0]*N
for i in range(1,N-1):
if A[i-1]<A[i]>A[i+1]: arr[i]=1
i,j=0,2
c=0
# print(arr)
while(j<K):
if arr[j-1]: c+=1
# print(j,c)
j+=1
m=[c,i]
# print(c,i,j)
while(j<N):
if arr[i+1]:... |
1363_B. Subsequence Hate | Shubham has a binary string s. A binary string is a string containing only characters "0" and "1".
He can perform the following operation on the string any amount of times:
* Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa.
... | ```python
for t in range(int(input())):
s=input()
one=s.count("1")
z=s.count("0")
if one==0 or z==0:
print(0)
else:
cost=one
mi=10**9
for i in s:
if i=="0":
cost+=1
else:
cost-=1
if mi>cost:
... |
1404_D. Game of Pairs | This is an interactive problem.
Consider a fixed positive integer n. Two players, First and Second play a game as follows:
1. First considers the 2n numbers 1, 2, ..., 2n, and partitions them as he wants into n disjoint pairs.
2. Then, Second chooses exactly one element from each of the pairs that First created (... | ```python
import sys
n = int(input())
if n % 2:
print('Second')
sys.stdout.flush()
l = list(map(lambda x: int(x)-1,input().split()))
rev1 = [-1]*n
rev2 = [-1]*n
revs = [0]*n
for i in range(2 * n):
revs[l[i]] += i
if rev1[l[i]] == -1:
rev1[l[i]] = i
else:
... |
1426_A. Floor Number | Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | ```python
from functools import reduce
import os
import sys
from collections import *
#from fractions import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value(): return tuple(map(int, input().split())) # multiple va... |
1472_G. Moving to the Capital | There are n cities in Berland. The city numbered 1 is the capital. Some pairs of cities are connected by a one-way road of length 1.
Before the trip, Polycarp for each city found out the value of d_i — the shortest distance from the capital (the 1-st city) to the i-th city.
Polycarp begins his journey in the city wit... | ```python
import sys
from sys import stdin
from collections import deque
def NC_Dij(lis,start):
ret = [float("inf")] * len(lis)
ret[start] = 0
q = deque([start])
plis = [i for i in range(len(lis))]
while len(q) > 0:
now = q.popleft()
for nex in lis[now]:
if ret[... |
1499_B. Binary Removals | You are given a string s, consisting only of characters '0' or '1'. Let |s| be the length of s.
You are asked to choose some integer k (k > 0) and find a sequence a of length k such that:
* 1 ≤ a_1 < a_2 < ... < a_k ≤ |s|;
* a_{i-1} + 1 < a_i for all i from 2 to k.
The characters at positions a_1, a_2, ...,... | ```python
for q in range(int(input())):
n=input()
s=0
s1=0
p=0
l=len(n)
for i in range(l-1,0,-1):
if(n[i]=='0' and n[i-1]=='0' ):
s=1
p=i-1
break
for i in range(p,0,-1):
if(n[i]=='1' and n[i-1]=='1'):
s1=1
break
... |
1520_G. To Go Or Not To Go? | Dima overslept the alarm clock, which was supposed to raise him to school.
Dima wonders if he will have time to come to the first lesson. To do this, he needs to know the minimum time it will take him to get from home to school.
The city where Dima lives is a rectangular field of n × m size. Each cell (i, j) on this ... | ```python
#!/usr/bin/env python3
import io
import os
from collections import deque
# input = sys.stdin.readline # to read input quickly
from math import inf
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# available on Google, AtCoder Python3, not available on Codeforces
# import numpy as np
# import sc... |
176_C. Playing with Superglue | Two players play a game. The game is played on a rectangular board with n × m squares. At the beginning of the game two different squares of the board have two chips. The first player's goal is to shift the chips to the same square. The second player aims to stop the first one with a tube of superglue.
We'll describe ... | ```python
n,m,X,Y,x,y=map(int,input().split())
a=[abs(X-x),abs(Y-y)]
a.sort()
print("First" if a[1]<5 and a[0]+a[1]<7 else "Second")
# Made By Mostafa_Khaled
``` |
220_A. Little Elephant and Problem | The Little Elephant has got a problem — somebody has been touching his sorted by non-decreasing array a of length n and possibly swapped some elements of the array.
The Little Elephant doesn't want to call the police until he understands if he could have accidentally changed the array himself. He thinks that he could ... | ```python
def main():
n = int(input())
arr = list(map(int, input().split()))
copy = arr[:]
copy.sort()
missed = 0
for i in range(n):
if arr[i] != copy[i]:
missed += 1
if missed == 2:
print('YES')
elif missed == 0:
print('YES')
else:
pri... |
244_B. Undoubtedly Lucky Numbers | Polycarpus loves lucky numbers. Everybody knows that lucky numbers are positive integers, whose decimal representation (without leading zeroes) contain only the lucky digits x and y. For example, if x = 4, and y = 7, then numbers 47, 744, 4 are lucky.
Let's call a positive integer a undoubtedly lucky, if there are suc... | ```python
def func(num):
if 0 < num <= n:
result.add(num)
num *= 10
func(num+x)
func(num+y)
if __name__ == "__main__":
n = int(input())
result = set()
for x in range(10):
for y in range(10):
func(x)
print(len(result))
... |
292_B. Network Topology | This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution.
Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them a... | ```python
n,m=map(int,input().split())
arr=[0]*(n+1)
for w in range(m):
a,b=map(int,input().split())
arr[a]+=1
arr[b]+=1
c1=0
c2=0
cs=0
for i in range(1,n+1):
if arr[i]==1:
c1+=1
if arr[i]==2:
c2+=1
if arr[i]==n-1:
cs+=1
if c1==2 and c2==n-2:
print("bus topology")
eli... |
363_B. Fence | There is a fence in front of Polycarpus's home. The fence consists of n planks of the same width which go one after another from left to right. The height of the i-th plank is hi meters, distinct planks can have distinct heights.
<image> Fence for n = 7 and h = [1, 2, 6, 1, 1, 7, 1]
Polycarpus has bought a posh piano... | ```python
n,k=map(int,input().split())
A = list(map(int,input().split()))
B = [0]
for i in range(k):
B[0]+=A[i]
for i in range(1,n-k+1):
B.append(B[i-1]-A[i-1]+A[i+k-1])
print(B.index(min(B))+1)
``` |
387_A. George and Sleep | George woke up and saw the current time s on the digital clock. Besides, George knows that he has slept for time t.
Help George! Write a program that will, given time s and t, determine the time p when George went to bed. Note that George could have gone to bed yesterday relatively to the current time (see the second... | ```python
def tmins():
sh, sm = map(int, input().split(':'))
return 60 * sh + sm
t = tmins() - tmins()
if t < 0:
t += 60*24
print('%02d:%02d' % (t//60, t%60))
``` |
457_B. Distributed Join | Piegirl was asked to implement two table join operation for distributed database system, minimizing the network traffic.
Suppose she wants to join two tables, A and B. Each of them has certain number of rows which are distributed on different number of partitions. Table A is distributed on the first cluster consisting... | ```python
n, m = list(map(int, input().split()))
A = list(map(int, input().split()))
B = list(map(int, input().split()))
A.sort(reverse=True)
B.sort(reverse=True)
sumA = sum(A)
sumB = sum(B)
ansA = sumB
ansB = sumA
for i in range(1, n):
ansA += min(A[i],sumB)
for i in range(1, m):
ansB += min(B[i], sumA)
print... |
479_E. Riding in a Lift | Imagine that you are in a building that has exactly n floors. You can move between the floors in a lift. Let's number the floors from bottom to top with integers from 1 to n. Now you're on the floor number a. You are very bored, so you want to take the lift. Floor number b has a secret lab, the entry is forbidden. Howe... | ```python
def solve(n, st, k):
MOD = int(1e9 + 7)
prev = [0] * (n + 1)
current = [0] * (n + 1)
prefix_sum = [0] * (n + 1)
prev[st] = 1
for times in range(k):
prefix_sum[0] = 0
for i in range(1, n + 1):
prefix_sum[i] = prefix_sum[i - 1] + prev[i]
if prefix_... |
527_C. Glass Carving | Leonid wants to become a glass carver (the person who creates beautiful artworks by cutting the glass). He already has a rectangular w mm × h mm sheet of glass, a diamond glass cutter and lots of enthusiasm. What he lacks is understanding of what to carve and how.
In order not to waste time, he decided to practice t... | ```python
w,h,n=map(int,input().split())
l=[-1]*(w+1)
r=[-1]*(w+1)
t=[-1]*(h+1)
b=[-1]*(h+1)
l[0]=0
b[0]=0
t[h]=h
r[w]=w
V=[0]*(n)
H=[0]*(n)
for i in range(n):
line,index=input().split()
index=int(index)
if line=="V":
r[index]=w
V[i]=index
else:
t[index]=h
H[i]=index
... |
553_A. Kyoya and Colored Balls | Kyoya Ootori has a bag with n colored balls that are colored with k different colors. The colors are labeled from 1 to k. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color i before drawing the last ball of color i... | ```python
#!/usr/bin/python3
import sys
from functools import lru_cache
MOD = 1000000007
cnk = [[1 for i in range(1001)] for j in range(1001)]
for i in range(1, 1001):
for j in range(1, i):
cnk[i][j] = cnk[i - 1][j - 1] + cnk[i - 1][j]
k = int(input())
cs = [int(input()) for i in range(k)]
ans = 1
sm ... |
579_F. LCS Again | You are given a string S of length n with each character being one of the first m lowercase English letters.
Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1.
Recall that LCS ... | ```python
def main():
n, m = map(int, input().split())
s = input()
k = sum(s[i] != s[i - 1] for i in range(1, n)) + 1
x = i = 0
while i < n - 1:
if s[i] != s[i + 1]:
j = i
while i + 2 < n and s[i] == s[i + 2]:
i += 1
j = (i - j) + 2
... |
600_E. Lomsat gelral | You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree... | ```python
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[... |
645_A. Amity Assessment | Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the em... | ```python
def read_ints():
return [int(x) for x in input(' ').split()]
def evaluate(top, bot):
res = 1 if 'X' in top else 2
perm = top + bot
perm = [x for x in perm if x != 'X']
for i in range(len(perm)):
for j in range(i+1, len(perm)):
if perm[i] > perm[j]:
res... |
697_A. Pineapple Incident | Ted has a pineapple. This pineapple is able to bark like a bulldog! At time t (in seconds) it barks for the first time. Then every s seconds after it, it barks twice with 1 second interval. Thus it barks at times t, t + s, t + s + 1, t + 2s, t + 2s + 1, etc.
<image>
Barney woke up in the morning and wants to eat the ... | ```python
t,s,x=(int(z) for z in input().split())
x-=t
if x>=0 and x%s in [0,1] and x!=1:
print("YES")
else:
print("NO")
``` |
762_C. Two strings | You are given two strings a and b. You have to remove the minimum possible number of consecutive (standing one after another) characters from string b in such a way that it becomes a subsequence of string a. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of th... | ```python
from sys import stdin
def main():
t = stdin.readline()
s = stdin.readline()
n = len(s) - 1
m = len(t) - 1
post = [-1] * n
ss = n - 1
st = m - 1
while st >= 0 and ss >= 0:
if t[st] == s[ss]:
post[ss] = st
ss -= 1
st -= 1
pre = [-1] *... |
785_D. Anton and School - 2 | As you probably know, Anton goes to school. One of the school subjects that Anton studies is Bracketology. On the Bracketology lessons students usually learn different sequences that consist of round brackets (characters "(" and ")" (without quotes)).
On the last lesson Anton learned about the regular simple bracket s... | ```python
mod = 10 ** 9 + 7
fact, inv, invfact = [1, 1], [0, 1], [1, 1]
for i in range(2, 200200):
fact.append(fact[-1] * i % mod)
inv.append(inv[mod % i] * (mod - mod // i) % mod)
invfact.append(invfact[-1] * inv[-1] % mod)
def C(n, k):
if k < 0 or k > n:
return 0
return fact[n] * invfact... |
807_D. Dynamic Problem Scoring | Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.
For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends... | ```python
import sys
inf = 10**9 + 7
def solve():
n = int(sys.stdin.readline())
v = [int(vi) for vi in sys.stdin.readline().split()] # Vesya
p = [int(pi) for pi in sys.stdin.readline().split()] # Petya
cnt = [0]*5
for i in range(5):
if v[i] != -1:
cnt[i] += 1
if p[i]... |
831_E. Cards Sorting | Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on... | ```python
# -*- coding: utf-8 -*-
import sys
# fout = open("output.txt", "w")
fin = sys.stdin
# fin = open("input.txt", "r")
fout = sys.stdout
n = int(fin.readline())
a = list(map(int, fin.readline().split()))
def solution(n, a):
sorted_arr = [(i, elem) for i, elem in enumerate(a)]
sorted_arr.sort(key=lamb... |
877_A. Alex and broken contest | One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems.
But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ... | ```python
judul = input()
nama = ["Danil", "Olya", "Slava", "Ann", "Nikita"]
cek = 0
ada = []
for i in range(0, 5):
ada.append(judul.count(nama[i]))
cek = cek + ada[i]
if cek == 1:
print("YES")
else:
print("NO")
``` |
900_B. Position in Fraction | You have a fraction <image>. You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.
Input
The first contains three single positive integers a, b, c (1 ≤ a < b ≤ 105, 0 ≤ c ≤ 9).
Output
Print position of the first occurrence of digit c into the fraction. Positions... | ```python
a,b,c = map(int, input().split())
t = a
q, r = divmod(t, b)
for i in range(1, 10**5+1):
q, r = divmod(r*10, b)
#print(q)
if q == c:
print(i)
exit()
else:
print(-1)
``` |
950_B. Intercepted Message | Hacker Zhorik wants to decipher two secret messages he intercepted yesterday. Yeah message is a sequence of encrypted blocks, each of them consists of several bytes of information.
Zhorik knows that each of the messages is an archive containing one or more files. Zhorik knows how each of these archives was transferred... | ```python
n,m=map(int,input().split())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
i=0
j=0
s1=0
s2=0
count=1
while i<n and j<m:
if s1==s2 and s1>0:
count+=1
s1=0
s2=0
elif s1>s2 or s2==0:
s2+=y[j]
j+=1
elif s1<s2 or s1==0:
s1+=x[i]
... |
978_E. Bus Video System | The busses in Berland are equipped with a video surveillance system. The system records information about changes in the number of passengers in a bus after stops.
If x is the number of passengers in a bus just before the current bus stop and y is the number of passengers in the bus just after current bus stop, the sy... | ```python
l=input().split()
n=int(l[0])
w=int(l[1])
l=input().split()
li=[int(i) for i in l]
left=0
right=w
sumi=0
for i in range(n):
sumi+=li[i]
left=max(left,-1*sumi)
right=min(right,w-sumi)
print(max(right-left+1,0))
``` |
998_D. Roman Digits | Let's introduce a number system which is based on a roman digits. There are digits I, V, X, L which correspond to the numbers 1, 5, 10 and 50 respectively. The use of other roman digits is not allowed.
Numbers in this system are written as a sequence of one or more digits. We define the value of the sequence simply as... | ```python
a = [0, 4, 10, 20, 35, 56, 83, 116, 155, 198, 244, 292]
n = int(input())
if n < len(a):
print (a[n])
else:
print (a[11] + 49*(n-11))
``` |
p02661 AtCoder Beginner Contest 169 - Count Median | There are N integers X_1, X_2, \cdots, X_N, and we know that A_i \leq X_i \leq B_i. Find the number of different values that the median of X_1, X_2, \cdots, X_N can take.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq A_i \leq B_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard ... | ```python
N = int(input())
A = [0]*N
B = [0]*N
for i in range(N):
A[i],B[i] = map(int, input().split())
A.sort()
B.sort()
if len(A)%2 != 0:
ans = B[N//2]-A[N//2]+1
else:
ans = (B[N//2]+B[N//2-1]) - (A[N//2]+A[N//2-1]) + 1
print(ans)
``` |
p02790 AtCoder Beginner Contest 152 - Comparing Strings | Given are 1-digit positive integers a and b. Consider these two strings: the concatenation of b copies of the digit a, and the concatenation of a copies of the digit b. Which of these is lexicographically smaller?
Constraints
* 1 \leq a \leq 9
* 1 \leq b \leq 9
* a and b are integers.
Input
Input is given from Stan... | ```python
N = list(map(int, input().split()))
a = N.sort()
print(str(N[0])*N[1])
``` |
p02926 AtCoder Beginner Contest 139 - Engines | E869120 is initially standing at the origin (0, 0) in a two-dimensional plane.
He has N engines, which can be used as follows:
* When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the ... | ```python
n = int(input())
pi = 3.141592653589793238462643383279
xy = [list(map(int, input().split())) for _ in range(n)]
import math
atan = [math.atan2(x[0], x[1]) for x in xy]
d = []
def hoge(a):
ret = 0
if a % (2*pi) < pi:
ret = (a % pi)
elif a % (2*pi) > pi:
ret = (a % pi)-pi
els... |
p03061 AtCoder Beginner Contest 125 - GCD on Blackboard | There are N integers, A_1, A_2, ..., A_N, written on the blackboard.
You will choose one of them and replace it with an integer of your choice between 1 and 10^9 (inclusive), possibly the same as the integer originally written.
Find the maximum possible greatest common divisor of the N integers on the blackboard afte... | ```python
from fractions import gcd
n=int(input())
a=list(map(int,input().split()))
l=[0]*(n+1)
r=[0]*(n+1)
for i in range(n):
l[i+1]=gcd(l[i],a[i])
for i in range(n-1,-1,-1):
r[i]=gcd(r[i+1],a[i])
ans=l[-1]
for i in range(n):
ans=max(ans,gcd(l[i],r[i+1]))
print(ans)
``` |
p03352 AtCoder Beginner Contest 097 - Exponential | You are given a positive integer X. Find the largest perfect power that is at most X. Here, a perfect power is an integer that can be represented as b^p, where b is an integer not less than 1 and p is an integer not less than 2.
Constraints
* 1 ≤ X ≤ 1000
* X is an integer.
Input
Input is given from Standard Input ... | ```python
x=int(input())
l=[]
for b in range (1,32):
for i in range (2,10):
if b**i <=x:
l.append (b**i)
print(max(l))
``` |
p03512 Code Festival Team Relay (Parallel) - Akashic Records | Consider an infinite sequence a_1, a_2, … Initially, the values of all the terms are 0, and from this state we will sequentially perform Q operations. The i-th operation (1 ≤ i ≤ Q) is as follows:
* For every positive integer j, add x_i to the value of a_{j × m_i}.
Find the value of the largest term after these Q o... | ```python
from itertools import product
Q = int(input())
mxs = [tuple(map(int, input().split())) for _ in range(Q)]
p1s = [2,3,5,7,11,13,17]
nums = [9,6,4,3,3,3,3]
rangeNums = [range(num) for num in nums]
p2s = [19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,... |
p03674 AtCoder Beginner Contest 066 - 11 | You are given an integer sequence of length n+1, a_1,a_2,...,a_{n+1}, which consists of the n integers 1,...,n. It is known that each of the n integers 1,...,n appears at least once in this sequence.
For each integer k=1,...,n+1, find the number of the different subsequences (not necessarily contiguous) of the given s... | ```python
# ------ combination -------
N, MOD = 10**5 + 1, 10**9 + 7
fc, ifc = [0] * (N+1), [0] * (N+1)
def power(n, a):
res, exp = 1, n
while(a):
if a & 1:
res = res * exp % MOD
exp = exp * exp % MOD
a = a >> 1
return res
fc[0] = 1
for i in range(1, N+1):
fc[i] = f... |
p03828 AtCoder Beginner Contest 052 - Factors of Factorial | You are given an integer N. Find the number of the positive divisors of N!, modulo 10^9+7.
Constraints
* 1≤N≤10^3
Input
The input is given from Standard Input in the following format:
N
Output
Print the number of the positive divisors of N!, modulo 10^9+7.
Examples
Input
3
Output
4
Input
6
Output
3... | ```python
n = int(input())
multiplier = [0 for _ in range(n)]
for m in range(2, n+1):
a = m
i = 2
while i ** 2 <= m:
while a % i == 0:
a = int(a / i)
multiplier[i-1] += 1
i += 1
if a != 1:
multiplier[a-1] += 1
ans = 1
for x in multiplier:
ans *= x + 1... |
p03995 CODE FESTIVAL 2016 qual A - Grid and Integers | There is a grid with R rows and C columns. We call the cell in the r-th row and c-th column (r,c).
Mr. Takahashi wrote non-negative integers into N of the cells, that is, he wrote a non-negative integer a_i into (r_i,c_i) for each i (1≤i≤N). After that he fell asleep.
Mr. Aoki found the grid and tries to surprise Mr.... | ```python
import sys
readline = sys.stdin.readline
class UFP():
def __init__(self, num):
self.par = [-1]*num
self.dist = [0]*num
def find(self, x):
if self.par[x] < 0:
return x
else:
res = 0
xo = x
while self.par[x] >= 0:
... |
p00083 Era Name Transformation | Create a program that converts the date expressed in the Christian era to the Japanese calendar using the era name and outputs the date. The input is three integers, as shown in the example, in the order year, month, and day. Convert this as shown in the sample output. If the date before the Meiji era is entered, pleas... | ```python
from bisect import bisect_left
import sys
name = ["pre-meiji", "meiji", "taisho", "showa", "heisei"]
period = [(1868,9,7), (1912,7,29), (1926,12,24), (1989,1,7)]
for t in (tuple(map(int, l.split())) for l in sys.stdin):
index = bisect_left(period, t)
if index:
date = "{} {} {}".format(t[0]-p... |
p00215 Pachimon Creature | A popular game in a certain country, Pachimon Creature, has been remade and released in Japan. If you love games, after playing this game many times, you've come to think about how you can clear it the fastest. However, no matter how much you think about it, you didn't know the fastest way to capture it, so you decided... | ```python
from heapq import heappop,heappush
# from line_profiler import LineProfiler
def main():
while(True):
W, H = map(int,input().split())
if not W: break
B = float('inf')
Bi = -1
consequNodes = []
monsterNodes = [[] for _ in range(5)]
idx = 0
for ... |
p00375 Celsius and Fahrenheit | In Japan, temperature is usually expressed using the Celsius (℃) scale. In America, they used the Fahrenheit (℉) scale instead. $20$ degrees Celsius is roughly equal to $68$ degrees Fahrenheit. A phrase such as "Today’s temperature is $68$ degrees" is commonly encountered while you are in America.
A value in Fahrenhei... | ```python
x=input()
x=int(x)
y=(x-30)//2
print(y)
``` |
p00593 JPEG Compression | The fundamental idea in the JPEG compression algorithm is to sort coeffi- cient of given image by zigzag path and encode it. In this problem, we don’t discuss about details of the algorithm, but you are asked to make simple pro- gram. You are given single integer N , and you must output zigzag path on a matrix where si... | ```python
t = 1
while 1:
N = int(input())
if N == 0:
break
print("Case %d:" % t); t += 1
M = [[0]*N for i in range(N)]
c = 1
for i in range(2*N-1):
for j in range(max(i-N+1, 0), min(N, i+1)):
if i % 2 == 0:
M[i-j][j] = "%3d" % c
else:
... |
p00729 Analyzing Login/Logout Records | You have a computer literacy course in your university. In the computer system, the login/logout records of all PCs in a day are stored in a file. Although students may use two or more PCs at a time, no one can log in to a PC which has been logged in by someone who has not logged out of that PC yet.
You are asked to w... | ```python
def main(N, M):
member = [[0] * 721 for i in range(M)]
r = int(input())
for _ in range(r):
t, _, m, s = map(int, input().split())
t -= 540
if s == 0:
member[m - 1][t] -= 1
else:
member[m - 1][t] += 1
for i in range(M):
for t in ra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.