name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
652_D. Nested Segments | You are given n segments on a line. There are no ends of some segments that coincide. For each segment find the number of segments it contains.
Input
The first line contains a single integer n (1 ≤ n ≤ 2·105) — the number of segments on a line.
Each of the next n lines contains two integers li and ri ( - 109 ≤ li < ... | ```python
#!/usr/bin/env python3
from __future__ import division, print_function
import collections
def least_significant_bit(i):
return ((i) & -(i))
class FenwickTree():
def __init__(self, n):
# 1-indexed
self.n = n + 1
self.data = [0,] * self.n
def add(self, index, val... |
678_B. The Same Calendar | The girl Taylor has a beautiful calendar for the year y. In the calendar all days are given with their days of week: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday and Sunday.
The calendar is so beautiful that she wants to know what is the next year after y when the calendar will be exactly the same. Help Tayl... | ```python
y = int(input())
r = 0
def getDays(year):
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
return 366
else:
return 365
days = getDays(y)
while r == 0 or not (r % 7 == 0 and getDays(y) == days):
r += getDays(y)
y += 1
print(y)
``` |
700_B. Connecting Universities | Treeland is a country in which there are n towns connected by n - 1 two-way road such that it's possible to get from any town to any other town.
In Treeland there are 2k universities which are located in different towns.
Recently, the president signed the decree to connect universities by high-speed network.The Min... | ```python
def bfs(source):
q = [0] * (n + 1);
fa = [-1] * n
l, r = [1] * 2
fa[source] = source
q[1] = source
while l <= r:
x = q[l]
l += 1
for y in e[x]:
if fa[y] == -1:
fa[y] = x
r += 1
q[r] = y
... |
722_D. Generating Sets | You are given a set Y of n distinct positive integers y1, y2, ..., yn.
Set X of n distinct positive integers x1, x2, ..., xn is said to generate set Y if one can transform X to Y by applying some number of the following two operation to integers in X:
1. Take any integer xi and multiply it by two, i.e. replace xi w... | ```python
from collections import defaultdict
import heapq
pow=[1]
for i in range(30):
pow.append(pow[-1]*2)
n=int(input())
b=list(map(int,input().split()))
d=defaultdict(lambda:0)
for j in b:
d[j]=1
for j in range(n):
b[j]=-b[j]
heapq.heapify(b)
ans=[]
f=1
while(f):
j= -heapq.heappop(b)
can=0
... |
744_B. Hongcow's Game | This is an interactive problem. In the interaction section below you will see the information about flushing the output.
In this problem, you will be playing a game with Hongcow. How lucky of you!
Hongcow has a hidden n by n matrix M. Let Mi, j denote the entry i-th row and j-th column of the matrix. The rows and col... | ```python
from sys import stdout
def g(k, p):
print(str(k) + '\n' + ' '.join(map(str, p)))
stdout.flush()
n = int(input())
s = [9e9] * n
def f(q):
global s
p = [k + 1 for k, v in enumerate(q) if v]
g(len(p), p)
s = [i if j else min(i, int(k)) for i, j, k in zip(s, q, input().split())]
ret... |
791_C. Bear and Different Names | In the army, it isn't easy to form a group of soldiers that will be effective on the battlefield. The communication is crucial and thus no two soldiers should share a name (what would happen if they got an order that Bob is a scouter, if there are two Bobs?).
A group of soldiers is effective if and only if their names... | ```python
import sys
import math
from math import *
import builtins
import collections
import bisect
import os
from io import BytesIO, IOBase
def print(x, end='\n'):
sys.stdout.write(str(x) + end)
# IO helpers
def get_int():
return int(input())
def get_list_ints():
return list(map(int, input().split()... |
858_C. Did you mean... | Beroffice text editor has a wide range of features that help working with text. One of the features is an automatic search for typos and suggestions of how to fix them.
Beroffice works only with small English letters (i.e. with 26 letters from a to z). Beroffice thinks that a word is typed with a typo if there are thr... | ```python
s = input()
res = []
l = 0
for r in range(2, len(s)):
if r - l >= 2 and not any(c in 'aeiou' for c in s[r - 2:r + 1]) and s[r - 2:r + 1].count(s[r]) < 3:
res.append(s[l:r])
l = r
res.append(s[l:])
print(' '.join(res))
``` |
883_I. Photo Processing | Evlampiy has found one more cool application to process photos. However the application has certain limitations.
Each photo i has a contrast vi. In order for the processing to be truly of high quality, the application must receive at least k photos with contrasts which differ as little as possible.
Evlampiy already k... | ```python
from bisect import bisect_left, bisect_right
class Result:
def __init__(self, index, value):
self.index = index
self.value = value
class BinarySearch:
def __init__(self):
pass
@staticmethod
def greater_than(num: int, func, size: int = 1):
"""Searches for sm... |
907_D. Seating of Students | Students went into a class to write a test and sat in some way. The teacher thought: "Probably they sat in this order to copy works of each other. I need to rearrange them in such a way that students that were neighbors are not neighbors in a new seating."
The class can be represented as a matrix with n rows and m col... | ```python
import bisect
def list_output(s):
print(' '.join(map(str, s)))
def list_input(s='int'):
if s == 'int':
return list(map(int, input().split()))
elif s == 'float':
return list(map(float, input().split()))
return list(map(str, input().split()))
n, m = map(int, input(... |
928_A. Login Verification | When registering in a social network, users are allowed to create their own convenient login to make it easier to share contacts, print it on business cards, etc.
Login is an arbitrary sequence of lower and uppercase latin letters, digits and underline symbols («_»). However, in order to decrease the number of frauds ... | ```python
def f(s):
return s.lower().replace('1', 'l').replace('0', 'o').replace('i', 'l')
s = f(input())
n = int(input())
l = {f(input()) for _ in range(n)}
print('No' if s in l else 'Yes')
``` |
957_C. Three-level Laser | An atom of element X can exist in n distinct states with energies E1 < E2 < ... < En. Arkady wants to build a laser on this element, using a three-level scheme. Here is a simplified description of the scheme.
Three distinct states i, j and k are selected, where i < j < k. After that the following process happens:
... | ```python
n,u = map(int,input().split())
a = list(map(int,input().split()))
i = 0
j = 1
f = 1
ma = -1
while not((i==j) and (i==n-1)):
if j<=i:
j+=1
if j < n-1:
if a[j+1]-a[i] <= u:
j+=1
else:
if j-i >= 2:
f=0
#print(i,j)
... |
982_C. Cut 'em all! | You're given a tree with n vertices.
Your task is to determine the maximum possible number of edges that can be removed in such a way that all the remaining connected components will have even size.
Input
The first line contains an integer n (1 ≤ n ≤ 10^5) denoting the size of the tree.
The next n - 1 lines contai... | ```python
from collections import defaultdict
import threading
from sys import stdin,setrecursionlimit
setrecursionlimit(300000)
input=stdin.readline
def dfs(node,g,par,sz):
for i in g[node]:
if i!=par:
sz[node]+=dfs(i,g,node,sz)
return sz[node]+1
def main():
n=int(input())
if n%2!=0:
print(-1)
exit(0)
... |
p02560 AtCoder Library Practice Contest - Floor Sum | In this problem, you should process T testcases.
For each testcase, you are given four integers N, M, A, B.
Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).
Constraints
* 1 \leq T \leq 100,000
* 1 \leq N, M \leq 10^9
* 0 \leq A, B < M
Input
Input is given from Standard Input in the following format:
... | ```python
import sys
def I(): return int(sys.stdin.readline().rstrip())
def MI(): return map(int,sys.stdin.readline().rstrip().split())
def floor_sum(n,m,a,b): # sum((A*i+B)//M for i in range(N))
res = 0
res += (a//m)*n*(n-1)//2 + (b//m)*n
a %= m
b %= m
y_max = (a*n+b)//m
if y_max == 0:
... |
p02691 AtCoder Beginner Contest 166 - This Message Will Self-Destruct in 5s | You are the top spy of AtCoder Kingdom. To prevent the stolen secret from being handed to AlDebaran Kingdom, you have sneaked into the party where the transaction happens.
There are N attendees in the party, and they are given attendee numbers from 1 through N. The height of Attendee i is A_i.
According to an examina... | ```python
n= int(input())
l=list(map(int,input().split()))
d={}
ans=0
for i in range(n):
if i-l[i] in d:
ans+=d[i-l[i]]
if i+l[i] in d:
d[i+l[i]]+=1
else:
d[i+l[i]]=1
print(ans)
``` |
p02820 AtCoder Beginner Contest 149 - Prediction and Restriction | At an arcade, Takahashi is playing a game called RPS Battle, which is played as follows:
* The player plays N rounds of Rock Paper Scissors against the machine. (See Notes for the description of Rock Paper Scissors. A draw also counts as a round.)
* Each time the player wins a round, depending on which hand he/she use... | ```python
n, k = map(int, input().split())
r,s,p = map(int, input().split())
d = {"r":p, "s":r, "p":s}
t = input()
mode = [True]*n
score = 0
for i in range(n):
score += d[t[i]]
if i >= k and mode[i-k] and t[i] == t[i-k]:
score -= d[t[i]]
mode[i] = False
print(score)
``` |
p02956 AtCoder Beginner Contest 136 - Enclosed Points | We have a set S of N points in a two-dimensional plane. The coordinates of the i-th point are (x_i, y_i). The N points have distinct x-coordinates and distinct y-coordinates.
For a non-empty subset T of S, let f(T) be the number of points contained in the smallest rectangle, whose sides are parallel to the coordinate ... | ```python
import sys
from operator import itemgetter
input = sys.stdin.readline
class BIT():
"""一点加算、区間取得クエリをそれぞれO(logN)で答える
add: i番目にvalを加える
get_sum: 区間[l, r)の和を求める
"""
def __init__(self, n):
self.n = n
self.bit = [0] * (n + 1)
def _sum(self, i):
s = 0
while i... |
p03092 AtCoder Grand Contest 032 - Rotation Sort | You are given a permutation p = (p_1, \ldots, p_N) of \\{ 1, \ldots, N \\}. You can perform the following two kinds of operations repeatedly in any order:
* Pay a cost A. Choose integers l and r (1 \leq l < r \leq N), and shift (p_l, \ldots, p_r) to the left by one. That is, replace p_l, p_{l + 1}, \ldots, p_{r - 1}, ... | ```python
import sys
readline = sys.stdin.readline
N, A, B = map(int, readline().split())
*P, = map(int, readline().split())
Q = [0]*N
for i, p in enumerate(P):
Q[p-1] = i
INF = 10**18
dp = [[INF]*(N+1) for i in range(N+1)]
dp[0][0] = 0
for i in range(N):
qi = Q[i]
for j in range(N):
v = dp[i][j]
... |
p03238 AtCoder Beginner Contest 112 - Programming Education | In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education.
One day, there was an exam where a one-year-old child must write a program that prints `Hello World`, and a two-year-old child must write a program that receives integers A, B... | ```python
import sys
if input()=="1": print("Hello World"),sys.exit()
print(int(input())+int(input()))
``` |
p03391 AtCoder Regular Contest 094 - Tozan and Gezan | You are given sequences A and B consisting of non-negative integers. The lengths of both A and B are N, and the sums of the elements in A and B are equal. The i-th element in A is A_i, and the i-th element in B is B_i.
Tozan and Gezan repeats the following sequence of operations:
* If A and B are equal sequences, ter... | ```python
N=int(input())
num=0
result=0
min=10000000000
for i in range(N):
a,b=map(int,input().split())
if a>b:
if b<min:
min=b
num=1
result+=a
if num ==0:
print(0)
else:
result-=min
print(result)
``` |
p03554 AtCoder Regular Contest 085 - NRE | You are given a sequence a = \\{a_1, ..., a_N\\} with all zeros, and a sequence b = \\{b_1, ..., b_N\\} consisting of 0 and 1. The length of both is N.
You can perform Q kinds of operations. The i-th operation is as follows:
* Replace each of a_{l_i}, a_{l_i + 1}, ..., a_{r_i} with 1.
Minimize the hamming distance... | ```python
import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
ope=[[] for i in range(n)]
Q=int(input())
for i in range(Q):
l,r=map(int,input().split())
ope[r-1].append(l-1)
res=b.count(0)
Data=[(-1)**((b[i]==1)+1) for i in range(n)]
for i in range(1,n):
Data[i]+=Data[i-1]... |
p03709 AtCoder Grand Contest 015 - Mr.Aoki Incubator | Takahashi is an expert of Clone Jutsu, a secret art that creates copies of his body.
On a number line, there are N copies of Takahashi, numbered 1 through N. The i-th copy is located at position X_i and starts walking with velocity V_i in the positive direction at time 0.
Kenus is a master of Transformation Jutsu, an... | ```python
class BIT():
def __init__(self,n,mod):
self.BIT=[0]*(n+1)
self.num=n
self.mod=mod
def query(self,idx):
res_sum = 0
mod=self.mod
while idx > 0:
res_sum += self.BIT[idx]
res_sum%=mod
idx -= idx&(-idx)
return res... |
p03863 AtCoder Beginner Contest 048 - An Ordinary Game | There is a string s of length 3 or greater. No two neighboring characters in s are equal.
Takahashi and Aoki will play a game against each other. The two players alternately performs the following operation, Takahashi going first:
* Remove one of the characters in s, excluding both ends. However, a character cannot b... | ```python
#D
s = input()
if s[0] == s[-1]:
if len(s)%2==0:
print("First")
else:
print("Second")
else:
if len(s)%2==0:
print("Second")
else:
print("First")
``` |
p04029 AtCoder Beginner Contest 043 - Children and Candies (ABC Edit) | There are N children in AtCoder Kindergarten. Mr. Evi will arrange the children in a line, then give 1 candy to the first child in the line, 2 candies to the second child, ..., N candies to the N-th child. How many candies will be necessary in total?
Constraints
* 1≦N≦100
Input
The input is given from Standard Inpu... | ```python
N=int(input())
print(int(((1+N)*int(N))/2))
``` |
p00112 A Milk Shop | Mr. Suzuki has opened a new mobile sales shop for freshly squeezed milk in the Aizu area. It is assumed that all the customers who come to buy that day are already in the store with bottles to take home and will not increase any more. Customers only order once each. There is only one faucet in the tank, so you have to ... | ```python
while True:
inputCount = int(input())
if inputCount == 0:
break
timeList = [int(input()) for item in range(inputCount)]
timeList.sort()
waitTimeList = [0]
for lp in range(inputCount - 1):
waitTime = waitTimeList[-1] + timeList[lp]
waitTimeList.append(waitTi... |
p00427 Card Game II | Consider the following game. There are k pairs of n cards with numbers from 1 to n written one by one. Shuffle these kn cards well to make piles of k cards and arrange them in a horizontal row. The i-th (k-card) pile from the left of the n piles created in this way is called "mountain i".
<image>
The game starts at ... | ```python
# AOJ 0504: Card Game II
# Python3 2018.7.1 bal4u
from decimal import *
while True:
n, k, m, r = map(int, input().split())
if n == 0: break
setcontext(Context(prec=r, rounding=ROUND_HALF_UP))
one = Decimal(1)
ans = one/Decimal(n)
if m == 1:
s = 0
for i in range(1, n): s += one/Decimal(i)
ans... |
p00622 Monster Factory | Nantendo Co., Ltd. has released a game software called Packet Monster. This game was intended to catch, raise, and fight monsters, and was a very popular game all over the world.
This game had features not found in traditional games. There are two versions of this game, Red and Green, and the monsters that can be caug... | ```python
# AOJ 1036: Monster Factory
# Python3 2018.7.6 bal4u
while True:
in1 = list(input())
if in1[0] == '-': break
in2 = list(input())
out = list(input())
k = in2.pop(0)
ans, f = '', True
while len(in1) or len(in2):
if len(out) and out[0] == k:
k = in1.pop(0)
del out[0]
else:
ans += k
if len... |
p00766 Patisserie ACM | Amber Claes Maes, a patissier, opened her own shop last month. She decided to submit her work to the International Chocolate Patissier Competition to promote her shop, and she was pursuing a recipe of sweet chocolate bars. After thousands of trials, she finally reached the recipe. However, the recipe required high skil... | ```python
from collections import deque
class Dinic:
"""
Dinicのアルゴリズム。最大流問題を解くことができます。
https://tjkendev.github.io/procon-library/python/max_flow/dinic.html
"""
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap):
forward =... |
p01470 Four Arithmetic Operations | Problem statement
There is a rational number sequence $ X_0, X_1, X_2, ..., X_N $. Each term is defined as follows.
1. $ X_0 = 0 $
2. $ X_i = X_ {i-1} $ $ op_i $ $ Y_i $ ($ 1 \ leq i \ leq N $). However, $ op_i $ is $ + $, $ − $, $ × $, $ ÷ $ Either.
Find $ X_N $.
Constraint
* $ 1 \ leq N \ leq 10 ^ 5 $
* $ 1 \... | ```python
m=10000000019
x=0
def mod(x):return (x%m+m)%m
def pow(x,a):
ret=1
while a:
if(a&1):ret=mod(x*ret)
x=mod(x*x)
a>>=1
return ret
for _ in range(int(input())):
o,y=map(int,input().split())
if o==1:x=(x+y)%m
elif o==2:x=(x-y)%m
elif o==3:x=mod(x*y)
else:x=mo... |
p01630 B2D | Problem Statement
Do you know the data structure called BDD (Binary Decision Diagram)? In recent years, ZDD, which has become a hot topic in the video related to Combinatorial Explosion Sister, is a data structure derived from BDD. This problem is a basic implementation of BDD.
BDD is a cycleless graph (DAG) that rep... | ```python
def root(x):
if x == par[x]:
return x
par[x] = root(par[x])
return par[x]
def unite(x,y):
x = root(x)
y = root(y)
if rank[x] < rank[y]:
par[x] = y
else:
par[y] = x
if rank[x] == rank[y]:
rank[x] += 1
n = int(input())
par = [i for i in r... |
p01782 Decoding Ancient Messages | Example
Input
3
aab
czc
baa
Output
aac | ```python
import heapq
class edge:
def __init__(self,to,cap,cost,rev):
self.to = to
self.cap = cap
self.cost = cost
self.rev = rev
class min_cost_flow:
INF = 52**60
def __init__(self, n):
self.V = n
self.G = [[] for _ in range(n)]
self.h = [0 for _ i... |
p01917 Dance Now! | B: Dansunau www --Dance Now!-
story
Last lab life! Daigakuin! !! Dosanko Snow has won 9th place in the event "Master Idol World", which can be said to be the outpost of the biggest competition "Lab Life" where master idols compete. The sharp dance is ridiculed as "9th place dance", and the whole body's deciding pose ... | ```python
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
n = int(input())
R = list(map(int,input().split()))
SPC = []
S = []
P = []
C = []
ans = 10**5
for i in range(n):
s,p,c = map(int,input().split())
S.append(s)
P.append(p)
C.append(c)
SPC.append([s,p,c])
you = list(SPC[0])
... |
p02055 Two Colors Sort | D: Two Colors Sort
problem
During the walk, umg found a sequence of length N, P_1, P_2, ..., P_N, which can be made by rearranging 1,2, ..., N.
umg can use mysterious powers to exchange places by choosing two different numbers painted in the same color.
umg wanted to be able to sort the sequence in ascending order ... | ```python
import sys
N, R = map(int, input().split())
if 2*R > N:
R = N - R
P = [0] + list(map(int, input().split()))
L = []
used = [False]*(N+1)
pre = 0
for i in range(1, N+1):
cnt = 0
while not used[i]:
used[i] = True
cnt += 1
i = P[i]
if cnt:
L.append(cnt)
table = [0... |
p02197 Twins | Twins
square1001 and E869120 are twins.
Please output the one that was born first.
input
No input is given.
output
Output the correct character string on one line.
However, insert a line break at the end.
Output example 1
square1001
Example
Input
Output | ```python
print('square1001')
``` |
p02351 RSQ and RAQ | Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(s, t, x): add x to as, as+1, ..., at.
* getSum(s, t): report the sum of as, as+1, ..., at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 1 ≤ ... | ```python
import sys
input = sys.stdin.readline
class LazyPropSegmentTree:
def __init__(self, lst, op, apply, comp, e, identity):
self.n = len(lst)
self.depth = (self.n - 1).bit_length()
self.N = 1 << self.depth
self.op = op # binary operation of elements
self.apply = apply ... |
1010_A. Fly | Natasha is going to fly on a rocket to Mars and return to Earth. Also, on the way to Mars, she will land on n - 2 intermediate planets. Formally: we number all the planets from 1 to n. 1 is Earth, n is Mars. Natasha will make exactly n flights: 1 → 2 → … n → 1.
Flight from x to y consists of two phases: take-off from ... | ```python
input()
m=int(input())
v=m
try:
for a in map(int, input().split() + input().split()):
v*=a
v/=a-1
print(v-m)
except ZeroDivisionError:
print(-1)
``` |
1034_A. Enlarge GCD | Mr. F has n positive integers, a_1, a_2, …, a_n.
He thinks the greatest common divisor of these integers is too small. So he wants to enlarge it by removing some of the integers.
But this problem is too simple for him, so he does not want to do it by himself. If you help him, he will give you some scores in reward.
... | ```python
from math import gcd
n = int(input())
l = list(map(int,input().split()))
m = max(l)+1
prime = [0]*(m)
commondivisor = [0]*(m)
def seive():
for i in range(2,m):
if prime[i] == 0:
for j in range(i*2,m,i):
prime[j] = i
for i in range(2,m):
if not prime[i]:
prime[i] = i
gc = l[... |
1056_F. Write The Contest | Polycarp, Arkady's friend, prepares to the programming competition and decides to write a contest. The contest consists of n problems and lasts for T minutes. Each of the problems is defined by two positive integers a_i and p_i — its difficulty and the score awarded by its solution.
Polycarp's experience suggests that... | ```python
from math import sqrt
class pro(object):
def __init__(self,dif,sc):
self.dif=dif
self.sc=sc
def __lt__(self,other):
return self.dif>other.dif
T=int(input())
mul=[1]
for i in range(100):
mul.append(mul[i]*10/9)
inf=1000000007
for t in range(T):
n=int(input())
effi,... |
107_B. Basketball Team | As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to differen... | ```python
from math import lgamma, exp
n, m, h = map(int, input().split())
ds = list(map(int, input().split()))
s, d = sum(ds), ds[h - 1]
if s < n:
print(-1)
elif s + 1 < n + d:
print(1)
else:
print(1 - exp(lgamma(s - d + 1) + lgamma(s - n + 1) - lgamma(s) - lgamma(s - d - n + 2)))
``` |
109_A. Lucky Sum of Digits | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya wonders eagerly what minimum lucky number has the sum of digits equal to n. Help him cope with... | ```python
n = int(input())
i = 0
j = 0
while n>=0:
if n%7==0:
j = n//7
ans = ['4'] * i + ['7'] * j
print("".join(ans))
break
n-=4
i+=1
else:
print(-1)
``` |
1120_A. Diana and Liana | At the first holiday in spring, the town Shortriver traditionally conducts a flower festival. Townsfolk wear traditional wreaths during these festivals. Each wreath contains exactly k flowers.
The work material for the wreaths for all n citizens of Shortriver is cut from the longest flowered liana that grew in the tow... | ```python
from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
# import string
# characters = string.ascii_lowercase
# digits = string.digits
# setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as... |
1147_C. Thanos Nim | Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stone... | ```python
n = int(input())
jog = [int(i) for i in input().split()]
mi = min(jog)
qtd = 0
for i in range(len(jog)):
if(jog[i] == mi):
qtd+=1
if(qtd <= n//2 and qtd!=0):
print("Alice")
else:
print("Bob")
``` |
1187_A. Stickers and Toys | Your favorite shop sells n Kinder Surprise chocolate eggs. You know that exactly s stickers and exactly t toys are placed in n eggs in total.
Each Kinder Surprise can be one of three types:
* it can contain a single sticker and no toy;
* it can contain a single toy and no sticker;
* it can contain both a sing... | ```python
for _ in range(int(input())):
n,s,t = map(int,input().split())
print(max(n-s+1,n-t+1))
``` |
1223_C. Save the Nature | You are an environmental activist at heart but the reality is harsh and you are just a cashier in a cinema. But you can still do something!
You have n tickets to sell. The price of the i-th ticket is p_i. As a teller, you have a possibility to select the order in which the tickets will be sold (i.e. a permutation of t... | ```python
t = int(input())
for case_num in range(t):
n = int(input())
p = list(map(int, input().split(' ')))
x, a = map(int, input().split(' '))
y, b = map(int, input().split(' '))
k = int(input())
p.sort()
p.reverse()
sum = [0]
for i in range(n):
sum.append(sum[-1] + p[i])
... |
1267_E. Elections | Byteburg Senate elections are coming. Usually "United Byteland", the ruling Byteland party, takes all the seats in the Senate to ensure stability and sustainable development. But this year there is one opposition candidate in one of the constituencies. Even one opposition member can disturb the stability in the Senate,... | ```python
import math
IP = lambda: list(map(int, input().split()))
INF = 1e9
n, m = IP()
lst = [[] for i in range(n)]
for i in range(m):
d = IP()
for j in range(n):
lst[j].append(d[j])
# print(*lst, sep = '\n')
s = [sum(i) for i in lst]
ret = [[] for i in range(n-1)]
if s[-1] <= max(s[:-1]):
print(... |
1332_A. Exercising Walk | Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat!
Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move:
* exactly a steps left: from (u,v) to (u-1,v);
* exactly b steps right: from (u,v) to (u+1,v); ... | ```python
import sys
I = lambda: int(input())
readline = lambda: sys.stdin.readline().strip('\n')
RM = readmap = lambda x=int: map(x,readline().split(' '))
#1332 630 div2
for _ in range(I()):
a,b,c,d,x,y,x1,y1,x2,y2 = *RM(),*RM()
flag1 = x2-x >= b-a and x-x1 >= a-b and y2-y >= d-c and y-y1 >= c-d
flag2 =... |
1352_D. Alice, Bob and Candies | There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | ```python
from sys import stdin, stdout
from collections import deque
def main():
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
ar = deque(map(int, stdin.readline().split()))
a = 0
b = 0
prev = ar.popleft()
a += prev
turn = 1
... |
1372_B. Omkar and Last Class of Math | In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b.
Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc... | ```python
from math import ceil, sqrt
for _ in range(int(input())):
n = int(input())
if n % 2 == 0: print(n // 2, n // 2)
else:
for i in range(3, ceil(sqrt(n)) + 1):
if n % i == 0:
print(n // i, n - (n // i))
break
else:
print(1, n - 1... |
1395_A. Boboniu Likes to Color Balls | Boboniu gives you
* r red balls,
* g green balls,
* b blue balls,
* w white balls.
He allows you to do the following operation as many times as you want:
* Pick a red ball, a green ball, and a blue ball and then change their color to white.
You should answer if it's possible to arrange all the b... | ```python
n = int(input(''))
for i in range(n):
r,g,b,w= map(int,input().split())
num = r%2+g%2+b%2+w%2
less = min(r,min(g,b))
if less == 0:
if num > 1:
print('No')
else:
print('Yes')
else:
if num == 2:
print('No')
else:
... |
1419_D1. Sage's Birthday (easy version) | This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | ```python
n = int(input())
a = sorted([int(i) for i in input().split()])
b = []
for i in range(n // 2):
b.append(a[-1-i])
b.append(a[i])
if n % 2 == 1:
b.append(a[n // 2])
print((n - 1) // 2)
print(' '.join([str(i) for i in b]))
``` |
1437_D. Minimal Height Tree | Monocarp had a tree which consisted of n vertices and was rooted at vertex 1. He decided to study BFS ([Breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)), so he ran BFS on his tree, starting from the root. BFS can be described by the following pseudocode:
a = [] # the order in whi... | ```python
tests = int (input())
for test in range (tests):
n = int (input())
a = list(map (int, input().split()))
res = 1
tails = 1
ntails = 0
i = 1
while i < n:
if tails == 0:
res += 1
tails = ntails
ntails = 0
while (i + 1 < n and a[i] < a[i+1]):
i += 1
ntails += 1... |
1462_B. Last Year's Substring | Polycarp has a string s[1 ... n] of length n consisting of decimal digits. Polycarp performs the following operation with the string s no more than once (i.e. he can perform operation 0 or 1 time):
* Polycarp selects two numbers i and j (1 ≤ i ≤ j ≤ n) and removes characters from the s string at the positions i, i+... | ```python
for x in range(int(input())):
n = int(input())
s = input()
if s[0]+s[1]+s[2]+s[3] == "2020":
print("YES")
elif s[0]+s[1]+s[2]+s[n-1] == "2020":
print("YES")
elif s[0]+s[1]+s[n-2]+s[n-1] == "2020":
print("YES")
elif s[0]+s[n-3]+s[n-2]+s[n-1] == "2020":
pr... |
1487_C. Minimum Ties | A big football championship will occur soon! n teams will compete in it, and each pair of teams will play exactly one game against each other.
There are two possible outcomes of a game:
* the game may result in a tie, then both teams get 1 point;
* one team might win in a game, then the winning team gets 3 point... | ```python
import math
import sys
import collections
import bisect
import heapq
ans = []
testcases = int(sys.stdin.readline())
for _ in range(testcases):
n = int(sys.stdin.readline())
arr = [[None]*n for i in range(n)]
if n % 2 == 0:
x = 1
y = 0
for i in range(n//2):
... |
1510_K. King's Task | The brave Knight came to the King and asked permission to marry the princess. The King knew that the Knight was brave, but he also wanted to know if he was smart enough. So he asked him to solve the following task.
There is a permutation p_i of numbers from 1 to 2n. You can make two types of operations.
1. Swap p_... | ```python
from sys import maxsize
N = int(input())
org_arr = list(map(int, input().split()))
sorted_arr = list(range(1, 2 * N + 1))
cost = maxsize
pos = False
for swap in range(2):
arr = org_arr.copy()
tmp_cost = 0
while arr[0] != 1:
if swap:
arr = arr[N:] + arr[:N]
else:
for idx in range(0, 2 * N - 1, 2... |
1538_E. Funny Substrings | Polycarp came up with a new programming language. There are only two types of statements in it:
* "x := s": assign the variable named x the value s (where s is a string). For example, the statement var := hello assigns the variable named var the value hello. Note that s is the value of a string, not the name of a v... | ```python
def count(string):
c=0
for i in range(len(string)-3):
k=0
va=0
for j in "haha":
if string[i+k]==j:
va+=1
else:
break
k+=1
if va==4:
c+=1
return c
def values(string):
length=len(strin... |
186_A. Comparing Strings | Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | ```python
g1=list(input())
g2=list(input())
cntr=0
if sorted(g1)!=sorted(g2):
print('NO')
else:
for i in range(len(g1)):
if g1[i]!=g2[i]:
cntr=cntr+1
if cntr==2:
print('YES')
else:
print('NO')
``` |
232_B. Table | John Doe has an n × m table. John Doe can paint points in some table cells, not more than one point in one table cell. John Doe wants to use such operations to make each square subtable of size n × n have exactly k points.
John Doe wondered, how many distinct ways to fill the table with points are there, provided that... | ```python
n,m,k=map(int,input().split())
M=int(1e9+7)
N=n*n
iv=[0]*(N+1)
iv[1]=1
for i in range(2, N+1):
iv[i]=M-M//i*iv[M%i]%M
f1=[1]*(N+1)
for i in range(1, N+1):
f1[i]=f1[i-1]*i%M
f2=[1]*(N+1)
for i in range(1, N+1):
f2[i]=f2[i-1]*iv[i]%M
left=m%n
#m/n+1, m/n
def powM(b, p):
r=1
while p>0:
... |
258_A. Little Elephant and Bits | The Little Elephant has an integer a, written in the binary notation. He wants to write this number on a piece of paper.
To make sure that the number a fits on the piece of paper, the Little Elephant ought to delete exactly one any digit from number a in the binary record. At that a new number appears. It consists of ... | ```python
n=input()
c=0
res=''
for i in range(len(n)):
if(n[i]=='0' and c==0):
c+=1
elif(n[i]=='0' and c>0):
res+="0"
elif(n[i]=='1'):
res+="1"
else:
pass
l=len(res)
if c==0:
res=res[:l-1]
print(res)
``` |
281_A. Word Capitalization | Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | ```python
n=list(input())
print(n[0].upper()+str(''.join(n[1:])))
``` |
330_A. Cakeminator | You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows:
<image>
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain... | ```python
r,c = map(int,input().split())
data = [list(input()) for i in range(r)]
total=0
for i in range(r):
if 'S' not in data[i]:
total+=c
row = total//c
for j in range(c):
for k in range(r):
if data[k][j]=='S':
break
else:
total=total+r-row
print(total)
... |
420_C. Bug in Code | Recently a serious bug has been found in the FOS code. The head of the F company wants to find the culprit and punish him. For that, he set up an organizational meeting, the issue is: who's bugged the code? Each of the n coders on the meeting said: 'I know for sure that either x or y did it!'
The head of the company d... | ```python
from collections import defaultdict
from bisect import bisect_left as lower
import sys
input = sys.stdin.readline
def put():
return map(int, input().split())
try:
n,m = put()
cnt, mp, ans = [0]*n, defaultdict(), [0]*n
for _ in range(n):
x,y = put()
x,y = x-1,y-1
key = ... |
447_A. DZY Loves Hash | DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | ```python
Str=input()
ss=[int(s) for s in Str.split() if s.isdigit()]
p=ss[0]
n=ss[1]
ll=[]
for i in range(n):
x=int(input())
r=x%p
if r not in ll:
ll.append(r)
else:
print(i+1)
break
else:
print(-1)
``` |
469_B. Chat Online | Little X and Little Z are good friends. They always chat online. But both of them have schedules.
Little Z has fixed schedule. He always online at any moment of time between a1 and b1, between a2 and b2, ..., between ap and bp (all borders inclusive). But the schedule of Little X is quite strange, it depends on the ti... | ```python
p,q,l,r=list(map(int,input().split()))
a=[]
for i in range(p):
k,j=list(map(int,input().split()))
a.append((k,j))
b=[]
for i in range(q):
k,j=list(map(int,input().split()))
b.append((k,j))
b.sort(key=lambda h:h[0])
count=0
for i in range(l,r+1):
for j in range(len(b)):
gg=0
... |
491_A. Up the hill | Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.
It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the se... | ```python
A, B = int(input()), int(input())
print(*range(B+1, A+B+2), *reversed(range(1, B+1)))
``` |
515_B. Drazil and His Happy Friends | Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and... | ```python
def slve(n,m,b,g):
bo = [0] * n;gi = [0] * m;i=0
for i in range(1, len(b)):
bo[b[i]] = 1
for i in range(1, len(g)):
gi[g[i]] = 1
while i <=10000:
if bo[(i % n)] == 1 or gi[(i % m)] == 1:bo[(i % n)], gi[(i % m)] = 1, 1
if bo == [1] * n and gi == [1] * m:return 'Y... |
542_C. Idempotent functions | Some time ago Leonid have known about idempotent functions. Idempotent function defined on a set {1, 2, ..., n} is such function <image>, that for any <image> the formula g(g(x)) = g(x) holds.
Let's denote as f(k)(x) the function f applied k times to the value x. More formally, f(1)(x) = f(x), f(k)(x) = f(f(k - 1)(x))... | ```python
from random import randint
from copy import deepcopy
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
a[i] -= 1
def gen(n):
a = []
for i in range(n):
a.append(randint(0, n - 1))
return a
def stupid(a, v=False):
n = len(a)
init = [a[i] for i in range(n)... |
569_D. Symmetric and Transitive | Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (a, b) of elements ... | ```python
def main():
mod = 10 ** 9 + 7
n = int(input())
a = [[0] * (n + 1) for i in range(n + 1)]
a[0][0] = 1
for i in range(1, n + 1):
a[i][0] = a[i - 1][i - 1]
for j in range(1, i + 1):
a[i][j] = (a[i][j - 1] + a[i - 1][j - 1]) % mod
print(a[n][n - 1])
main()
``` |
590_B. Chip 'n Dale Rescue Rangers | A team of furry rescue rangers was sitting idle in their hollow tree when suddenly they received a signal of distress. In a few moments they were ready, and the dirigible of the rescue chipmunks hit the road.
We assume that the action takes place on a Cartesian plane. The headquarters of the rescuers is located at poi... | ```python
from math import sqrt
import re
class point2:
def __init__(self, x, y):
self.x = x
self.y = y
def length(self):
return sqrt(self.x * self.x + self.y * self.y)
def xmult(a, b):
return a.x * b.y - a.y * b.x
def dmult(a, b):
return a.x * b.x + a.y * b.y
x1, y1, x2, ... |
612_A. The Text Splitting | You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q.
For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo".
Note it is allowed to split the string s to the strings only of length p or... | ```python
n, p, q = map(int, input().split())
s = input()
for i in range(n // p + 1):
for j in range(n // q + 1):
if i * p + j * q == n:
print(i + j)
for k in range(i):
print(s[k * p: (k + 1) * p])
for k in range(j):
print(s[i * p + k * q: ... |
632_A. Grandma Laura and Apples | Grandma Laura came to the market to sell some apples. During the day she sold all the apples she had. But grandma is old, so she forgot how many apples she had brought to the market.
She precisely remembers she had n buyers and each of them bought exactly half of the apples she had at the moment of the purchase and al... | ```python
n,k = map(int,input().split())
s = [input() for i in range(n)]
s = s[::-1]
x = 0
# print(s)
cost = 0
for i in s:
if i == "halfplus":
x = 2*x+1
cost += x/2*k
else:
x = 2*x
cost += x/2*k
print(int(cost))
``` |
660_D. Number of Parallelograms | You are given n points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
Input
The first line of the input contains integer n (1 ≤ n ≤ 2000) — the number of points.
Each of the next n lines contains two integers... | ```python
n=int(input())
def inp(n):
coor=[[int(i) for i in input().split()] for j in range(n)]
return coor
coor=inp(n)
def newlist(a):
d={}
s=len(a)
for i in range(1,s):
for j in range(i):
if (a[i][0]+a[j][0],a[i][1]+a[j][1]) in d:
d[a[i][0]+a[j][0],a[i][... |
707_B. Bakery | Masha wants to open her own bakery and bake muffins in one of the n cities numbered from 1 to n. There are m bidirectional roads, each of whose connects some pair of cities.
To bake muffins in her bakery, Masha needs to establish flour supply from some storage. There are only k storages, located in different cities nu... | ```python
def solve():
n, m, k = list(map(int, input().split()))
graph = [dict() for i in range(n + 1)]
for i in range(m):
u, v, l = list(map(int, input().split()))
if v not in graph[u]:
graph[u][v] = l
graph[v][u] = l
else:
graph[u][v] = min(gra... |
74_E. Shift It! | There is a square box 6 × 6 in size. It contains 36 chips 1 × 1 in size. Those chips contain 36 different characters — "0"-"9" and "A"-"Z". There is exactly one chip with each character.
You are allowed to make the following operations: you may choose one of 6 rows or one of 6 columns and cyclically shift the chips th... | ```python
ls="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
s,cnt,a1,a2=[],0,[],[]
for i in range(6):
s.append(list(input()))
def add(c,i):
global cnt
cnt+=1
a1.append(c)
a2.append(i)
def right(i):
add('R',i+1)
tmp=s[i][5]
for j in range(5,0,-1):
s[i][j]=s[i][j-1]
s[i][0]=tmp
def left(i):
add('L',i+1)
tmp=s[i][... |
798_C. Mike and gcd problem | Mike has a sequence A = [a1, a2, ..., an] of length n. He considers the sequence B = [b1, b2, ..., bn] beautiful if the gcd of all its elements is bigger than 1, i.e. <image>.
Mike wants to change his sequence in order to make it beautiful. In one move he can choose an index i (1 ≤ i < n), delete numbers ai, ai + 1 a... | ```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
n = int(input())
a = list(map(int, input().split()))
ans = 0
l = 0
g = a[0]
for i in range(n):
g = gcd(a[i], g)
if g > 1:
print('YES\n0')
else:
for i in range(n):
if a[i] % 2:
l += 1
else... |
818_E. Card Game Again | Vova again tries to play some computer card game.
The rules of deck creation in this game are simple. Vova is given an existing deck of n cards and a magic number k. The order of the cards in the deck is fixed. Each card has a number written on it; number ai is written on the i-th card in the deck.
After receiving th... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(1... |
844_A. Diversity | Calculate the minimum number of characters you need to change in the string s, so that it contains at least k different letters, or print that it is impossible.
String s consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too.
Input
First line of input con... | ```python
m=input()
n=int(input())
if n>len(m):
print("impossible")
else:
v=n-len(set(m))
print(v if v>0 else 0)
``` |
864_D. Make a Permutation! | Ivan has an array consisting of n elements. Each of the elements is an integer from 1 to n.
Recently Ivan learned about permutations and their lexicographical order. Now he wants to change (replace) minimum number of elements in his array in such a way that his array becomes a permutation (i.e. each of the integers fr... | ```python
def solve(printing):
n = int(input())
nums = [int(st)-1 for st in input().split(" ")]
numdupe = [0] * n
dupeindex = []
dupeindexindv = {}
missing = []
if printing:
print("nums"); print(nums)
for i in range(n):
numdupe[nums[i]] += 1
for i in range(n):
... |
88_C. Trains | Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,... | ```python
a, b = input().split()
a = int(a); b = int(b)
def gcd(a, b):
if a < b:
return gcd(b, a)
elif not a%b:
return b
return gcd(b, a%b)
lcm = a*b//gcd(a, b)
if a > b:
d_count = lcm//a
m_count = lcm//b - 1
if m_count > d_count:
print("Masha")
elif m_count == d_count:
print("Equal")
else:
print(... |
913_A. Modular Exponentiation | The following problem is well-known: given integers n and m, calculate
<image>,
where 2n = 2·2·...·2 (n factors), and <image> denotes the remainder of division of x by y.
You are asked to solve the "reverse" problem. Given integers n and m, calculate
<image>.
Input
The first line contains a single integer n (1 ... | ```python
n,m=int(input()),int(input())
n=min(n,31)
print(m%(2**n))
``` |
935_A. Fafa and his Company | Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ... | ```python
n = int(input())
count = 1
for i in range(2,(n//2)+1):
if (n-i)%i ==0:
count+=1
print(count)
``` |
988_E. Divisibility by 25 | You are given an integer n from 1 to 10^{18} without leading zeroes.
In one move you can swap any two adjacent digits in the given number in such a way that the resulting number will not contain leading zeroes. In other words, after each move the number you have cannot contain any leading zeroes.
What is the minimum ... | ```python
def idx(s, c, start = 0):
try:
return s[::-1].index(c, start)
except:
return -1
def main():
s = input()
zero_cnt = 0
while zero_cnt < len(s) - 1 and s[zero_cnt + 1] == '0':
zero_cnt += 1
i01 = idx(s, '0')
i02 = idx(s, '0', i01 + 1)
i2 = idx(s, '2')
... |
p02597 AtCoder Beginner Contest 174 - Alter Altar | An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; `R` stands for red and `W` stands for white.
You can do the following two kinds of operations any number of times in any order:
* Choose two stones (not nec... | ```python
N = int(input())
S = input()
r = S.count('R')
ans = r - S[:r].count('R')
print(ans)
``` |
p02728 AtCoder Beginner Contest 160 - Distributing Integers | We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and b_i. For each k=1, ..., N, solve the problem below:
* Consider writing a number on each vertex in the tree in the following manner:
* First, write 1 on Vertex k.
* Then, for each of the numbers 2, ..., N in this order, w... | ```python
def main():
M=10**9+7
N=10**5*2
fac=[0]*(N+1)
fac[0]=b=1
for i in range(1,N+1):fac[i]=b=b*i%M
inv=[0]*(N+1)
inv[N]=b=pow(fac[N],M-2,M)
for i in range(N,0,-1):inv[i-1]=b=b*i%M
n,*t=open(0).read().split()
n=int(n)
e=[[]for _ in range(n)]
for a,b in zip(*[map(int,t... |
p02860 AtCoder Beginner Contest 145 - Echo | Given are a positive integer N and a string S of length N consisting of lowercase English letters.
Determine whether the string is a concatenation of two copies of some string. That is, determine whether there is a string T such that S = T + T.
Constraints
* 1 \leq N \leq 100
* S consists of lowercase English letter... | ```python
N=int(input());S=input()
print('Yes') if S[:N//2] == S[N//2:] else print('No')
``` |
p02995 AtCoder Beginner Contest 131 - Anti-Division | You are given four integers A, B, C, and D. Find the number of integers between A and B (inclusive) that can be evenly divided by neither C nor D.
Constraints
* 1\leq A\leq B\leq 10^{18}
* 1\leq C,D\leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
A B ... | ```python
import fractions
a,b,c,d=map(int,input().split())
a-=1
e=c*d//fractions.gcd(c,d)
print(b-a-b//c+a//c-b//d+a//d+b//e-a//e)
``` |
p03136 AtCoder Beginner Contest 117 - Polygon | Determine if an N-sided polygon (not necessarily convex) with sides of length L_1, L_2, ..., L_N can be drawn in a two-dimensional plane.
You can use the following theorem:
Theorem: an N-sided polygon satisfying the condition can be drawn if and only if the longest side is strictly shorter than the sum of the lengths... | ```python
input()
a, *b = sorted(map(int, input().split()), reverse=True)
print('Yes' if a < sum(b) else 'No')
``` |
p03281 AtCoder Beginner Contest 106 - 105 | The number 105 is quite special - it is odd but still it has eight divisors. Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?
Constraints
* N is an integer between 1 and 200 (inclusive).
Input
Input is given from Standard Input in the following... | ```python
import bisect
n = int(input())
print(bisect.bisect([105, 135, 165, 189, 195], n))
``` |
p03436 AtCoder Beginner Contest 088 - Grid Repainting | Constraints
* H is an integer between 2 and 50 (inclusive).
* W is an integer between 2 and 50 (inclusive).
* s_{i, j} is `.` or `#` (1 \leq i \leq H, 1 \leq j \leq W).
* s_{1, 1} and s_{H, W} are `.`.
Input
Input is given from Standard Input in the following format:
H W
s_{1, 1}s_{1, 2}s_{1, 3} ... s_{1, W}
s_{2,... | ```python
from collections import deque
h,w = map(int,input().split())
maze = []
visited = [[0]*(w) for _ in range(h)]
mx = 0
for _ in range(h):
s = input()
mx += s.count('.')
maze.append(list(s))
sy,sx = 0, 0
gy, gx = h-1, w-1
que = deque([(sy,sx,1)])
while que:
y,x,c = que.popleft()
if visited[y]... |
p03752 square869120Contest #4 - Buildings are Colorful! | Input Format
N K
a_1 a_2 a_3 ... a_N
Output Format
Print the minimum cost in one line. In the end put a line break.
Constraints
* 1 ≤ K ≤ N ≤ 15
* 1 ≤ a_i ≤ 10^9
Scoring
Subtask 1 [120 points]
* N = K
Subtask 2 [90 points]
* N ≤ 5
* a_i ≤ 7
Subtask 3 [140 points]
* There are no additional constraint... | ```python
n,k=map(int,input().split())
A=list(map(int,input().split()))
ans=float("inf")
for i in range(1,2**n):
num=format(i,"b").zfill(n)
point=0
if num.count("1")!=k:continue
highest=A[0]
for j in range(1,n):
if highest>=A[j] and num[j]=="1":
point +=highest-A[j]+1
... |
p00019 Factorial | Write a program which reads an integer n and prints the factorial of n. You can assume that n ≤ 20.
Input
An integer n (1 ≤ n ≤ 20) in a line.
Output
Print the factorial of n in a line.
Example
Input
5
Output
120 | ```python
num = int(input())
ans = num
for i in range(1, num):
ans = ans *i
print(ans)
``` |
p00150 Twin Prime | Prime numbers are widely applied for cryptographic and communication technology. A twin prime is a prime number that differs from another prime number by 2. For example, (5, 7) and (11, 13) are twin prime pairs.
In this problem, we call the greater number of a twin prime "size of the twin prime."
Your task is to crea... | ```python
def isPrime(n):
for i in range(2,int(n**.5+1)):
if n%i==0:
return False
return True
while 1:
n=int(input())
if not n:break
for i in range(n,1,-1):
if isPrime(i) and isPrime(i-2):
print(i-2,i)
break
``` |
p00663 SAT-EN-3 | She was worried. The grades are not good. Although she forced her parents to enroll in a dormitory school, her talent never blossomed. Or maybe he didn't have the talent in the first place, but it was possible that he didn't want to think about it as much as possible.
So she relied on the dubious brain training materi... | ```python
# AOJ 1078: SAT-EN-3
# Python3 2018.7.10 bal4u
def clause(e):
f = True
dic = {}
f = e.split('&')
for x in f:
pm, t = 1, x[0]
if t == '~':
pm, t = -1, x[1]
if t in dic and dic[t] + pm == 0: f = False
dic[t] = pm
return f
while True:
p = input()
if p == '#': break
exp = list(p.split('|'))
... |
p00937 Sibling Rivalry | Example
Input
3 3 1 2 4
1 2
2 3
3 1
Output
IMPOSSIBLE | ```python
from collections import deque
import sys
def solve():
readline = sys.stdin.readline
write = sys.stdout.write
N, M, *V = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
u, v = map(int, readline().split())
G[u-1].append(v-1)
def matmul(A, B):
... |
p01340 Kaeru Jump | There is a frog living in a big pond. He loves jumping between lotus leaves floating on the pond. Interestingly, these leaves have strange habits. First, a leaf will sink into the water after the frog jumps from it. Second, they are aligned regularly as if they are placed on the grid points as in the example below.
<i... | ```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**13
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 ... |
p01678 Restore Calculation | Problem Statement
The Animal School is a primary school for animal children. You are a fox attending this school.
One day, you are given a problem called "Arithmetical Restorations" from the rabbit teacher, Hanako. Arithmetical Restorations are the problems like the following:
* You are given three positive integers... | ```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 ... |
p01957 Tournament Chart | In 21XX, an annual programming contest, Japan Algorithmist GrandPrix (JAG) has become one of the most popular mind sports events.
JAG is conducted as a knockout tournament. This year, $N$ contestants will compete in JAG. A tournament chart is represented as a string. '[[a-b]-[c-d]]' is an easy example. In this case, t... | ```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, ... |
p02244 8 Queens Problem | The goal of 8 Queens Problem is to put eight queens on a chess-board such that none of them threatens any of others. A queen threatens the squares in the same row, in the same column, or on the same diagonals as shown in the following figure.
<image>
For a given chess board where $k$ queens are already placed, find ... | ```python
from itertools import product
def setq(ri,ci,krc):
for ir in range(8):
if ir!=ri:
if krc[ir*8+ci]=="Q":
return False,krc
else:
krc[ir*8+ci]="X"
for ic in range(8):
if ic!=ci:
if krc[ri*8+ic]=="Q":
retu... |
p02390 Watch | Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.
Constraints
* $0 \leq S \leq 86400$
Input
An integer $S$ is given in a line.
Output
Print $h$, $m$ and $s$ separated by ':'. You do not n... | ```python
s=int(input())
a=60
print(f'{s//a**2}:{s//a%a}:{s%a}')
``` |
1056_C. Pick Heroes | Don't you tell me what you think that I can be
If you say that Arkady is a bit old-fashioned playing checkers, you won't be right. There is also a modern computer game Arkady and his friends are keen on. We won't discuss its rules, the only feature important to this problem is that each player has to pick a distinct h... | ```python
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 12/14/18
"""
import collections
import time
import os
import sys
import bisect
import heapq
N, M = map(int, input().split())
P = [0] + [int(x) for x in input().split()]
A = [0 for _ in range(2*N+1)]
pairs = []
for i in range(M):
a, b = map(in... |
1099_D. Sum in the tree | Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vert... | ```python
import sys
def getAndParseInt(num=1):
string = (sys.stdin.readline()).strip()
if num==1:
return int(string)
else:
return [int(part) for part in string.split()]
def getAndParseString(num=1,delim=" "):
string = (sys.stdin.readline()).strip()
if num==1:
return string
... |
1168_A. Increasing by Modulo | Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i... | ```python
def check(mid,arr,n,m):
prev=0
for i in range(n):
if(arr[i]>prev):
t=m-(arr[i]-prev)
if(t>mid):
prev=arr[i]
else:
t=prev-arr[i]
if(t>mid):
return False
return True
n,m=map(int,input().split())
arr=list(map(int,input().split()))
lo=0
hi=m
while(lo<=hi):
mid=(lo+hi)//2
if(check(mid,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.