name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1143_A. The Doors | Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | ```python
def the_doors(arr,n):
count_1 = 0
count_0 = 0
for i in arr:
if i == 0:count_0 += 1
else:count_1 += 1
check_1 = 0
check_0 = 0
for i in range(n):
if arr[i] == 0:
check_0 += 1
else:
check_1 += 1
if count_0 == check_0:
... |
1163_B1. Cat Party (Easy Edition) | This problem is same as the next one, but has smaller constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to the n... | ```python
'''input
5
10 2 5 4 1
'''
n = int(input())
arr = list(map(int,input().split()))
count = [0]*10
ans = 1
for i in range(n):
count[arr[i]-1]+=1
cp_count = list.copy(count)
cp_count.sort()
r =0
for j in range(1,10):
if cp_count[j]!=cp_count[j-1]:
r+=1
if (r==0 and cp_count[0]==1):
ans = i+1
elif (r=... |
1183_G. Candy Box (hard version) | This problem is a version of problem D from the same contest with some additional constraints and tasks.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type pres... | ```python
from collections import defaultdict
from sys import stdin, stdout
q = int(stdin.readline())
for it in range(q):
n = int(stdin.readline())
d = [0]*n
f = [0]*n
for i in range(n):
t, b = map(int, stdin.readline().split())
d[t-1]+=1
if b == 1:
f[t-1] += 1
... |
1201_B. Zero Array | You are given an array a_1, a_2, …, a_n.
In one operation you can choose two elements a_i and a_j (i ≠ j) and decrease each of them by one.
You need to check whether it is possible to make all the elements equal to zero or not.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the size of the array.... | ```python
n=int(input())
a=list(map(int, input().split()))
if(sum(a)<2*max(a) or sum(a)%2==1):
print("NO")
else:
print("YES")
``` |
1243_B1. Character Swap (Easy Version) | This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct str... | ```python
t=int(input())
for ti in range(t):
n=int(input())
lia=[]
lib=[]
a=list(input())
b=list(input())
ctr=0
for i in range(n):
if a[i]!=b[i]:
lia.append(a[i])
lib.append(b[i])
ctr+=1
if ctr>2:
print("No")
break
... |
1284_C. New Year and Permutation | Recall that the permutation is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
A sequence a is a subsegment of a... | ```python
n, m = map(int, input().split())
fac = [1]
for i in range(1, n + 1):
fac.append(i * fac[i - 1] % m)
ans = 0
for i in range(1, n+1):
ans += (n - i + 1) * fac[i] * fac[n - i + 1]
ans %= m
print(ans)
``` |
1303_E. Erase Subsequences | You are given a string s. You can build new string p from s using the following operation no more than two times:
1. choose any subsequence s_{i_1}, s_{i_2}, ..., s_{i_k} where 1 ≤ i_1 < i_2 < ... < i_k ≤ |s|;
2. erase the chosen subsequence from s (s can become empty);
3. concatenate chosen subsequence to th... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
from math import inf,isinf
def solve(s,t):
if len(t) == 1:
if s.count(t[0]):
return 'YES'
return 'NO'
for i in range(1,len(t)):
dp = [[-inf]*(i+1) for _ in ran... |
1327_F. AND Segments | You are given three integers n, k, m and m conditions (l_1, r_1, x_1), (l_2, r_2, x_2), ..., (l_m, r_m, x_m).
Calculate the number of distinct arrays a, consisting of n integers such that:
* 0 ≤ a_i < 2^k for each 1 ≤ i ≤ n;
* bitwise AND of numbers a[l_i] \& a[l_i + 1] \& ... \& a[r_i] = x_i for each 1 ≤ i ≤ m... | ```python
def main():
import sys
input = sys.stdin.buffer.readline
mod = 998244353
N, K, M = map(int, input().split())
cond = []
for _ in range(M):
cond.append(tuple(map(int, input().split())))
ans = 1
for k in range(K):
one = [0] * (N+1)
zero_cond = [0] * (N+1)
... |
1368_F. Lamps on a Circle | This is an interactive problem.
John and his imaginary friend play a game. There are n lamps arranged in a circle. Lamps are numbered 1 through n in clockwise order, that is, lamps i and i + 1 are adjacent for any i = 1, …, n - 1, and also lamps n and 1 are adjacent. Initially all lamps are turned off.
John and his f... | ```python
from sys import stdout, exit
from traceback import format_exc
def main():
n = int(input())
on = [False] * n
def query(ll):
res = 0
pvals = [i+1 for i in ll]
print(len(ll), ' '.join(map(str,pvals)))
stdout.flush()
for i in ll:
if not on[i]:
... |
138_A. Literature Lesson | Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their ... | ```python
n,k=list(map(int,input().split()))
def z(a,b):
global k
c=0
d=''
for i in range(len(a)-1,-1,-1):
d+=a[i]
if a[i] in ['a','e','i','o','u']:
c+=1
if c==k:
break
f=c==k
c=0
e=''
for i in range(len(b)-1,-1,-1):
e+=b[i]
... |
1454_E. Number of Simple Paths | You are given an undirected graph consisting of n vertices and n edges. It is guaranteed that the given graph is connected (i. e. it is possible to reach any vertex from any other vertex) and there are no self-loops and multiple edges in the graph.
Your task is to calculate the number of simple paths of length at leas... | ```python
import sys
input=sys.stdin.readline
from collections import defaultdict,deque
t=int(input())
for _ in range(t):
n=int(input())
ct=[1]*(n+1)
deg=[0]*(n+1)
d=defaultdict(set)
for _ in range(n):
u,v=map(int,input().split())
d[u].add(v)
d[v].add(u)
deg[u]+=1
... |
1478_C. Nezzar and Symmetric Array | Long time ago there was a symmetric array a_1,a_2,…,a_{2n} consisting of 2n distinct integers. Array a_1,a_2,…,a_{2n} is called symmetric if for each integer 1 ≤ i ≤ 2n, there exists an integer 1 ≤ j ≤ 2n such that a_i = -a_j.
For each integer 1 ≤ i ≤ 2n, Nezzar wrote down an integer d_i equal to the sum of absolute d... | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in... |
1505_F. Math | <image> <image>
*The two images are equivalent, feel free to use either one.
Input
The input contains a single integer a (-100 ≤ a ≤ 100).
Output
Output the result – an integer number.
Example
Input
1
Output
1 | ```python
s=int(input())
print(2-s**2)
``` |
15_E. Triangles | Last summer Peter was at his granny's in the country, when a wolf attacked sheep in the nearby forest. Now he fears to walk through the forest, to walk round the forest, even to get out of the house. He explains this not by the fear of the wolf, but by a strange, in his opinion, pattern of the forest that has n levels,... | ```python
a,b,c,m=1,2,4,10**9+9
n=int(input())
for i in range(1,n//2):
c=c*a%m
b=(b+c)%m
a=(2*a+3)%m
print((b*b+1)*2%m)
``` |
17_B. Hierarchy | Nick's company employed n people. Now Nick needs to build a tree hierarchy of «supervisor-surbodinate» relations in the company (this is to say that each employee, except one, has exactly one supervisor). There are m applications written in the following form: «employee ai is ready to become a supervisor of employee bi... | ```python
import sys
import math
import collections
import heapq
input=sys.stdin.readline
n=int(input())
l=[int(i) for i in input().split()]
m=int(input())
s=0
d={}
for i in range(m):
a,b,c=(int(i) for i in input().split())
if(b in d):
d[b]=min(d[b],c)
else:
d[b]=c
c1=0
for i in range(1,n+1)... |
202_C. Clear Symmetry | Consider some square matrix A with side n consisting of zeros and ones. There are n rows numbered from 1 to n from top to bottom and n columns numbered from 1 to n from left to right in this matrix. We'll denote the element of the matrix which is located at the intersection of the i-row and the j-th column as Ai, j.
L... | ```python
'''input
3
'''
from sys import stdin
import math
def make_dp():
dp = [0] * 1001
dp[1] = 1
dp[3] = 5
for i in range(5, 100, 2):
dp[i] = dp[i - 2] + i + i - 2
return dp
# main starts
x = int(stdin.readline().strip())
if x == 3:
print(5)
exit()
dp = make_dp()
for i in range(1, len(dp)):
if x <= d... |
227_B. Effective Approach | Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the requ... | ```python
def editorial(n, a, m, b):
c = [None] * n
for i, x in enumerate(a):
c[x - 1] = i + 1
vasya = 0
petya = 0
for x in b:
i = c[x - 1]
vasya += i
petya += n - i + 1
return (vasya, petya)
if __name__ == '__main__':
n = int(input())
a = [int(x) for x ... |
250_E. Mad Joe | Joe has been hurt on the Internet. Now he is storming around the house, destroying everything in his path.
Joe's house has n floors, each floor is a segment of m cells. Each cell either contains nothing (it is an empty cell), or has a brick or a concrete wall (always something one of three). It is believed that each f... | ```python
n, m = [int(i) for i in input().split()]
current_floor = list(input())
x, t, direction = 0, 0, 1
for i in range(n-1):
floor = list(input())
l, r = x, x
wall = 0
while True:
t += 1
if floor[x] == '.':
break
if (x + direction == m) or (x + direction < 0) or ... |
276_A. Lunch Rush | Having written another programming contest, three Rabbits decided to grab some lunch. The coach gave the team exactly k time units for the lunch break.
The Rabbits have a list of n restaurants to lunch in: the i-th restaurant is characterized by two integers fi and ti. Value ti shows the time the Rabbits need to lunch... | ```python
n, k = map(int,input().split())
f = t = 0
maxf = -1000000000
for i in range(n):
f, t = map(int,input().split())
if t > k: f -= (t - k)
if f > maxf: maxf = f
print(maxf)
``` |
299_C. Weird Game | Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fir... | ```python
#!/usr/bin/python3
n = int(input())
s = list(input())
l = list(input())
a = len([_ for _ in zip(s, l) if _ == ('1', '1')])
b = len([_ for _ in zip(s, l) if _ == ('1', '0')])
c = len([_ for _ in zip(s, l) if _ == ('0', '1')])
f = b + (a + 1) // 2
s = c + a // 2
if f > s:
print('First')
elif f + 1 < s:
... |
322_A. Ciel and Dancing | Fox Ciel and her friends are in a dancing room. There are n boys and m girls here, and they never danced before. There will be some songs, during each song, there must be exactly one boy and one girl are dancing. Besides, there is a special rule:
* either the boy in the dancing pair must dance for the first time (so... | ```python
n, m = map(int, input().split())
print(n + m - 1)
for i in range (1, n + 1): print(i, 1)
for i in range (1, m): print(1, i + 1)
``` |
441_A. Valera and Antique Items | Valera is a collector. Once he wanted to expand his collection with exactly one antique item.
Valera knows n sellers of antiques, the i-th of them auctioned ki items. Currently the auction price of the j-th object of the i-th seller is sij. Valera gets on well with each of the n sellers. He is perfectly sure that if h... | ```python
r = lambda: list(map(int, input().split()))[1:]
n,c = map(int, input().split())
d = []
for _ in range(n):
for i in r():
if i<c:
d.append(str(_+1))
break
print (len(d))
print (' '.join(d))
``` |
463_B. Caisa and Pylons | Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (n + 1) pylons numbered from 0 to n in this game. The pylon with number 0 has zero height, the pylon with number i (i > 0) has height hi. The goal of the game is to reach n-th pylon... | ```python
n=int(input())
s=list(map(int,input().split()))
m,h,d=0,0,0
for i in range(n):
m+=h-s[i]
if(m<0):
d-=m
m=0
h=s[i]
print(d)
``` |
487_A. Fight the Monster | A monster is attacking the Cyberland!
Master Yang, a braver, is going to beat the monster. Yang and the monster each have 3 attributes: hitpoints (HP), offensive power (ATK) and defensive power (DEF).
During the battle, every second the monster's HP decrease by max(0, ATKY - DEFM), while Yang's HP decreases by max(0,... | ```python
from math import *
#from bisect import *
#from collections import *
#from random import *
#from decimal import *"""
#from heapq import *
#from random import *
import sys
input=sys.stdin.readline
#sys.setrecursionlimit(3*(10**5))
global flag
def inp():
return int(input())
def st():
return input().rstri... |
535_A. Tavas and Nafas | Today Tavas got his test result as an integer score and he wants to share it with his girlfriend, Nafas.
His phone operating system is Tavdroid, and its keyboard doesn't have any digits! He wants to share his score with Nafas via text, so he has no choice but to send this number using words.
<image>
He ate coffee mi... | ```python
l=['','-one','-two','-three','-four','-five','-six','-seven','-eight','-nine']
l1=['ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen']
l2=['twenty','thirty','forty','fifty','sixty','seventy','eighty','ninety']
l3=['zero','one','two','three','four','five','six',... |
55_B. Smallest number | Recently, Vladimir got bad mark in algebra again. To avoid such unpleasant events in future he decided to train his arithmetic skills. He wrote four integer numbers a, b, c, d on the blackboard. During each of the next three minutes he took two numbers from the blackboard (not necessarily adjacent) and replaced them wi... | ```python
import math,sys
from itertools import permutations
from collections import defaultdict,deque
import bisect as bi
def yes():print('YES')
def no():print('NO')
#sys.stdin=open('input.txt','r');sys.stdout=open('output.txt','w');
def I():return (int(sys.stdin.readline()))
def In():return(map(int,sys.stdin.readline... |
629_D. Babaei and Birthday Cake | As you know, every birthday party has a cake! This time, Babaei is going to prepare the very special birthday party's cake.
Simple cake is a cylinder of some radius and height. The volume of the simple cake is equal to the volume of corresponding cylinder. Babaei has n simple cakes and he is going to make a special ca... | ```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... |
653_E. Bear and Forgotten Tree 2 | A tree is a connected undirected graph consisting of n vertices and n - 1 edges. Vertices are numbered 1 through n.
Limak is a little polar bear. He once had a tree with n vertices but he lost it. He still remembers something about the lost tree though.
You are given m pairs of vertices (a1, b1), (a2, b2), ..., (am, ... | ```python
import sys
import math
from heapq import *;
input = sys.stdin.readline
from functools import cmp_to_key;
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
re... |
701_D. As Fast As Possible | On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k pe... | ```python
n, l, v1, v2, k=map(int,input().split())
n=(n+k-1)//k
t0=l/v1
t1=l/v2
if n==1:
print(t1)
else:
for k in range(50):
t=(t0+t1)/2
d2=v2*t
x2=(d2-l)/(n-1)/2
u2=(d2-(n-1)*x2)/n
tt=u2/v2+(l-u2)/v1
if tt>t: t1=t
else: t0=t
print(t)
``` |
723_E. One-Way Reform | There are n cities and m two-way roads in Berland, each road connects two cities. It is known that there is no more than one road connecting each pair of cities, and there is no road which connects the city with itself. It is possible that there is no way to get from one city to some other city using only these roads.
... | ```python
import sys
from collections import defaultdict
rlines = sys.stdin.readlines()
lines = (l.strip() for l in rlines)
def eucycle(n,m,adj):
dir_edges = []
us = list(adj.keys())
for u in us:
while adj[u]:
v0 = u
v1 = adj[v0].pop()
adj[v1].remove(v0)
dir_edges.append((v0, v1))
while v1 != u:... |
745_D. 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
import sys
n = int(input())
MAX = 2000 * 1000 * 1000
res = [MAX] * n
k = 1
while k < n:
x = [0] * n
output = []
sz = 0
for i in range(0, n, 2 * k):
for j in range(0, min(n - i, k)):
output.append(i + j + 1)
sz += 1
#print(i + j + 1, end = ' ')
... |
768_F. Barrels and boxes | Tarly has two different type of items, food boxes and wine barrels. There are f food boxes and w wine barrels. Tarly stores them in various stacks and each stack can consist of either food boxes or wine barrels but not both. The stacks are placed in a line such that no two stacks of food boxes are together and no two s... | ```python
import sys
def factorial():
global mod
fac = [1] * int(3e5 + 1)
for i in range(1, int(3e5)):
fac[i] = i*fac[i-1] % mod
return fac
def inverse(x):
global mod
return pow(x, mod-2, mod)
def C(n, r):
global fac
if n < 0 or n < r:
return 0
return fac[n]*inverse(f... |
792_E. Colored Balls | There are n boxes with colored balls on the table. Colors are numbered from 1 to n. i-th box contains ai balls, all of which have color i. You have to write a program that will divide all balls into sets such that:
* each ball belongs to exactly one of the sets,
* there are no empty sets,
* there is no set con... | ```python
import time
import sys
from math import sqrt
n = int(input())
a = list(map(int, input().split()))
sq = int(sqrt(a[0]))+2
s = set()
for box in range(1, sq):
if a[0] % box == 0:
s.add(a[0] // box)
s.add(a[0] // box - 1)
else:
s.add(a[0] // box)
for balls in range(1, sq):
... |
813_B. The Golden Age | Unlucky year in Berland is such a year that its number n can be represented as n = xa + yb, where a and b are non-negative integer numbers.
For example, if x = 2 and y = 3 then the years 4 and 17 are unlucky (4 = 20 + 31, 17 = 23 + 32 = 24 + 30) and year 18 isn't unlucky as there is no such representation for it.
Su... | ```python
x, y, l, r = map(int, input().split())
def gen_list(var):
cur = 1
while cur <= r:
yield cur
cur *= var
x_list = list(gen_list(x))
# print(x_list)
y_list = list(gen_list(y))
# print(y_list)
numbers = [l-1, r+1]
for _x in x_list:
for _y in y_list:
n = _x + _y
if n... |
839_A. Arya and Bran | Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her cand... | ```python
n, k = map(int, input().split())
a = list(map(int, input().split()))
aria = 0
bran = 0
for i in range(n):
aria += a[i]
if aria > 8:
bran += 8
aria -= 8
else:
bran += aria
aria = 0
if bran >= k:
print(i + 1)
break
if bran < k:
print(-1... |
859_D. Third Month Insanity | The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - ... | ```python
n = int(input())
# Using the same index I would for a tree
m = 2**n
points = [0]*(2*m)
points[1] = 2**(n-1)
for i in range(1,m):
x = points[i]//2
points[2*i] = x
points[2*i+1] = x
P = [[int(x)/100.0 for x in input().split()] for _ in range(m)]
state = [[0.0]*64 for _ in range(2*m)]
for i in r... |
884_C. Bertown Subway | The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. I... | ```python
input()
l = [[int(x)-1,False] for x in input().split()]
loop = []
for begin in l:
if begin[1]:
continue
count = 0;
nextI = begin[0];
while not l[nextI][1]:
l[nextI][1]=True
nextI = l[nextI][0]
count += 1
loop.append(count)
s = sorted(loop,reverse=True)
total... |
908_E. New Year and Entity Enumeration | You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
... | ```python
from collections import defaultdict as di
MOD = int(1e9+7)
bells = di(int)
bells[0,0] = 1
K=1000
for j in range(1,K):
bells[0,j] = bells[j-1,j-1]
for i in range(j):
bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD
def bellman(n):
return bells[n-1,n-1]
m,n = [int(x) for x in input().sp... |
92_D. Queue | There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus stan... | ```python
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
b = [0] * n
for i in range(n - 1, -1, -1):
b[i] = bisect_left(a, a[i], i + 1, len(a)) - i - 2
a[i] = min(a[i + 1], a[i]) if i != n - 1 else a[i]
print (*b)
# Made By Mostafa_Khaled
``` |
958_B2. Maximum Control (medium) | The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels i... | ```python
from sys import stdin
from collections import defaultdict
import heapq
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]... |
p02567 AtCoder Library Practice Contest - Segment Tree | You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},... | ```python
class segtree:
## define what you want to do ,(min, max)
sta = -1
func = max
def __init__(self,n):
self.n = n
self.size = 1 << n.bit_length()
self.tree = [self.sta]*(2*self.size)
def build(self, list):
for i,x in enumerate(list,self.size):
self... |
p02698 AtCoder Beginner Contest 165 - LIS on Tree | We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k... | ```python
from bisect import bisect_left
n = int(input())
A = [0] + list(map(int, input().split()))
graph = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
graph[v].append(u)
graph[u].append(v)
start = 1
stack = [1]
par = [-1] * (n + 1)
ans = [0] * (n + 1)
used = [False... |
p02964 AtCoder Grand Contest 036 - Do Not Duplicate | We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty... | ```python
from bisect import bisect_right
from collections import defaultdict
N, K = map(int, input().split())
As = list(map(int, input().split()))
indices_of_elem = defaultdict(list)
for i, A in enumerate(As):
indices_of_elem[A].append(i)
empty_index = [0]
while True:
cur_index = empty_index[-1]
look_fo... |
p03099 AtCoder Grand Contest 031 - Snuke the Phantom Thief | A museum exhibits N jewels, Jewel 1, 2, ..., N. The coordinates of Jewel i are (x_i, y_i) (the museum can be regarded as a two-dimensional plane), and the value of that jewel is v_i.
Snuke the thief will steal some of these jewels.
There are M conditions, Condition 1, 2, ..., M, that must be met when stealing jewels,... | ```python
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
from bisect import bisect_left,bisect_right
class MinCostFlow:
def __init__(self,n):
self.n=n
self.edges=[[] for i in range(n)]
def add_edge(self,fr,to,cap,cost):
self.edges[fr].append([to,cap,cost,len(self.edges... |
p03245 AtCoder Beginner Contest 111 - Robot Arms | Snuke is introducing a robot arm with the following properties to his factory:
* The robot arm consists of m sections and m+1 joints. The sections are numbered 1, 2, ..., m, and the joints are numbered 0, 1, ..., m. Section i connects Joint i-1 and Joint i. The length of Section i is d_i.
* For each section, its mode ... | ```python
N = int(input())
point = [tuple(map(int, input().split())) for i in range(N)]
point_farthest = max(point, key=lambda p: abs(p[0]) + abs(p[1]))
mod = sum(point_farthest) % 2
D = [1, 1] if mod == 0 else [1]
while sum(D) < abs(point_farthest[0]) + abs(point_farthest[1]):
D.append(D[-1] * 2)
D.reverse()
W = [... |
p03563 AtCoder Beginner Contest 076 - Rating Goal | Takahashi is a user of a site that hosts programming contests.
When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows:
* Let the current rating of the user be a.
* Suppose that the performance of the user in the contest is b.
... | ```python
r=float(input())
g=float(input())
print(int(2*g-r))
``` |
p03718 AtCoder Regular Contest 074 - Lotus Leaves | There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there ... | ```python
"""
https://atcoder.jp/contests/arc074/tasks/arc074_d
適当に最小カットを求めればいい
→縦横を別ノードで持っておいてつなぐ
0~99 列
100~199 横
200 = start
201 = goal
"""
from collections import defaultdict
from collections import deque
def Ford_Fulkerson_Func(s,g,lines,cost):
N = len(cost)
ans = 0
queue = deque([ [s,float("i... |
p03878 CODE FESTIVAL 2016 Grand Final(Parallel) - 1D Matching | There are N computers and N sockets in a one-dimensional world. The coordinate of the i-th computer is a_i, and the coordinate of the i-th socket is b_i. It is guaranteed that these 2N coordinates are pairwise distinct.
Snuke wants to connect each computer to a socket using a cable. Each socket can be connected to onl... | ```python
mod = 10 ** 9 + 7
N, *E = map(int, open(0).read().split())
E = sorted((e, 2 * (i < N) - 1) for i, e in enumerate(E))
res = 1
cnt = 0
for _, delta in E:
if cnt * delta < 0:
res *= abs(cnt)
res %= mod
cnt += delta
print(res)
``` |
p04039 AtCoder Regular Contest 058 - Iroha's Obsession | Iroha is very particular about numbers. There are K digits that she dislikes: D_1, D_2, ..., D_K.
She is shopping, and now paying at the cashier. Her total is N yen (the currency of Japan), thus she has to hand at least N yen to the cashier (and possibly receive the change).
However, as mentioned before, she is very ... | ```python
n, k = map(int, input().split())
checker = list(map(str, input().split()))
cont = True
while cont:
keep = True
for nn in str(n):
if nn in checker:
keep = False
break
if keep: break
n += 1
print(n)
``` |
p00120 Patisserie | The cake shop made a lot of roll cakes of various sizes. You have been tasked with arranging this cake in a box.
The roll cake is so soft that it will collapse if another roll cake is on top. Therefore, as shown in Fig. (A), all roll cakes must be arranged so that they touch the bottom of the box. Sorting also changes... | ```python
from collections import deque
def calcwidth(cks):
if len(cks) == 1: return cks[0]*2
width = cks[0] + cks[-1]
for ck1,ck2 in zip(cks[:-1],cks[1:]):
width += ((ck1+ck2)**2-(ck1-ck2)**2)**0.5
return width
while True:
try: W, *rs = list(map(float,input().split()))
except: break
... |
p00253 Kitchen Garden | I decided to plant vegetables in the vegetable garden. There were n seeds, so I sown n seeds one by one a day over n days. All seeds sprout and grow quickly. I can't wait for the harvest time.
One day, when I was watering the seedlings as usual, I noticed something strange. There should be n vegetable seedlings, but o... | ```python
from sys import exit
while(True):
N = int(input())
# print(N)
if N == 0:
break
h = list(map(int, input().split()))
for i in range(N+1):
targ = h[:i] + h[i+1:]
diff = targ[1] - targ[0]
OK = True
for j in range(1, N):
if diff != targ[j] - t... |
p00439 Maximum Sum | problem
Given a sequence of n integers a1, a2, ..., an and a positive integer k (1 ≤ k ≤ n), then the sum of k consecutive integers Si = ai + ai + Create a program that outputs the maximum value of 1 + ... + ai + k-1 (1 ≤ i ≤ n --k + 1).
input
The input consists of multiple datasets. Each dataset is given in the f... | ```python
while True:
n , k = map(int,input().split())
if (n,k) == (0,0): break
a = [int(input()) for _ in range(n)]
s = sum(a[0:k])
l = [s]
for i in range(k,n):
s = s + a[i] - a[i-k]
l.append(s)
print(max(l))
``` |
p00630 CamelCase | When naming identifiers (variables and functions) in programming, compound words that concatenate words are used. However, if you concatenate them as they are, you will not be able to understand the word breaks, so in general, select and apply the one that is unified from the following naming conventions:
* Set to Upp... | ```python
while True:
name,typ = input().split()
if typ=="X": break
ans = []
if "_" in name:
ans = name.split("_")
else:
j = 0
for i in range(1,len(name)):
if name[i].isupper():
ans.append(name[j:i])
j = i
ans.append(n... |
p00774 Chain Disappearance Puzzle | Chain Disappearance Puzzle
We are playing a puzzle. An upright board with H rows by 5 columns of cells, as shown in the figure below, is used in this puzzle. A stone engraved with a digit, one of 1 through 9, is placed in each of the cells. When three or more stones in horizontally adjacent cells are engraved with the... | ```python
from functools import lru_cache
def DEBUG(*args): pass # print('@', *args)
@lru_cache(maxsize=None)
def pat(s, n):
return ' '.join([s] * n)
DEBUG(pat('1', 3))
def removeAll(xs, s):
while s in xs:
xs.remove(s)
xs.append('#')
return xs
def lmap(f, s): return list(map(f, s))... |
p00905 Stylish | Stylish is a programming language whose syntax comprises names, that are sequences of Latin alphabet letters, three types of grouping symbols, periods ('.'), and newlines. Grouping symbols, namely round brackets ('(' and ')'), curly brackets ('{' and '}'), and square brackets ('[' and ']'), must match and be nested pro... | ```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 = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x in ... |
p01172 Headstrong Student | You are a teacher at a cram school for elementary school pupils.
One day, you showed your students how to calculate division of fraction in a class of mathematics. Your lesson was kind and fluent, and it seemed everything was going so well - except for one thing. After some experiences, a student Max got so curious ab... | ```python
def gcd(a,b):
while b:a,b=b,a%b
return a
def f(n,m):
if m==1:return 0
x=1
for i in range(m):
x=(x*n)%m
if x==1:return i+1
while 1:
a,b=map(int,input().split())
if a==0:break
c=gcd(a,b)
a//=c;b//=c
cnt=0;d=gcd(b,10)
while d!=1:
b//=d... |
p01308 Angel Stairs | An angel lives in the clouds above the city where Natsume lives. The angel, like Natsume, loves cats and often comes down to the ground to play with cats. To get down to the ground, the angel made a long, long staircase leading from the clouds to the ground. However, the angel thought that it would be boring to just go... | ```python
dic = {"C":0, "C#":1, "D":2, "D#":3,
"E":4, "F":5, "F#":6, "G":7,
"G#":8, "A":9, "A#":10, "B":11}
t = int(input())
for _ in range(t):
n, m = map(int, input().split())
t_lst = [-100] + list(map(lambda x:dic[x],input().split()))
s_lst = list(map(lambda x:dic[x],input().split()))
s_lst.reve... |
p01789 Unfair Game | Example
Input
3 5 4
3
6
12
Output
Hanako | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def check(N, A, B, S):
K = min(A, B)
g = 0
for s in S:
g ^= s % (K+1)
if A == B:
return g != 0
if A > B:
if g != 0:
return 1
for s in S:
if s > B:
retu... |
p01924 Coastline | coastline
Waves rush to the beach every second. There is data that observes and records how many meters the wave rushed beyond the reference point P every second for only T seconds. The data consists of T integers x1, ..., xT, and for each i (1 ≤ i ≤ T), a wave from point P to the point exactly xi m rushes in i second... | ```python
while True:
t,d,l=map(int,input().split())
if t==0:
break
ls=[]
for i in range(t):
ls.append(int(input()))
ans=0
r=0
for j in range(t):
if ls[j]>=l:
ans+=1
if r<d:
r=d-1
else:
if r>0:
... |
p02062 Short Circuit Evaluation | C: Short-circuit evaluation
problem
Naodai-kun and Hokkaido University-kun are playing games. Hokkaido University first generates the following logical formula represented by BNF.
<formula> :: = <or-expr>
<or-expr> :: = <and-expr>
| <or-expr> "|" <and-expr>
<and-expr> :: = <term>
| <and-expr> "&" <term>
<term> :: =... | ```python
# from inspect import currentframe
# from sys import exit, stderr
# debug function
# def debug(*args):
# names = {id(v):k for k,v in currentframe().f_back.f_locals.items()}
# print(', '.join(names.get(id(arg),'???') + str(id(arg)) +' = '+repr(arg) for arg in args), file=stderr)
src = list(str(inpu... |
p02204 Contest T-shirts | Contest T-shirts
Segtree has $ M $ contest T-shirts.
He decided to spend $ N $ days on the contest T-shirt alone, and told $ i = 1, 2, 3, \ dots, N $ "$ A_i $ T-shirt on the $ i $ day." I made a plan for $ N $ to wear.
However, if you keep the current plan, you may not be able to do the laundry in time, so I would l... | ```python
m,n = map(int,input().split())
a = list(map(int,input().split()))
if m == 2:
ans = n
for i in range(2):
t = 0
for j in range(n):
idx = (i+j)%2 + 1
if idx != a[j]:
t += 1
ans = min(ans, t)
else:
ans = 0
prev = a[0]
for i in ra... |
p02358 Union of Rectangles | Given a set of $N$ axis-aligned rectangles in the plane, find the area of regions which are covered by at least one rectangle.
Constraints
* $ 1 \leq N \leq 2000 $
* $ −10^9 \leq x1_i < x2_i\leq 10^9 $
* $ −10^9 \leq y1_i < y2_i\leq 10^9 $
Input
The input is given in the following format.
$N$
$x1_1$ $y1_1$ $x2_1$ ... | ```python
from itertools import accumulate
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
def main():
N = int(input())
xs = set()
ys = set()
rect = []
for _ in range(N):
x1, y1, x2, y2 = map(int, input().split())
xs.add(x1)
xs.add(x2)
y... |
1013_B. And | There is an array with n elements a1, a2, ..., an and the number x.
In one operation you can select some i (1 ≤ i ≤ n) and replace element ai with ai & x, where & denotes the [bitwise and](https://en.wikipedia.org/wiki/Bitwise_operation#AND) operation.
You want the array to have at least two equal elements after appl... | ```python
from sys import stdin,stdout
a,b=map(int,stdin.readline().split())
z=set(map(int,stdin.readline().split()))
if len(z)!=a:stdout.write("0");exit()
r=set()
for i in z:
if i&b in z and i&b!=i:stdout.write("1");exit()
r.add(i&b)
if len(r)!=a:stdout.write("2");exit()
stdout.write("-1")
``` |
1060_D. Social Circles | You invited n guests to dinner! You plan to arrange one or more circles of chairs. Each chair is going to be either occupied by one guest, or be empty. You can make any number of circles.
Your guests happen to be a little bit shy, so the i-th guest wants to have a least l_i free chairs to the left of his chair, and a... | ```python
import heapq
n=int(input())
fa=[i for i in range(n)]
ls=[]
rs=[]
for i in range(n):
l,r=[int(x) for x in input().split()]
ls.append((l,i))
rs.append((r,i))
ls.sort()
rs.sort()
ans=n
for i in range(n):
ans+=max(ls[i][0],rs[i][0])
# heapq.heapify(ls)
# heapq.heapify(rs)
#
# ans=n
# if n==1:
# ... |
1082_B. Vova and Trophies | Vova has won n trophies in different competitions. Each trophy is either golden or silver. The trophies are arranged in a row.
The beauty of the arrangement is the length of the longest subsegment consisting of golden trophies. Vova wants to swap two trophies (not necessarily adjacent ones) to make the arrangement as ... | ```python
from sys import stdin
input=stdin.readline
n=int(input())
s="a"+input().rstrip()
l=[0]*(n+1)
r=[0]*(n+1)
cnt_g=0
for i in range(len(s)):
if s[i]=="G":
cnt_g+=1
if n==cnt_g:
print(n)
exit()
for i in range(1,n+1):
if s[i]=="G":
l[i]=r[i]=1
for i in range(1,n+1):
if s[i]=="G" and s[i-1]=="G":
... |
1101_D. GCD Counting | You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to a_i.
Let's denote the function g(x, y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also ... | ```python
from sys import stdin, stdout
from math import *
from heapq import *
from collections import *
dv=list(range(200002))
for i in range(2,200002):
if ((i*i)>=200002):
break
if (dv[i]==i):
j=i
while ((i*j)<200002):
dv[i*j]=i
j=j+1
def loPr(x):
global d... |
112_B. Petya and Square | Little Petya loves playing with squares. Mum bought him a square 2n × 2n in size. Petya marked a cell inside the square and now he is solving the following task.
The task is to draw a broken line that would go along the grid lines and that would cut the square into two equal parts. The cutting line should not have any... | ```python
n,x,y=map(int,input().split())
a=[(n//2),(n//2)+1]
print(['YES','NO'][x in a and y in a])
``` |
114_C. Grammar Lessons | Petya got interested in grammar on his third year in school. He invented his own language called Petya's. Petya wanted to create a maximally simple language that would be enough to chat with friends, that's why all the language's grammar can be described with the following set of rules:
* There are three parts of sp... | ```python
import re
def f(x):
if x.endswith("lios"): return 1
elif x.endswith("liala"): return -1
elif x.endswith("etr"): return 2
elif x.endswith("etra"): return -2
elif x.endswith("initis"):return 3
elif x.endswith("inites"): return -3
else: return 0
a,b=input().strip().split(),[]
for s ... |
1189_F. Array Beauty | Let's call beauty of an array b_1, b_2, …, b_n (n > 1) — min_{1 ≤ i < j ≤ n} |b_i - b_j|.
You're given an array a_1, a_2, … a_n and a number k. Calculate the sum of beauty over all subsequences of the array of length exactly k. As this number can be very large, output it modulo 998244353.
A sequence a is a subsequenc... | ```python
from collections import defaultdict
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998... |
1227_F1. Wrong Answer on test 233 (Easy Version) | Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the easier version of the problem. In this version 1 ≤ n ≤ 2000. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing n one-choice-questions. Each of the questions contains k options... | ```python
n,k=[int(kk) for kk in input().strip().split(" ")]
h=[int(kk) for kk in input().strip().split(" ")]
fact=[1]*(n+1)
mod=998244353
for i in range(1,n+1):
fact[i]=(fact[i-1]*i)%mod
def inv(x):
return pow(x,mod-2,mod)
def C(n,k):
return (fact[n]*inv(fact[k])*inv(fact[n-k]))%mod
ng=0
for i in... |
1292_B. Aroma's Search | [THE SxPLAY & KIVΛ - 漂流](https://soundcloud.com/kivawu/hyouryu)
[KIVΛ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives)
With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space.
The space can be considered a 2D plane,... | ```python
"""
Satwik_Tiwari ;) .
12th july , 2020 - Sunday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import ... |
1312_C. Adding Powers | Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can:
* either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i;
* or not choose any posit... | ```python
def convert(n, base):
a = "01"
if n < base:
if n % base >= 2:
return False
return a[n % base]
else:
if n % base >= 2:
return False
x = convert(n // base, base)
if x:
return x + a[n % base]
return False
t = int(in... |
1355_B. Young Explorers | Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | ```python
for i in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
l.sort()
i1,i2=1,0
for j in l:
if j==i1:
i2+=1
i1=0
i1+=1
print(i2)
``` |
1375_A. Sign Flipping | You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold:
1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea... | ```python
#!/usr/bin/env python3
def ans(A):
A = [abs(a) for a in A]
for i in range(1, len(A), 2):
if i+1 < len(A):
[p, q, r] = A[i-1:i+2]
if p <= q <= r: A[i] = -A[i]
elif p >= q >= r: A[i] = -A[i]
return ' '.join([str(a) for a in A])
T = int(input())
for _ in... |
1398_D. Colored Rectangles | You are given three multisets of pairs of colored sticks:
* R pairs of red sticks, the first pair has length r_1, the second pair has length r_2, ..., the R-th pair has length r_R;
* G pairs of green sticks, the first pair has length g_1, the second pair has length g_2, ..., the G-th pair has length g_G;
* B ... | ```python
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
from functools import lru_cach... |
1421_E. Swedish Heroes | While playing yet another strategy game, Mans has recruited n [Swedish heroes](https://www.youtube.com/watch?v=5sGOwFVUU0I), whose powers which can be represented as an array a.
Unfortunately, not all of those mighty heroes were created as capable as he wanted, so that he decided to do something about it. In order to ... | ```python
n = int(input())
a = list(map(int,input().split()))
INF = 10 ** 20
DP = [-INF] * 12
DP[1] = a[0]
DP[5] = -a[0]
for elem in a[1:]:
newDP = []
newDP.append(DP[5] + elem)
newDP.append(DP[3] + elem)
newDP.append(DP[4] + elem)
newDP.append(DP[1] - elem)
newDP.append(DP[2] - elem)
newDP.... |
143_D. Help General | Once upon a time in the Kingdom of Far Far Away lived Sir Lancelot, the chief Royal General. He was very proud of his men and he liked to invite the King to come and watch drill exercises which demonstrated the fighting techniques and tactics of the squad he was in charge of. But time went by and one day Sir Lancelot h... | ```python
n, m = map(int, input().split())
if n > m:
n, m = m, n
if n > 2 and m > 2:
print(((n * m) + 1) // 2)
elif n == 1:
print(m)
else:
print(2 * (((m // 4) * 2) + min(m % 4, 2)))
# Made By Mostafa_Khaled
``` |
1491_C. Pekora and Trampoline | There is a trampoline park with n trampolines in a line. The i-th of which has strength S_i.
Pekora can jump on trampolines in multiple passes. She starts the pass by jumping on any trampoline of her choice.
If at the moment Pekora jumps on trampoline i, the trampoline will launch her to position i + S_i, and S_i wi... | ```python
#region Header
#!/usr/bin/env python3
# from typing import *
import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq
def input():
return sys.stdin.readline()[:-1]
# sys.setrecursionlimit(1000000)
#endregion
# _INPUT = """4
# 18
# 6 6 5 4 3 3 3 2... |
1513_F. Swapping Problem | You are given 2 arrays a and b, both of size n. You can swap two elements in b at most once (or leave it as it is), and you are required to minimize the value $$$∑_{i}|a_{i}-b_{i}|.$$$
Find the minimum possible value of this sum.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line c... | ```python
# Codeforces - 1513-F (https://codeforces.com/problemset/problem/1513/F)
n = int(input())
a = [int(val) for val in input().split()]
b = [int(val) for val in input().split()]
# step 1: partition
s = []
t = []
for i in range(n):
if a[i] < b[i]:
s.append((a[i], b[i]))
elif a[i] > b[i]:
t.append((b... |
189_B. Counting Rhombi | You have two positive integers w and h. Your task is to count the number of rhombi which have the following properties:
* Have positive area.
* With vertices at integer points.
* All vertices of the rhombi are located inside or on the border of the rectangle with vertices at points (0, 0), (w, 0), (w, h), (0,... | ```python
w,h=map(int,input().split())
ans=0
for i in range(2,w+1,2):
for j in range(2,h+1,2):
ans+=(w+1-i)*(h+1-j)
print(ans)
``` |
236_B. Easy Number Challenge | Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum:
<image>
Find the sum modulo 1073741824 (230).
Input
The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 100).
Output
Print a singl... | ```python
a,b,c=map(int,input().split())
M=1073741824
n=a*b*c
d=[1]*(n+1)
for i in range(2,n+1):
for j in range(i,n+1,i):
d[j]+=1
r=0
for i in range(1,a+1):
for j in range(1,b+1):
for k in range(1,c+1):
r+=(d[i*j*k])%M
print(r%M)
``` |
355_C. Vasya and Robot | Vasya has n items lying in a line. The items are consecutively numbered by numbers from 1 to n in such a way that the leftmost item has number 1, the rightmost item has number n. Each item has a weight, the i-th item weights wi kilograms.
Vasya needs to collect all these items, however he won't do it by himself. He us... | ```python
path = list(map(int, input().split()))
n, L, R, QL, QR = path[0], path[1], path[2], path[3], path[4]
w = list(map(int, input().split()))
sumpref = [0]
for i in range(1, n + 1) :
sumpref.append(w[i - 1] + sumpref[i - 1])
answer = QR * (n - 1) + sumpref[n] * R
for i in range(1, n + 1) :
energy = L * ... |
379_D. New Year Letter | Many countries have such a New Year or Christmas tradition as writing a letter to Santa including a wish list for presents. Vasya is an ordinary programmer boy. Like all ordinary boys, he is going to write the letter to Santa on the New Year Eve (we Russians actually expect Santa for the New Year, not for Christmas).
... | ```python
def main():
k, x, n, m = map(int, input().split())
def f(s, e, n, cnt):
ret = [""] * n
ret[0] = s
ret[-1] = e
sa = 0 if s == 'A' else 1
for i in range(cnt):
ret[sa] = 'A'
ret[sa + 1] = 'C'
sa += 2
for j in range(s... |
426_B. Sereja and Mirroring | Let's assume that we are given a matrix b of size x × y, let's determine the operation of mirroring matrix b. The mirroring of matrix b is a 2x × y matrix c which has the following properties:
* the upper half of matrix c (rows with numbers from 1 to x) exactly matches b;
* the lower half of matrix c (rows with n... | ```python
string_input = input().split(" ")
n, m = int(string_input[0]), int(string_input[1])
matrix = []
row = n
for i in range(0, n):
matrix.append(input())
while True:
if n % 2 == 1:
break
else:
row_flag = 1
n = n//2
for i in range(0, n):
if matrix[i] != matrix... |
44_E. Anfisa the Monkey | Anfisa the monkey learns to type. She is yet unfamiliar with the "space" key and can only type in lower-case Latin letters. Having typed for a fairly long line, Anfisa understood that it would be great to divide what she has written into k lines not shorter than a and not longer than b, for the text to resemble human s... | ```python
k,a,b=map(int,input().split())
ss=input()
h=len(ss)
q,r=divmod(h,k)
if q<a or q>b or (q==b and r>0):
print('No solution')
else:
i=0
while r>0:
print(ss[i:i+q+1])
r-=1
i=i+q+1
while i<h:
print(ss[i:i+q])
i=i+q
``` |
471_A. MUH and Sticks | Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
... | ```python
a = list(map(int,input().split()))
for i in range(6):
if a.count(a[i])>=4:
v = a[i]
break
else:
print("Alien")
exit()
for i in range(4):
a.remove(v)
a.sort()
if a[0]<a[1]:
print("Bear")
elif a[0]==a[1]:
print("Elephant")
else:
print("Alien")
``` |
495_B. Modular Equations | Last week, Hamed learned about a new type of equations in his math class called Modular Equations. Lets define i modulo j as the remainder of division of i by j and denote it by <image>. A Modular Equation, as Hamed's teacher described, is an equation of the form <image> in which a and b are two non-negative integers a... | ```python
a, b = map(int, input().split())
if a == b:
print ('infinity')
elif b > a:
print (0)
else:
a -= b
i = 1
cont = 0
while (i*i) <= a:
if (a % i) == 0:
if i > b:
cont += 1
if (a/i) > b and (i*i) != a:
cont += 1
i += 1
print (cont)
... |
519_E. A and B and Lecture Rooms | A and B are preparing themselves for programming contests.
The University where A and B study is a set of rooms connected by corridors. Overall, the University has n rooms connected by n - 1 corridors so that you can get from any room to any other one by moving along the corridors. The rooms are numbered from 1 to n.
... | ```python
from collections import defaultdict as df
from collections import deque
import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b"": x if type(x) is bytes else _str(x).encode()
BUFSIZE = 8192
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwa... |
546_A. Soldier and Bananas | A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | ```python
price = 0
iter = 1
k,n,w = list(map(int,input().split()))
for i in range (w):
price += k*iter
iter += 1
if price <= n:
print(0)
else:
output = price - n
print(output)
``` |
572_C. Lengthening Sticks | You are given three sticks with positive integer lengths of a, b, and c centimeters. You can increase length of some of them by some positive integer number of centimeters (different sticks can be increased by a different length), but in total by at most l centimeters. In particular, it is allowed not to increase the l... | ```python
a, b, c, l = map(int, input().split())
ans = (l + 3) * (l + 2) * (l + 1) // 3
for z in (a, b, c):
s = 2 * z - a - b - c
for x in range(max(0, -s), l + 1):
m = min(s + x, l - x)
ans -= (m + 1) * (m + 2)
print(ans // 2)
# Made By Mostafa_Khaled
``` |
594_A. Warrior and Archer | In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.
V... | ```python
n = int(input())
x = sorted(list(map(int, input().split())))
print(min([x[i + n // 2] - x[i] for i in range(n // 2)]))
``` |
615_D. Multipliers | Ayrat has number n, represented as it's prime factorization pi of size m, i.e. n = p1·p2·...·pm. Ayrat got secret information that that the product of all divisors of n taken modulo 109 + 7 is the password to the secret data base. Now he wants to calculate this value.
Input
The first line of the input contains a sing... | ```python
MD = 1000000007
m = int(input())
p = list(map(int, input().split()))
q = {}
for el in p:
if el in q:
q[el] += 1
else:
q[el] = 2
sum1 = 1
sum2 = 1
for el in q:
sum1=sum1*q[el]
sum2=sum2*pow(el,(q[el]-1),MD)
sum=pow(sum2,sum1//2,MD)
if sum1 % 2 == 1:
for el in q:
sum ... |
634_F. Orchestra | Paul is at the orchestra. The string section is arranged in an r × c rectangular grid and is filled with violinists with the exception of n violists. Paul really likes violas, so he would like to take a picture including at least k of them. Paul can take a picture of any axis-parallel rectangle in the orchestra. Count ... | ```python
r, c, n, k = map(int, input().split())
board = [[0 for col in range(c)] for row in range(r)]
for i in range(n):
x, y = map(lambda x: int(x)-1, input().split())
board[x][y] = 1
photos = 0
for x1 in range(r):
for y1 in range(c):
for x2 in range(x1, r):
for y2 in range(y1, c):
... |
688_B. Lovely Palindromes | Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | ```python
n = input()
print(n + "".join(reversed(list(n))))
``` |
710_A. King Moves | The only king stands on the standard chess board. You are given his position in format "cd", where c is the column from 'a' to 'h' and d is the row from '1' to '8'. Find the number of moves permitted for the king.
Check the king's moves here https://en.wikipedia.org/wiki/King_(chess).
<image> King moves from the posi... | ```python
import sys
from collections import Counter
from math import factorial
input = sys.stdin
output = sys.stdout
# input = open('input.txt')
def read_int():
return [int(x) for x in input.readline().rstrip().split()]
line = input.readline().rstrip()
x = ord(line[0]) - ord('a')
y = ord(line[1]) - ord('1')
a... |
731_A. Night at the Museum | Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | ```python
import sys
from math import ceil,log
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] f... |
755_C. PolandBall and Forest | PolandBall lives in a forest with his family. There are some trees in the forest. Trees are undirected acyclic graphs with k vertices and k - 1 edges, where k is some integer. Note that one vertex is a valid tree.
There is exactly one relative living in each vertex of each tree, they have unique ids from 1 to n. For e... | ```python
n = int(input())
a = [0] + list(map(int, input().split()))
was = set()
for i in range(1, n + 1):
if a[a[i]] == i:
was.add(min(i, a[i]))
print(len(was))
``` |
776_D. The Door Problem | Moriarty has trapped n people in n distinct rooms in a hotel. Some rooms are locked, others are unlocked. But, there is a condition that the people in the hotel can only escape when all the doors are unlocked at the same time. There are m switches. Each switch control doors of some rooms, but each door is controlled by... | ```python
import sys
from math import inf
time = 0
cc = 0
l = {}
d = {}
f = {}
conn_comp = {}
on_stack = {}
stack = []
color = []
def tarjan(graph):
global l
global d
global f
global pi
global stack
global on_stack
l = {key : inf for key in graph}
d = {key : -1 for key in graph}
f... |
7_E. Defining Macros | Most C/C++ programmers know about excellent opportunities that preprocessor #define directives give; but many know as well about the problems that can arise because of their careless use.
In this problem we consider the following model of #define constructions (also called macros). Each macro has its name and value. T... | ```python
P, A, S, M, D = 1, 2, 4, 8, 16
ADD = A | S
ANY = A | S | M | D
OP_BIT = {"+": A, "-": S, "*": M, "/": D, ")": 0}
UNSAFE_BEFORE = {P: 0, A: 0, S: ADD, M: ADD, D: ANY}
UNSAFE_AFTER = {P: 0, A: 0, S: 0, M: ADD, D: ADD}
macro = dict()
def expr(chars,
pseudo=P,
expand=macro.get,
op_bit=O... |
821_B. Okabe and Banana Trees | Okabe needs bananas for one of his experiments for some strange reason. So he decides to go to the forest and cut banana trees.
Consider the point (x, y) in the 2D plane such that x and y are integers and 0 ≤ x, y. There is a tree in such a point, and it has x + y bananas. There are no trees nor bananas in other point... | ```python
m,b=map(int,input().split())
f=lambda n: n*(n+1)//2
def g(y):
x=m*(b-y)
return f(x)*(y+1)+f(y)*(x+1)
print(max(g(y) for y in range(b+1)))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.