name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1476_C. Longest Simple Cycle | You have n chains, the i-th chain consists of c_i vertices. Vertices in each chain are numbered independently from 1 to c_i along the chain. In other words, the i-th chain is the undirected graph with c_i vertices and (c_i - 1) edges connecting the j-th and the (j + 1)-th vertices for each 1 ≤ j < c_i.
Now you decided... | ```python
import math,sys,bisect,heapq,os
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
def input(): return sys.stdin.readline().rstrip('\r\n')
#input = iter(sys.stdin.buffer.read()... |
1501_B. Napoleon Cake | This week Arkady wanted to cook some pancakes (to follow ancient traditions) and make a problem about that. But then he remembered that one can't make a problem about stacking pancakes without working at a specific IT company, so he decided to bake the Napoleon cake instead.
To bake a Napoleon cake, one has to bake n ... | ```python
def get_layers_status(aa):
n = len(aa)
intervals = []
for i in range(n):
if aa[i] > 0:
intervals.append([max(0, i + 1 - aa[i]), i + 1])
endpoints = [(s, 0) for s, e in intervals] + [(e, 1) for s, e in intervals]
endpoints.sort(key = lambda x: x[0] - 0.1 * x[1])
#p... |
1526_D. Kill Anton | After rejecting 10^{100} data structure problems, Errorgorn is very angry at Anton and decided to kill him.
Anton's DNA can be represented as a string a which only contains the characters "ANTON" (there are only 4 distinct characters).
Errorgorn can change Anton's DNA into string b which must be a permutation of a. ... | ```python
from collections import defaultdict
import itertools
import sys
input = sys.stdin.readline
t = int(input())
p = list("ANOT")
q = [0, 1, 2, 3]
d = dict()
for i in range(4):
d[p[i]] = i
for _ in range(t):
a = list(input().rstrip())
n = len(a)
cnt = [0] * 4
x = [[0] * 4 for _ in range(4)]
... |
158_B. Taxi | After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | ```python
n=int(input())
a=list(map(int,input().split()))
s=[0]*5
sum=0
for i in a: s[i]+=1
sum+=s[4]+s[3]
if s[3]<s[1]:
s[1]-=s[3]
s[3]=0
else :
s[3]=0
s[1]=0
sum+=s[2]//2
s[2]%=2
sum+=s[1]//4
s[1]%=4
end=s[2]*2+s[1]
if end>4:sum+=2
elif end>0: sum+=1
print(int(sum))
``` |
1_C. Ancient Berland Circus | Nowadays all circuses in Berland have a round arena with diameter 13 meters, but in the past things were different.
In Ancient Berland arenas in circuses were shaped as a regular (equiangular) polygon, the size and the number of angles could vary from one circus to another. In each corner of the arena there was a spec... | ```python
from math import *
def g(x,y):
if y<1e-3:
return x
else:
return g(y,fmod(x,y))
p=[list(map(float,input().split())) for i in range(3)]
a,b,c=[hypot(x1-x2,y1-y2) for (x1,y1),(x2,y2) in [(p[0],p[1]),(p[0],p[2]),(p[1],p[2])]]
A,B,C=[acos((y*y+z*z-x*x)/2/z/y) for x,y,z in [(a,b,c),(b,c,a),(... |
224_D. Two Strings | A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).
You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at... | ```python
import bisect
import string
s = input()
t = input()
max_match = [0 for i in range(len(s))]
min_match = [0 for i in range(len(s))]
char_idx = [0 for i in range(30)]
char_occur = [ [] for i in range(30) ]
for (i, ch) in enumerate(t):
idx = ord(ch) - ord('a')
char_occur[idx].append(i)
for ch in strin... |
249_B. Sweets for Everyone! | For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!"
Dr. Suess, How The Grinch Stole Christmas
Christmas celebrations are coming to Whoville. Cindy Lou Who and her paren... | ```python
def check(n, casas):
#print('n:',n)
global T,N,street
current = n
time = T
need = 0
last_house = 0
for ind, i in enumerate(street):
time -= 1
if i == 'S':
current += 1
elif i == 'H':
need += 1
i... |
296_E. Greg and Friends | One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe... | ```python
from collections import deque
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c50 = sum([1 for i in a if i == 50])
c100 = sum([1 for i in a if i == 100])
c = [[0] * 51 for i in range(51)]
c[0][0] = 1
c[1][0] = 1
c[1][1] = 1
for x in range(2, 51):
for y in range(x + 1):
... |
31_C. Schedule | At the beginning of the new semester there is new schedule in the Berland State University. According to this schedule, n groups have lessons at the room 31. For each group the starting time of the lesson and the finishing time of the lesson are known. It has turned out that it is impossible to hold all lessons, becaus... | ```python
from operator import add
import sys
from array import array # noqa: F401
from typing import TypeVar, Generic, Callable, List
T = TypeVar('T')
class SegmentTree(Generic[T]):
__slots__ = ["size", "tree", "identity", "op", "update_op"]
def __init__(self, size: int, identity: T, op: Callable[[T, T], T... |
344_C. Rational Resistance | Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co... | ```python
import sys
import string
import math
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
from fractions import Fraction
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def tmi(s):... |
390_A. Inna and Alarm Clock | Inna loves sleeping very much, so she needs n alarm clocks in total to wake up. Let's suppose that Inna's room is a 100 × 100 square with the lower left corner at point (0, 0) and with the upper right corner at point (100, 100). Then the alarm clocks are points with integer coordinates in this square.
The morning has ... | ```python
n = int(input())
x_set = set()
y_set = set()
for i in range(n):
x,y = map(int, input().split())
x_set.add(x)
y_set.add(y)
print(min(len(x_set), len(y_set)))
``` |
411_C. Kicker | Kicker (table football) is a board game based on football, in which players control the footballers' figures mounted on rods by using bars to get the ball into the opponent's goal. When playing two on two, one player of each team controls the goalkeeper and the full-backs (plays defence), the other player controls the ... | ```python
x = [tuple(int(i) for i in input().split()) for j in range(4)]
if x[0][0] + x[1][1] > x[0][1] + x[1][0]:
t1atk = x[1][1]
t1def = x[0][0]
else:
t1atk = x[0][1]
t1def = x[1][0]
def f():
if t1atk > t2def and t1def > t2atk:
return 0
elif t1atk < t2def and t1def < t2atk:
r... |
439_B. Devu, the Dumb Guy | Devu is a dumb guy, his learning curve is very slow. You are supposed to teach him n subjects, the ith subject has ci chapters. When you teach him, you are supposed to teach all the chapters of a subject continuously.
Let us say that his initial per chapter learning power of a subject is x hours. In other words he can... | ```python
n, x = map(int, input().split())
m = list(map(int, input().split()))
m.sort()
ans = 0
for i in range(n):
ans += m[i] * x
if x > 1:
x -= 1
print(ans)
``` |
460_D. Little Victor and Set | Little Victor adores the sets theory. Let us remind you that a set is a group of numbers where all numbers are pairwise distinct. Today Victor wants to find a set of integers S that has the following properties:
* for all x <image> the following inequality holds l ≤ x ≤ r;
* 1 ≤ |S| ≤ k;
* lets denote the i-th... | ```python
import random
l, r, k = map(int, input().split(' '))
if k == 1:
print(l)
print(1)
print(l)
quit()
if k == 2:
if r == l+1:
a = l
b = l^r
if a <= b:
print(a)
print(1)
print(l)
quit()
else:
print(b)
... |
508_C. Anya and Ghosts | Anya loves to watch horror movies. In the best traditions of horror, she will be visited by m ghosts tonight. Anya has lots of candles prepared for the visits, each candle can produce light for exactly t seconds. It takes the girl one second to light one candle. More formally, Anya can spend one second to light one can... | ```python
import sys
ghosts, duration, candles = input().split()
arrival = input().split()
burn = []
for j in range(len(arrival)):
time = int(arrival[len(arrival) - 1 - j])
candle = int(candles)
if len(burn) != 0:
for k in range(len(burn)):
if burn[k] <= time:
candle -= ... |
557_D. Vitaly and Cycle | After Vitaly was expelled from the university, he became interested in the graph theory.
Vitaly especially liked the cycles of an odd length in which each vertex occurs at most once.
Vitaly was wondering how to solve the following problem. You are given an undirected graph consisting of n vertices and m edges, not ne... | ```python
def connected_components(n, graph):
components, visited = [], [False] * n
def dfs(start):
component, stack = [], [start]
while stack:
start = stack[-1]
if visited[start]:
stack.pop()
continue
else:
v... |
583_B. Robot's Task | Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ... | ```python
n = int(input())
a = [int(x) for x in input().split()]
hacked = 0
pos = 0
changes = 0
right = True
while hacked < n:
if right:
r = range(pos, n)
else:
r = range(pos, -1, -1)
for i in r:
if a[i] <= hacked:
a[i] = n + 1
hacked += 1
pos = ... |
605_B. Lazy Student | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin... | ```python
n, m = (int(x) for x in input().split())
edges = []
for i in range(m):
w, in_tree = input().split()
edges.append([int(w), i, int(in_tree)])
sorted_edges = sorted(edges, key = lambda e: (e[0], -e[2]))
print
def free_edge():
for y in range(3, n+1):
for x in range(2, y):
yield [x,... |
627_C. Package Delivery | Johnny drives a truck and must deliver a package from his hometown to the district center. His hometown is located at point 0 on a number line, and the district center is located at the point d.
Johnny's truck has a gas tank that holds exactly n liters, and his tank is initially full. As he drives, the truck consumes ... | ```python
destination, max_gas_tank_volume, gas_prices_number = map(int, input().split())
start_point = 0
gas_prices = {start_point:0}
for i in range(gas_prices_number):
coordinate, price = map(int, input().split())
gas_prices[coordinate] = price
points = sorted(gas_prices.keys(), reverse = True)
current_point ... |
651_C. Watchmen | Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider... | ```python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def inc_val_of_dict(dictionary, key):
if key not in dictionary:
dictionary[key] = 0
dictionary[key] += 1
def main():
n = int(input())
p_ctr = dict()
x_ctr = dict()
y_ctr = dict()
for _ in range(n):
x, y = map(int, i... |
677_A. Vanya and Fence | Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | ```python
lin1 = input().split()
h = input().split()
for i in range(len(h)):
h[i] = int(h[i])
n_friends = int(lin1[0])
h_fence = int(lin1[1])
total = 0
for i in h:
if i > h_fence: total += 2
else: total += 1
print(total)
``` |
6_A. Triangle | Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo... | ```python
# https://codeforces.com/problemset/problem/6/A
import sys
#-----------------------------------------------------------------------------#
# # comment before submission
# sys.stdin = open('inputs.txt', 'r')
# sys.stdout = open('output.txt', 'w')
#--------------------------------------------------------------... |
721_C. Journey | Recently Irina arrived to one of the most famous cities of Berland — the Berlatov city. There are n showplaces in the city, numbered from 1 to n, and some of them are connected by one-directional roads. The roads in Berlatov are designed in a way such that there are no cyclic routes between showplaces.
Initially Irina... | ```python
n, m, T = map(int, input().split())
graph_a = [[] for _ in range(n+1)]
graph_b = [[] for _ in range(n+1)]
double_graph_a = [[0 for _ in range(n+1)] for _ in range(n+1)]
double_graph_b = [[0 for _ in range(n+1)] for _ in range(n+1)]
for i in range(m):
u, v, t = map(int, input().split())
graph_a[v].a... |
743_A. Vladik and flights | Vladik is a competitive programmer. This year he is going to win the International Olympiad in Informatics. But it is not as easy as it sounds: the question Vladik face now is to find the cheapest way to get to the olympiad.
Vladik knows n airports. All the airports are located on a straight line. Each airport has uni... | ```python
n, a, b = list(map(int, input().split()))
line = []
aa = input()
for i in range(n):
line += [int(aa[i])]
print(0 + (line[a-1] != line[b-1]))
``` |
766_C. Mahmoud and a Message | Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alpha... | ```python
N, s, l = int(input()), [ord(x) - ord('a') for x in input()], [int(x) for x in input().split()]
arr = [[1, l[s[0]]]]
total = 1
ma = 1
t = 1
mi = 1
for c in s[1:]:
tmp = 0
for i in range(len(arr)):
arr[i][1] = min(arr[i][1],l[c])
if i + 1 >= arr[i][1]:
arr = arr[:i]
if(t > i):
t = 0
mi += 1... |
78_B. Easter Eggs | The Easter Rabbit laid n eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
* Each of the seven colors should be used to paint at least one egg.
* Any four eggs lying ... | ```python
n = int(input())
s = 'ROYGBIV'
s1 = 'GBIV'
print(s, (n - 7) // 4 * s1, s1[:(n - 7) % 4], sep='')
``` |
837_A. Text Volume | You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
Input
The first line contains one integer number n ... | ```python
n = int(input())
text = input()
ll = list(text.split())
num = []
for i in range(len(ll)):
num.append(sum(1 for c in ll[i] if c.isupper()))
print(max(num))
``` |
906_C. Party | Arseny likes to organize parties and invite people to it. However, not only friends come to his parties, but friends of his friends, friends of friends of his friends and so on. That's why some of Arseny's guests can be unknown to him. He decided to fix this issue using the following procedure.
At each step he selects... | ```python
from collections import defaultdict
def count(x):
c=0
while x > 0:
c+=1
x &= (x-1)
return c
n,m=map(int,input().split())
g=defaultdict(list)
for _ in range(m):
u, v = map(int,input().split())
u-=1;v-=1
g[u].append(v)
g[v].append(u)
mask1=0;mask2=0;MAX=(1<<n)-1
a=[... |
926_E. Merge Equal Elements | You are given a sequence of positive integers a1, a2, ..., an.
While possible, you perform the following operation: find a pair of equal consecutive elements. If there are more than one such pair, find the leftmost (with the smallest indices of elements). If the two integers are equal to x, delete both and insert a s... | ```python
# https://codeforces.com/problemset/problem/926/E
input()
stack1 = [int(i) for i in input().split()]
stack1.reverse()
stack2 = []
while stack1:
transfer = stack1.pop()
while stack2 and stack2[-1] == transfer:
stack2.pop()
transfer += 1
stack2.append(transfer)
print(len(stack2... |
955_C. Sad powers | You're given Q queries of the form (L, R).
For each query you have to find the number of such x that L ≤ x ≤ R and there exist integer numbers a > 0, p > 1 such that x = ap.
Input
The first line contains the number of queries Q (1 ≤ Q ≤ 105).
The next Q lines contains two integers L, R each (1 ≤ L ≤ R ≤ 1018).
Ou... | ```python
import math
import bisect
import sys
def flrt(exp,x):
l=max(0,math.floor(x**(1/exp))-3)
r= math.floor(x**(1/exp))+3
while l<r:
mid=(l+r)//2
if mid**exp<=x:
l=mid+1
else:
r=mid
return l-1
def c1(r):
ans=set()
pr = [5,7,11, ... |
p02554 AtCoder Beginner Contest 178 - Ubiquity | How many integer sequences A_1,A_2,\ldots,A_N of length N satisfy all of the following conditions?
* 0 \leq A_i \leq 9
* There exists some i such that A_i=0 holds.
* There exists some i such that A_i=9 holds.
The answer can be very large, so output it modulo 10^9 + 7.
Constraints
* 1 \leq N \leq 10^6
* N is an in... | ```python
N = int(input())
ans = 10**N - 2*(9**N) + 8**N
print(ans % 1000000007)
``` |
p02685 AtCoder Beginner Contest 167 - Colorful Blocks | There are N blocks arranged in a row. Let us paint these blocks.
We will consider two ways to paint the blocks different if and only if there is a block painted in different colors in those two ways.
Find the number of ways to paint the blocks under the following conditions:
* For each block, use one of the M colors... | ```python
n,m,k=map(int,input().split())
mod=998244353
ans=0
fact=[1] * (n+1) # 階乗を格納するリスト
factinv=[1] * (n+1) # 階乗を格納するリスト
for i in range(n):
fact[i+1] = fact[i] * (i+1) % mod # 階乗を計算
factinv[i+1] = pow(fact[i+1], mod-2, mod) # modを法とした逆元(フェルマーの小定理)
def nCk(n,k): # 組み合わせ(mod)を返却する
return fact[n] * f... |
p02814 AtCoder Beginner Contest 150 - Semi Common Multiple | Given are a sequence A= {a_1,a_2,......a_N} of N positive even numbers, and an integer M.
Let a semi-common multiple of A be a positive integer X that satisfies the following condition for every k (1 \leq k \leq N):
* There exists a non-negative integer p such that X= a_k \times (p+0.5).
Find the number of semi-co... | ```python
import math
from functools import reduce
N,M=map(int,input().split())
A=[int(x)//2 for x in input().split()]
def lcm_base(x, y):
return (x * y) // math.gcd(x, y)
def lcm(*numbers):
return reduce(lcm_base, numbers, 1)
LCM=lcm(*A)
for a in A:
if LCM//a%2==0:
print(0)
break
else:
print((M... |
p02950 AtCoder Beginner Contest 137 - Polynomial Construction | Given are a prime number p and a sequence of p integers a_0, \ldots, a_{p-1} consisting of zeros and ones.
Find a polynomial of degree at most p-1, f(x) = b_{p-1} x^{p-1} + b_{p-2} x^{p-2} + \ldots + b_0, satisfying the following conditions:
* For each i (0 \leq i \leq p-1), b_i is an integer such that 0 \leq b_i \le... | ```python
p = int(input())
a = list(map(int,input().split()))
ans = [0]*p
for i in range(p):
if a[i] == 0:
continue
ans[0] -= p-1
m = 1
for k in range(p):
ans[p-1-k] -= m
ans[p-1-k] %= p
m *= i
m %= p
print(*ans)
``` |
p03086 AtCoder Beginner Contest 122 - ATCoder | You are given a string S consisting of uppercase English letters. Find the length of the longest ACGT string that is a substring (see Notes) of S.
Here, a ACGT string is a string that contains no characters other than `A`, `C`, `G` and `T`.
Constraints
* S is a string of length between 1 and 10 (inclusive).
* Each c... | ```python
import re
S=input()
ans = sorted((re.findall("[AGCT]*", S)), reverse=True, key=len)
print(len(ans[0]))
``` |
p03231 AtCoder Grand Contest 028 - Two Abbreviations | You are given a string S of length N and another string T of length M. These strings consist of lowercase English letters.
A string X is called a good string when the following conditions are all met:
* Let L be the length of X. L is divisible by both N and M.
* Concatenating the 1-st, (\frac{L}{N}+1)-th, (2 \times \... | ```python
gcd = lambda a,b: a if b==0 else gcd(b,a%b)
n,m = map(int,input().split())
s = input()
t = input()
d = gcd(n,m)
if s[::n//d]==t[::m//d]:
print(n*m//d)
else:
print(-1)
``` |
p03381 AtCoder Regular Contest 095 - Many Medians | When l is an odd number, the median of l numbers a_1, a_2, ..., a_l is the (\frac{l+1}{2})-th largest value among a_1, a_2, ..., a_l.
You are given N numbers X_1, X_2, ..., X_N, where N is an even number. For each i = 1, 2, ..., N, let the median of X_1, X_2, ..., X_N excluding X_i, that is, the median of X_1, X_2, ..... | ```python
N=int(input())
X=list(map(int,input().split()))
X_sort=sorted(X)
med_n=X_sort[N//2-1]
med_p=X_sort[N//2]
for i in range(N):
if X[i]<=med_n:
print(med_p)
else:
print(med_n)
``` |
p03546 AtCoder Beginner Contest 079 - Wall | Joisino the magical girl has decided to turn every single digit that exists on this world into 1.
Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).
She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and... | ```python
h,w = map(int,input().split())
c = [list(map(int,input().split())) for i in range(10)]
A = [list(map(int,input().split())) for i in range(h)]
for k in range(10):
for i in range(10):
for j in range(10):
c[i][j] = min(c[i][j],c[i][k]+c[k][j])
ans = 0
for i in range(h):
for j in A[i]... |
p03700 AtCoder Beginner Contest 063 - Widespread | You are going out for a walk, when you suddenly encounter N monsters. Each monster has a parameter called health, and the health of the i-th monster is h_i at the moment of encounter. A monster will vanish immediately when its health drops to 0 or below.
Fortunately, you are a skilled magician, capable of causing expl... | ```python
N, A, B = map(int, input().split())
H = [int(input()) for i in range(N)]
def f(x):
s = sum([- (- max(0, h - x * B) // (A - B)) for h in H])
if s <= x:
return True
else:
return False
l = 0
r = 10 ** 9 + 7
while r - l > 1:
m = (l + r) // 2
if f(m):
r = m
... |
p03857 AtCoder Regular Contest 065 - Connectivity | There are N cities. There are also K roads and L railways, extending between the cities. The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities. No two roads connect the same pair of cities. Similarly, no two railways connect the s... | ```python
N,K,L = list(map(int,input().split()))
e_list1 = [[] for i in range(N)]
e_list2 = [[] for i in range(N)]
for i in range(K):
p,q = list(map(int,input().split()))
e_list1[p-1].append(q-1)
e_list1[q-1].append(p-1)
for i in range(L):
p,q = list(map(int,input().split()))
e_list2[p-1].append(... |
p04022 AtCoder Grand Contest 003 - Anticube | Snuke got positive integers s_1,...,s_N from his mother, as a birthday present. There may be duplicate elements.
He will circle some of these N integers. Since he dislikes cubic numbers, he wants to ensure that if both s_i and s_j (i ≠ j) are circled, the product s_is_j is not cubic. For example, when s_1=1,s_2=1,s_3=... | ```python
def examA():
S = SI()
if "W" in S and not "E" in S:
print("No")
elif "E" in S and not "W" in S:
print("No")
elif "N" in S and not "S" in S:
print("No")
elif "S" in S and not "N" in S:
print("No")
else:
print("Yes")
return
def examB():
N ... |
p00106 Discounts of Buckwheat | Aizu is famous for its buckwheat. There are many people who make buckwheat noodles by themselves.
One day, you went shopping to buy buckwheat flour. You can visit three shops, A, B and C. The amount in a bag and its unit price for each shop is determined by the follows table. Note that it is discounted when you buy bu... | ```python
while 1:
try:
inp=int(input())
if inp==0:break
m_list=[]
for i in range(4):
for j in range(5):
for k in range(6):
for l in range(3):
for m in range(4):
for n in range(5):
... |
p00240 Interest Rates | Interest rates are attached to the money deposited in banks, and the calculation method and interest rates vary from bank to bank. The combination of interest and principal is called principal and interest, but as a method of calculating principal and interest, there are "single interest" that calculates without incorp... | ```python
def simple_interest(r, y):
return (100 + r * y) / 100
def compound_interest(r, y):
return ((100 + r) / 100) ** y
import sys
import operator
f = sys.stdin
get_ganri = {1:simple_interest,2:compound_interest}
while True:
n = int(f.readline())
if n == 0:
break
y = int(f.readline())
... |
p00412 Gas Station | Gas stations in the White Tiger service area have $ N $ lanes assigned numbers from $ 1 $ to $ N $. The first car in each lane can refuel.
Cars entering the gas station will choose the lane with the fewest cars in line and line up at the end of the line. If there are multiple such lanes, choose the one with the lowest... | ```python
N,M = [int(i) for i in input().split()]
table = [[] for i in range(N)]
for l in range(M):
command,num = [int(i) for i in input().split()]
if command == 0:
print(table[num-1].pop(0))
else:
minSize = 10000
minId = -1
for i in range(N):
if len(table[i]) ... |
p00616 Cubes Without Holes | There is a cube which consists of n × n × n small cubes. Small cubes have marks on their surfaces. An example where n = 4 is shown in the following figure.
<image>
Then, as shown in the figure above (right), make a hole that penetrates horizontally or vertically from the marked surface to the opposite surface.
You... | ```python
# AOJ 1030 Cubes Without Holes
# Python3 2018.7.6 bal4u
import sys
from sys import stdin
input = stdin.readline
# n <= 500, 2^9 = 512
while True:
n, h = map(int, input().split())
if n == 0: break
ans = []
for i in range(h):
c, a, b = input().split()
a, b = int(a)-1, int(b)-1
if c == "xy":
ans ... |
p00760 Millennium | A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one aft... | ```python
# AOJ 1179: Millennium
# Python3 2018.7.14 bal4u
for cno in range(int(input())):
y, m, d = map(int, input().split())
ans = 195*y
if y > 1: ans += 5*((y-1)//3)
if y % 3: ans += 19*(m-1) + m//2
else: ans += (m-1)*20
print(196666-ans-d)
``` |
p00892 Intersection of Two Prisms | Suppose that P1 is an infinite-height prism whose axis is parallel to the z-axis, and P2 is also an infinite-height prism whose axis is parallel to the y-axis. P1 is defined by the polygon C1 which is the cross section of P1 and the xy-plane, and P2 is also defined by the polygon C2 which is the cross section of P2 and... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
M, N = map(int, readline().split())
if M == N == 0:
return False
P = [list(map(int, readline().split())) for i in range(M)]
Q = [list(map(int, readline().split())) for i in range(N)]
xs = set()
xs.up... |
p01295 Champernowne Constant | Champernown constant is an irrational number represented in decimal by "0." followed by concatenation of all positive integers in the increasing order. The first few digits of this constant are: 0.123456789101112...
Your task is to write a program that outputs the K digits of Chapnernown constant starting at the N-th ... | ```python
#!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, ... |
p01624 Ononokomachi's Edit War | Dr. Akita, who lives in the neighborhood, is a historical researcher in the field and recently discovered a new ancient document about Ono no Komachi.
It is widely known that Ono no Komachi has given General Fukakusa, who wants to be dating, on condition that he keeps going for 100 nights, but he claims that this disc... | ```python
INF = 100000000000000
def ev1(s):
ans = 0
try:
ans = eval(s)
if ans == (): raise Exception
if len(s)==0: raise Exception
except:
ans = -INF
return ans
def ev2(s):
ans = 0
try:
ans = eval(s)
if ans == (): raise Exception
if len(s... |
p02191 Range Count Query | Range Count Query
Given the sequence a_1, a_2, .., a_N.
In the query, answer the number of terms whose value is l or more and r or less.
input
N Q
a_1 a_2 ... a_N
l_1 r_1
l_2 r_2
::
l_q r_q
output
ans_1
ans_2
::
ans_q
On line i, output the answer to the i-th query, that is, the number of j such as l_i \ leq ... | ```python
def num():
return int(input())
def nums():
return list(map(int,input().split()))
"""
N = num()
A = nums()
print(A.index(min(A))+1)
"""
"""
N = num()
A = set(nums())
print(len(A))
"""
def get_near_index(sorted_l,val,last):
left = 0
right = len(sorted_l) - 1
while left <= right:
mi... |
p02345 Range Minimum Query (RMQ) | Write a program which manipulates a sequence A = {a0, a1, . . . , an-1} with the following operations:
* find(s, t): report the minimum element in as, as+1, . . . ,at.
* update(i, x): change ai to x.
Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 10000... | ```python
class SegTree:
def __init__(self,N,f,ini):
"""
f(val,ini)=ini
"""
n=1
while n<N: n<<=1
self.n=n
self.arr=[ini]*(2*n-1)
self.f,self.ini=f,ini
def update(self,i,val):
i += self.n-1
self.arr[i]=val
while i>0:
... |
1038_D. Slime | There are n slimes in a row. Each slime has an integer value (possibly negative or zero) associated with it.
Any slime can eat its adjacent slime (the closest slime to its left or to its right, assuming that this slime exists).
When a slime with a value x eats a slime with a value y, the eaten slime disappears, and ... | ```python
import sys
import os
def solve(slimes):
if len(slimes) == 1:
return slimes[0]
havePos = False
haveNeg = False
for s in slimes:
if s > 0:
havePos = True
elif s < 0:
haveNeg = True
if havePos and haveNeg:
return sum(map(abs, slimes)... |
1102_A. Integer Sequence Dividing | You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible.
The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S.
Input
The first line of the input ... | ```python
def check(n):
if (n // 2) % 2 == 1:
return 0
return 1
n = int(input())
if n % 2 == 1:
print(check(n))
else:
print(check(n - 1))
``` |
1130_A. Be Positive | You are given an array of n integers: a_1, a_2, …, a_n. Your task is to find some non-zero integer d (-10^3 ≤ d ≤ 10^3) such that, after each number in the array is divided by d, the number of positive numbers that are presented in the array is greater than or equal to half of the array size (i.e., at least ⌈n/2⌉). Not... | ```python
import itertools
def main():
n = int(input())
data = [int(v) for v in input().split()]
mv = n//2 if n%2==0 else n//2+1
for i in range(-1000, 1001):
if i==0:
continue
if len([v/i for v in data if v/i>0])>=mv:
print(i)
return
print(0)
if... |
1150_B. Tiling Challenge | One day Alice was cleaning up her basement when she noticed something very curious: an infinite set of wooden pieces! Each piece was made of five square tiles, with four tiles adjacent to the fifth center tile:
<image> By the pieces lay a large square wooden board. The board is divided into n^2 cells arranged into n ... | ```python
n = int(input())
A = []
for i in range (n):
s = input()
A.append('#' + s + '#')
A.append('#' * (n + 2))
A.append('#' * (n + 2))
for i in range (n):
for j in range (1, n + 1):
#for k in range (n + 2):
# print(A[k])
#print(i, j)
#print()
#print()
if... |
1172_C1. Nauuo and Pictures (easy version) | The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal proba... | ```python
P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [[] for _ in range(M+1)]
X[0] = [1]
def calc(L):
su = sum(L)
pl = 0
pd = 0
RE = []... |
118_D. Caesar's Legions | Gaius Julius Caesar, a famous general, loved to line up his soldiers. Overall the army had n1 footmen and n2 horsemen. Caesar thought that an arrangement is not beautiful if somewhere in the line there are strictly more that k1 footmen standing successively one after another, or there are strictly more than k2 horsemen... | ```python
R = lambda: map(int, input().split())
n1, n2, k1, k2 = R()
k1 = min(k1, n1)
k2 = min(k2, n2)
dp = [[[0] * 2 for j in range(n2 + 1)] for i in range(n1 + 1)]
for i in range(k1 + 1):
dp[i][0][0] = 1
for i in range(k2 + 1):
dp[0][i][1] = 1
for i in range(1, n1 + 1):
for j in range(1, n2 + 1):
... |
1209_C. Paint the Digits | You are given a sequence of n digits d_1d_2 ... d_{n}. You need to paint all the digits in two colors so that:
* each digit is painted either in the color 1 or in the color 2;
* if you write in a row from left to right all the digits painted in the color 1, and then after them all the digits painted in the color ... | ```python
for _ in range(int(input())):
n = int(input())
d = [*map(int, input())]
s = d[:]
s.sort()
o = []
i = 0
ans = []
for j in range(n):
if d[j] == s[i]:
ans.append('1')
i += 1
else:
ans.append('2')
t = []
for i in range(n):
if ans[i] == '1':
t.append(d[i])
for i in range(n):
... |
1228_B. Filling the Grid | Suppose there is a h × w grid consisting of empty or full cells. Let's make some definitions:
* r_{i} is the number of consecutive full cells connected to the left side in the i-th row (1 ≤ i ≤ h). In particular, r_i=0 if the leftmost cell of the i-th row is empty.
* c_{j} is the number of consecutive full cells ... | ```python
n, m = map(int, input().split())
row = list(map(int, input().split()))
col = list(map(int, input().split()))
grid = [['?'] * m for _ in range(n)]
for i in range(n):
lng = row[i]
for j in range(lng):
grid[i][j] = 'b'
if lng < m:
grid[i][lng] = 'w'
for i in range(m):
lng = col[i]... |
1270_B. Interesting Subarray | For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) ≥ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 ≥ 5.
... | ```python
def findsubarray(n,ll):
for i in range(0,n-1):
if abs(ll[i]-ll[i+1])>1:
return 1,i+1,i+2
return 0,None,None
tests = int(input())
for i in range(0,tests):
numberlen = int(input())
numbers = input().split()
numberss = list(map(int,numbers))
result, left,right... |
1292_F. Nora's Toy Boxes | [SIHanatsuka - EMber](https://soundcloud.com/hanatsuka/sihanatsuka-ember)
[SIHanatsuka - ATONEMENT](https://soundcloud.com/hanatsuka/sihanatsuka-atonement)
Back in time, the seven-year-old Nora used to play lots of games with her creation ROBO_Head-02, both to have fun and enhance his abilities.
One day, Nora's adop... | ```python
MOD = 1000000007
def isSubset(a, b):
return (a & b) == a
def isIntersect(a, b):
return (a & b) != 0
# Solve for each weakly connected component (WCC)
def cntOrder(s, t):
p = len(s)
m = len(t)
inMask = [0 for i in range(m)]
for x in range(p):
for i in range(m):
if t[i] % s[x] == 0:
inMas... |
1312_G. Autocompletion | You are given a set of strings S. Each string consists of lowercase Latin letters.
For each string in this set, you want to calculate the minimum number of seconds required to type this string. To type a string, you have to start with an empty string and transform it into the string you want to type using the followin... | ```python
import io
import os
DEBUG = False
def dfs(trie, root, preorder=None, postorder=None):
stack = [root]
seen = set()
while stack:
nodeId = stack.pop()
if nodeId not in seen:
if preorder:
preorder(nodeId)
stack.append(nodeId)
seen.... |
1335_D. Anti-Sudoku | You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz).
The picture showing the correct sudoku solution:
<image>
Blocks are bordered with bold black color.
Your task is to change at most 9 elements of this field (i.e. choose s... | ```python
def f(grid):
for i in range(9):
for j in range(9):
if grid[i][j] == '1':
grid[i][j] = '2'
def main():
t = int(input())
for _ in range(t):
grid = [[x for x in input()] for __ in range(9)]
f(grid)
for row in grid:
print(''.join(row))
main()
``` |
1375_E. Inversion SwapSort | Madeline has an array a of n integers. A pair (u, v) of integers forms an inversion in a if:
* 1 ≤ u < v ≤ n.
* a_u > a_v.
Madeline recently found a magical paper, which allows her to write two indices u and v and swap the values a_u and a_v. Being bored, she decided to write a list of pairs (u_i, v_i) with t... | ```python
n=int(input())
arr=list(map(int,input().split()))
ans=[]
for i in range(n):
for j in range(n-1,i,-1):
if arr[i]>arr[j]:
ans.append((arr[i],i+1,j+1))
ans=sorted(ans,key=lambda x:x[0])
ans=sorted(ans,reverse=True,key=lambda x:x[2])
print(len(ans))
for _,u,v in ans:
print(u,v)
``` |
1399_A. Remove Smallest | You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | ```python
def t(b):
if b:
print("YES")
return
print("NO")
for _ in range(int(input())):
a = int(input())
l = sorted(list(map(int, input().split())))
for i in range(a - 1):
if l[i + 1] - l[i] >= 2:
t(False)
break
else:
t(True)
``` |
1422_D. Returning Home | Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city.
Let's represent the city as an area of n × n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the ... | ```python
from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
import sys
'''
@lru_cache(None)
def fact(x):
if x<2:
return 1
return fact(x-1)*x
@lru_cache(None)
def per(i,j):
... |
1440_C1. Binary Table (Easy Version) | This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | ```python
import sys
from itertools import permutations
from itertools import combinations
from itertools import combinations_with_replacement
#sys.stdin = open('/Users/pranjalkandhari/Desktop/Template/input.txt', 'r')
def makeThree(mat , i , j , liAns):
liToAdd = []
if(mat[i][j] == 1):
liToAdd.append(... |
1467_D. Sum of Paths | There are n cells, numbered 1,2,..., n from left to right. You have to place a robot at any cell initially. The robot must make exactly k moves.
In one move, the robot must move one cell to the left or right, provided that it doesn't move out of bounds. In other words, if the robot was in the cell i, it must move to e... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write i... |
1491_G. Switch and Flip | There are n coins labeled from 1 to n. Initially, coin c_i is on position i and is facing upwards ((c_1, c_2, ..., c_n) is a permutation of numbers from 1 to n). You can do some operations on these coins.
In one operation, you can do the following:
* Choose 2 distinct indices i and j.
* Then, swap the coins on ... | ```python
import sys
input = sys.stdin.readline
n = int(input());A = [0] + list(map(int, input().split()));seen = [0] * (n + 1);cycles = [];ans = []
for i in range(1, n + 1):
cur = [];j = i
while not seen[j]:cur.append(j);seen[j] = 1;j = A[j]
if len(cur) > 1: cycles.append(cur)
def swap(x, y):A[x], A[y] = ... |
1514_D. Cut and Stick | Baby Ehab has a piece of Cut and Stick with an array a of length n written on it. He plans to grab a pair of scissors and do the following to it:
* pick a range (l, r) and cut out every element a_l, a_{l + 1}, ..., a_r in this range;
* stick some of the elements together in the same order they were in the array; ... | ```python
from bisect import bisect, bisect_left
from random import random
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n, q = map(int, input().split())
a = list(map(int, input().split()))
v = [list() for i in range(n + 1)]
for i in range(n):
v[a[i]].append(i)
for i in range(q):
l, r =... |
1541_D. Tree Array | You are given a tree consisting of n nodes. You generate an array from the tree by marking nodes one by one.
Initially, when no nodes are marked, a node is equiprobably chosen and marked from the entire tree.
After that, until all nodes are marked, a node is equiprobably chosen and marked from the set of unmarked no... | ```python
from functools import lru_cache
from collections import deque
M = 10 ** 9 + 7
@lru_cache(None)
def inv(x):
return pow(x, M - 2, M)
@lru_cache(None)
def dp(u, v):
# u before v
if u == 0:
return 0
if v == 0:
return 1
return (dp(u - 1, v) * inv(2) + dp(u, v - 1) * inv(2))... |
18_A. Triangle | At a geometry lesson Bob learnt that a triangle is called right-angled if it is nondegenerate and one of its angles is right. Bob decided to draw such a triangle immediately: on a sheet of paper he drew three points with integer coordinates, and joined them with segments of straight lines, then he showed the triangle t... | ```python
import math
"""
#include <cstdio>
#include <iostream>
#include <algorithm>
bool isRight(int *c){
int sides[3] = {0};
sides[0] = (c[4] - c[2]) * (c[4] - c[2]) + (c[5] - c[3])* (c[5] - c[3]);
sides[1] = (c[4] - c[0]) * (c[4] - c[0]) + (c[5] - c[1])* (c[5] - c[1]);
sides[2] = (c[2] - c[0]) * (c... |
213_A. Game | Furik and Rubik love playing computer games. Furik has recently found a new game that greatly interested Rubik. The game consists of n parts and to complete each part a player may probably need to complete some other ones. We know that the game can be fully completed, that is, its parts do not form cyclic dependencies.... | ```python
n = int(input())
c = list(map(int, input().split()))
d = dict()
d[1] = []
d[2] = []
d[3] = []
for i in range(n):
d[c[i]].append(i)
done = set()
mas = []
k = 0
poss = set()
for i in range(n):
l = list(map(int, input().split()))
l = l[1:]
mas.append(l)
if len(l) == 0:
k = c[i]
... |
237_A. Free Cash | Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ... | ```python
t=int(input())
d={}
while (t>0):
t=t-1
s=input()
if s in d:
d[s]+=1
else:
d[s]=1
print(max(d.values()))
``` |
285_D. Permutation Sum | Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
Petya decided to introduce the sum operation on the se... | ```python
n = int(input())
ans = [1, 3, 5, 7, 9, 11, 13, 15]
dct = \
{
1 : 1,
3 : 18,
5 : 1800,
7 : 670320,
9 : 734832000,
11 : 890786230,
13 : 695720788,
15 : 150347555
}
if n in ans:
print(dct[n])
else:
print(0)
``` |
333_B. Chips | Gerald plays the following game. He has a checkered field of size n × n cells, where m various cells are banned. Before the game, he has to put a few chips on some border (but not corner) board cells. Then for n - 1 minutes, Gerald every minute moves each chip into an adjacent cell. He moves each chip from its original... | ```python
n, m = tuple(map(int, input().split(' ')))
vb = set()
hb = set()
for k in range(m):
i, j = tuple(map(int, input().split(' ')))
hb.add(i-1)
vb.add(j-1)
c = 0
for i in range(1, n//2):
c += 1 if i not in hb else 0
c += 1 if n-i-1 not in hb else 0
c += 1 if i not in vb else 0
c += 1 if n-i-1 not in vb else... |
37_A. Towers | Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ... | ```python
x=int(input())
l=list(map(int,input().split()))
a=list(set(l))
l.sort()
maxx=l.count(0)
for i in range(len(l)):
if(l.count(l[i])>maxx):
maxx=l.count(l[i])
print(maxx,len(a))
``` |
3_D. Least Cost Bracket Sequence | This is yet another problem on regular bracket sequences.
A bracket sequence is called regular, if by inserting "+" and "1" into it we get a correct mathematical expression. For example, sequences "(())()", "()" and "(()(()))" are regular, while ")(", "(()" and "(()))(" are not. You have a pattern of a bracket sequenc... | ```python
from heapq import heappush, heappop
from sys import stdin, exit
template = list(next(stdin).strip())
n, cost, balance = len(template), 0, 0
min_heap = []
for i in range(n):
if template[i] == '(':
balance += 1
elif template[i] == ')':
balance -= 1
else:
cost_left, cost_right = map(int, next(stdin)... |
427_A. Police Recruits | The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups.
Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime.
If there is no police offi... | ```python
n=int(input())
a=list(map(int,input().split()))
oc=0
cc=0
ans=0
for i in a:
if i>0:
oc+=i
elif oc==0:
ans+=1
else:
oc-=1
print(ans)
``` |
44_I. Toys | Little Masha loves arranging her toys into piles on the floor. And she also hates it when somebody touches her toys. One day Masha arranged all her n toys into several piles and then her elder brother Sasha came and gathered all the piles into one. Having seen it, Masha got very upset and started crying. Sasha still ca... | ```python
def combinacoes(x):
# Se for apenas 1 elemento retorna 1 arranjo
if x == 1:
return [[0]]
else:
# Adiciona os elementos a lista auxiliar
aux = combinacoes(x - 1)
pilha = []
par = 0
# Percorre a lista juntando os elementos nas possibilidades possíveis
for elem... |
496_A. Minimum Difficulty | Mike is trying rock climbing but he is awful at it.
There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe... | ```python
n=int(input())
lis=list(map(int,input().split()))
dif=abs(lis[1]-lis[0])
pos=[]
for i in range(n-1):
#print(i,end=",")
if(abs(lis[i]-lis[i+1])>dif):
dif=abs(lis[i]-lis[i+1])
for i in range(1,n-1):
t=abs(lis[i-1]-lis[i+1])
if(t>dif):
pos.append(t)
else:
pos.append(di... |
51_D. Geometrical problem | Polycarp loves geometric progressions — he collects them. However, as such progressions occur very rarely, he also loves the sequences of numbers where it is enough to delete a single element to get a geometric progression.
In this task we shall define geometric progressions as finite sequences of numbers a1, a2, ...,... | ```python
def main():
n = int(input())
l = tuple(map(int, input().split()))
if n == 1:
return 0
if n == 2:
if l[0] == 0 and l[1] != 0: return 1
return 0
def div(a, b):
if b == 0: return 0 if a == 0 else "inf"
return a / b
pref, suff = [["init", 1]], [["ini... |
546_E. Soldier and Traveling | In the country there are n cities and m bidirectional roads between them. Each city has an army. Army of the i-th city consists of ai soldiers. Now soldiers roam. After roaming each soldier has to either stay in his city or to go to the one of neighboring cities by at moving along at most one road.
Check if is it poss... | ```python
from sys import stdin
from collections import deque
def bfs(g, el, source, dest, pre):
q = deque()
pre.clear()
pre.extend([None] * len(g))
q.append(source)
while q:
u = q.popleft()
for e in g[u]:
v, c, f = el[e][1], el[e][2], el[e][3]
if pre[v] is None and f < c and v != source:
pre[v] = e... |
573_B. Bear and Blocks | Limak is a little bear who loves to play. Today he is playing by destroying block towers. He built n towers in a row. The i-th tower is made of hi identical blocks. For clarification see picture for the first sample.
Limak will repeat the following operation till everything is destroyed.
Block is called internal if i... | ```python
# Author : nitish420 --------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
def main():
n=int(input())
arr=list(map(int,input().split()))
if n<3:
print(1)
exit()
dp=[0]*(n)
dp[0]=1
dp[-1]=1
# first ... |
616_C. The Labyrinth | You are given a rectangular field of n × m cells. Each cell is either empty or impassable (contains an obstacle). Empty cells are marked with '.', impassable cells are marked with '*'. Let's call two empty cells adjacent if they share a side.
Let's call a connected component any non-extendible set of cells such that a... | ```python
from collections import deque
dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]]
componentsizes = {}
componentid = 0
n, m = map(int, input().split())
field = [list(input()) for _ in range(n)]
def valid(y, x):
return y >= 0 and x >= 0 and y < n and x < m
def component(y, x):
size = 1
q = deque([(y, x)]... |
635_D. Factory Repairs | A factory produces thimbles in bulk. Typically, it can produce up to a thimbles a day. However, some of the machinery is defective, so it can currently only produce b thimbles each day. The factory intends to choose a k-day period to do maintenance and construction; it cannot produce any thimbles during this time, but ... | ```python
from functools import reduce
class SegmentTree():
def __init__(self, L, function = lambda x,y: x+y, initilizer = None):
self.function = function
self.initilizer = initilizer
N = self.size = len(L)
M = 1 << N.bit_length()
self.margin = 2*M - N
self.L = [None ... |
664_C. International Olympiad | International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo... | ```python
from __future__ import print_function
dic = {"9":"1989","0":"1990","1":"1991","2":"1992","3":"1993","4":"1994","5":"1995","6":"1996","7":"1997","8":"1998"}
def get_year(s):
# print("came into get_year")
length=len(s)
if len(s)==1:
return dic[s]
pos=[s]
pre=1
if s[0]=="0" or len(s)<4 or (len(s)==4 ... |
689_A. Mike and Cellphone | While swimming at the beach, Mike has accidentally dropped his cellphone into the water. There was no worry as he bought a cheap replacement phone with an old-fashioned keyboard. The keyboard has only ten digital equal-sized keys, located in the following way:
<image>
Together with his old phone, he lost all his cont... | ```python
n = int(input())
s = input()
fill = [[False for i in range(3)] for j in range(4)]
for i in s:
if i == "0":
j = 10
else:
j = ord(i)-ord('1') #0, 1, 2, 3... 8
fill[j//3][j%3] = True
#for i in fill:
# print(i)
top = fill[0][0] or fill[0][1] or fill[0][2]
bottom = fill[2][0] or fill... |
710_E. Generate a String | zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a'... | ```python
n, x, y = map(int, input().split(" "))
l = [0.]*(n+1)
for i in range(1,n+1):
l[i] = min(l[i-1]+x, l[(i+1)//2]+y+(x*(i&1)))
print(int(l[n]))
``` |
731_E. Funny Game | Once upon a time Petya and Gena gathered after another programming competition and decided to play some game. As they consider most modern games to be boring, they always try to invent their own games. They have only stickers and markers, but that won't stop them.
The game they came up with has the following rules. In... | ```python
n=int(input())
a=[0]+list(map(int, input().split()))
p=[0]
for i in range(1, n+1):
p+=[ p[-1]+a[i] ]
d=[ p[n] ]*(n+1)
for i in range(n-2, 0, -1):
d[i]=max(d[i+1], p[i+1]-d[i+1])
print(d[1])
``` |
777_A. Shell Game | Bomboslav likes to look out of the window in his room and watch lads outside playing famous shell game. The game is played by two persons: operator and player. Operator takes three similar opaque shells and places a ball beneath one of them. Then he shuffles the shells by swapping some pairs and the player has to guess... | ```python
def nap(y):
if y==0:
p=[0,1,2]
return p
if y==1:
p=[1,0,2]
return p
if y==2:
p=[1,2,0]
return p
if y==3:
p=[2,1,0]
return p
if y==4:
p=[2,0,1]
return p
if y==5:
p=[0,2,1]
return p
n=int(inpu... |
801_D. Volatile Kite | You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value ... | ```python
from collections import Counter
n=int(input())
a=[]
for i in range(n):
a.append(list(map(int,input().split())))
#a.append(a[0])
m=10000000000
for i in range(-1,n-1):
b=a[i+1][0]-a[i-1][0]
c=a[i-1][1]-a[i+1][1]
d=-a[i-1][1]*b-a[i-1][0]*c
m=min(m,((a[i-1][0]-a[i][0])**2+(a[i-1][1]-a[i][1])**... |
822_A. I'm bored with life | Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave Vičkopolis and move to Pavlopo... | ```python
arr1 = input().split()
a = int(arr1[0])
b = int(arr1[1])
c = int(min(a, b))
res = 1
for i in range(2, c+1):
res *= i
print(res)
``` |
847_F. Berland Elections | The elections to Berland parliament are happening today. Voting is in full swing!
Totally there are n candidates, they are numbered from 1 to n. Based on election results k (1 ≤ k ≤ n) top candidates will take seats in the parliament.
After the end of the voting the number of votes for each candidate is calculated. I... | ```python
class State:
__slots__ = ['candidate', 'votes', 'last_vote']
def __init__(self, cand, votes, last):
self.candidate = cand
self.votes = votes
self.last_vote = last
def beats(self, other, extra):
return self.votes + extra > other.votes
def main():
candidates, seats, people, voted = ma... |
869_A. The Artful Expedient | Rock... Paper!
After Karen have found the deterministic winning (losing?) strategy for rock-paper-scissors, her brother, Koyomi, comes up with a new game as a substitute. The game works as follows.
A positive integer n is decided first. Both Koyomi and Karen independently choose n distinct positive integers, denoted ... | ```python
# Main maut ko takiya, aur kafan ko chaadar banakar audhta hoon!
print("Karen")
``` |
916_A. Jamie and Alarm Snooze | Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno... | ```python
def lucky(a,b):
return '7' in str(a)+str(b)
x = int(input())
t = 0
h,m = map(int,input().split())
while not lucky(h,m):
t+=1
m -= x
while m<0:
m+=60
h-=1
h%=24
print(t)
``` |
939_B. Hamster Farm | Dima has a hamsters farm. Soon N hamsters will grow up on it and Dima will sell them in a city nearby.
Hamsters should be transported in boxes. If some box is not completely full, the hamsters in it are bored, that's why each box should be completely full with hamsters.
Dima can buy boxes at a factory. The factory pr... | ```python
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 2 22:09:34 2018
@author: Xiaohua
"""
def Hamster(amounts,boxsize):
a=10000000000000000000
result=[0,0]
for i in range(0,len(boxsize)):
if(amounts[0]%boxsize[i]<a):
a=amounts[0]%boxsize[i]
result[0]=i+1
... |
991_E. Bus Number | This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all.
... | ```python
from itertools import chain, combinations
from collections import defaultdict
import math
def powerset(iterable):
xs = iterable
return chain.from_iterable(combinations(xs,n) for n in range(1, len(xs)+1))
def has(s):
h = 1
p = [2,3,5,7,11,13,17,19,23,29]
for i in s:
h *= p[i-1]
return h
h = se... |
p02620 Introduction to Heuristics Contest - Incremental Scoring | You will be given a contest schedule for D days and M queries of schedule modification. In the i-th query, given integers d_i and q_i, change the type of contest to be held on day d_i to q_i, and then output the final satisfaction at the end of day D on the updated schedule. Note that we do not revert each query. That ... | ```python
NTEST = 26
D=int(input())
C=list(map(int,input().split()))
SL=list()
SL.append([0 for i in range(NTEST)])
for d in range(D):
S=list(map(int,input().split()))
SL.append(S)
tests=list()
tests.append(0)
for d in range(D):
tests.append(int(input()))
def calcSat(test_applied):
lastDay = [0 for... |
p02751 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Odd Sum Rectangles | We have a grid with (2^N - 1) rows and (2^M-1) columns. You are asked to write 0 or 1 in each of these squares. Let a_{i,j} be the number written in the square at the i-th row from the top and the j-th column from the left.
For a quadruple of integers (i_1, i_2, j_1, j_2) such that 1\leq i_1 \leq i_2\leq 2^N-1, 1\leq ... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from itertools import permutations
import sys
import math
import bisect
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.