problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 1 | k = int(raw_input())
l = int(raw_input())
m = int(raw_input())
n = int(raw_input())
d = int(raw_input())
divisionList = [k, l, m, n]
divisionList.sort()
if divisionList[0] == 1:
print d
else:
refinedList = []
refinedList.append(divisionList[0])
if divisionList[1] % divisionList[0] != 0:
refin... |
Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows:
* Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `888888... | 3 | s,k,p=list(input()),int(input())-1,0
while s[p]=='1' and k:
k -= 1
p += 1
print(s[p]) |
Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a n× m grid (rows are numbered from 1 to n, and columns are nu... | 3 | import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s); sys.stdout.write('\n')
def wi(n): sys.stdout.write(str(n)); sys.stdout.write('\n')
def wia(a, sep=' '): sys.stdout.write(sep... |
You are given a complete undirected graph with n vertices. A number ai is assigned to each vertex, and the weight of an edge between vertices i and j is equal to ai xor aj.
Calculate the weight of the minimum spanning tree in this graph.
Input
The first line contains n (1 ≤ n ≤ 200000) — the number of vertices in th... | 1 | import sys
range = xrange
input = raw_input
n = int(input())
A = [int(x) for x in input().split()]
A.sort()
### Tree
L = [-1, -1]
val = [0, 0]
def check(ind):
if L[ind] == -1:
L[ind] = len(L)
L.append(-1)
L.append(-1)
val.append(-1)
val.append(-1)
def add(i, ind, bit):
... |
Snuke is buying a bicycle. The bicycle of his choice does not come with a bell, so he has to buy one separately.
He has very high awareness of safety, and decides to buy two bells, one for each hand.
The store sells three kinds of bells for the price of a, b and c yen (the currency of Japan), respectively. Find the m... | 3 | print(sum(sorted([int(tok) for tok in input().split()])[:2])) |
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly.
In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ... | 3 | def main():
for _ in range(int(input())):
n,k=map(int,input().split())
l=list(map(int,input().split()))
a,b=max(l),min(l)
if (a-b)<=2*k:
print(b+k)
else:
print(-1)
return
main()
|
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ... | 3 | N=int(input())
S=input()
a=[]
for i in range(N):
a.append(len(set(S[0:i])&set(S[i:N])))
print(max(a))
|
We have N+1 integers: 10^{100}, 10^{100}+1, ..., 10^{100}+N.
We will choose K or more of these integers. Find the number of possible values of the sum of the chosen numbers, modulo (10^9+7).
Constraints
* 1 \leq N \leq 2\times 10^5
* 1 \leq K \leq N+1
* All values in input are integers.
Input
Input is given from S... | 3 | N, K = map(int,input().split())
ans = 0
for i in range(K,N+2):
ans += (2*N+1-i)*i//2-(i-1)*i//2+1
print(ans%(10**9+7)) |
The spring is coming and it means that a lot of fruits appear on the counters. One sunny day little boy Valera decided to go shopping. He made a list of m fruits he wanted to buy. If Valera want to buy more than one fruit of some kind, he includes it into the list several times.
When he came to the fruit stall of Ash... | 1 | d=raw_input()
d=d.split()
d[0]=int(d[0])
d[1]=int(d[1])
x=raw_input()
x=x.split()
hres=0
sres=0
v=['']*d[1]
for i in range(0,len(x)):
x[i]=int(x[i])
for i in range(0,d[1]):
v[i]=raw_input()
v=sorted(v)
s=1
g=''
for i in range(1,len(v)):
if(v[i-1]==v[i]):
s=s+1
if(v[i-1]!=v[i]):
... |
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b.
Can you reconst... | 3 | a,b = list(map(int,input().split()))
if a > b or b - a > 1:
if a == 9 and b == 1:
print(9,10)
else:
print(-1)
else:
if a == b:
print(a*10, a*10 + 1)
else:
print(a, b) |
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya was delivered a string s, containing only digits. He needs to find a string that
* ... | 1 | import sys
import math
def readints() :
l = sys.stdin.readline()
return map(int, l.split(' '))
def readstring() :
l = sys.stdin.readline()[:-1]
return l
def readint() :
l = sys.stdin.readline()
return int(l)
def clearchars(s, chars) :
for c in chars :
s = s.replace(c, '')
ret... |
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... | 3 | ############ ---- Input Functions ---- ############
import sys
def readInt():
return(int(input()))
def readList(op):
return sorted(list(map(op, sys.stdin.readline().strip().split(' '))))
def readString():
s = input()
return s
def readInts():
return(map(int,input().rstrip().split()))
t = readInt()
f... |
Bessie the cow and her best friend Elsie each received a sliding puzzle on Pi Day. Their puzzles consist of a 2 × 2 grid and three tiles labeled 'A', 'B', and 'C'. The three tiles sit on top of the grid, leaving one grid cell empty. To make a move, Bessie or Elsie can slide a tile adjacent to the empty cell into the em... | 1 | from collections import deque
def bfs(start, end):
Q = deque([start])
visited = set()
while Q:
c = Q.popleft()
if c in visited:
continue
visited.add(c)
if c == end:
return 'YES'
if c[0][0] == 0:
Q.append(((c[0][1], c[0][0]),
... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 |
def is_composite(n):
if n==1 or n==2 or n==3:
return False
elif n%6 == 5 or n%6 == 1:
i=2
while(i<int((n+1)/2)):
if n%i==0:
return True
i+=1
return False
else :
return True
n = int(input())
num = int(n/2)
#smaller
w = Non... |
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m... | 3 | def my_log(num):
ans = 0
while not num % 2:
num //= 2
ans += 1
return ans if num == 1 else -1
n = int(input())
for i in range(n):
a, b = map(int, input().split())
a, b = max(a, b), min(a, b)
if not a % b:
pot = my_log(a // b)
if pot >= 0:
ans = 0
... |
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | N=int(input())
li=[int(i) for i in input().split()]
li1=set(li)
if 0 in li1:
li1.remove(0)
print(len(li1))
|
You are given a string s consisting of n lowercase Latin letters. n is even.
For each position i (1 ≤ i ≤ n) in string s you are required to change the letter on this position either to the previous letter in alphabetic order or to the next one (letters 'a' and 'z' have only one of these options). Letter in every posi... | 3 | t=int(input())
while t:
t-=1
n=int(input())
s=input()
flag=1
for i in range(0,int(n/2)):
if(abs(ord(s[i])-ord(s[n-i-1]))!=2 and abs(ord(s[i])-ord(s[n-i-1]))!=0):
flag=0
if(flag):
print("YES")
else:
print("NO")
|
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties:
* In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z... | 3 | n = int(input())
s = list(map(int,input().split()))
s = list(set(s))
if 0 in s: print(len(s)-1)
else: print(len(s))
|
ABC Gene
There is a gene sequence represented by the string `ABC`. You can rewrite this gene sequence by performing the following operations several times.
* Choose one of the letters `A`,` B`, `C`. Let this be x. Replace all x in the gene sequence with `ABC` at the same time.
Given a string S consisting only of `... | 3 | target=input()
list_abc=["A","B","C"]
old=[]
new=[]
check=[]
flag=False
if "ABC" in target:
old.append([target,[]])
while old !=[] and flag==False:
for i in old:
if i[0]=="ABC":
check.append(i[1])
flag=True
break
for j in list_abc:
element=i[0].rep... |
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there.
At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one... | 3 | N = int(input())
mins = []
maxs = []
for i in range(3):
mi, ma = map(int, input().split())
mins.append(mi)
maxs.append(ma)
anss = list(mins)
rem = N - sum(anss)
for i in range(3):
if rem >= 0:
add = min(rem, maxs[i] - mins[i])
rem -= add
anss[i] += add
print(" ".join(map(str, an... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | import sys
length = int(input())
thing = input()
thing = [int(x) for x in thing.split()]
thing.sort()
for num in thing:
print(num,end=" ") |
You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion i... | 3 | n = int(input())
l = list(map(int, input().split()))
inv = 0
out = 0
mult = 1
for i in range(32):
curr = dict()
opp = 0
same = 0
for v in l:
if v ^ 1 in curr:
if v & 1:
opp += curr[v ^ 1]
else:
same += curr[v ^ 1]
if ... |
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar... | 3 | a=int(input())
for i in range(a):
b=int(input())
if (b-5)%3==0 and b-5>=0:
print((b-5)//3,1,0)
elif (b-7)%3==0 and b-7>=0:
print((b-7)//3,0,1)
elif b%3==0:
print(b//3,0,0)
elif (b-3)%7==0 and b-3>=0:
print(1,0,(b-3)//7)
elif (b-5)%7==0 and b-5>=0:
print(0,... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | m = input()
print('YES' if ('0'*7 in m or '1'*7 in m) else 'NO')
|
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You ... | 3 |
import re
def isgood(item):
try:
if len(item) > 1 and item[0] == '0':
return False
val = int(item)
if val < 0:
return False
except ValueError:
return False
return True
s = input()
a, b = [], []
for x in re.split(',|;', s):
(a if isgood(x) e... |
The Hedgehog likes to give presents to his friend, but no less he likes to receive them.
Having received another present today, the Hedgehog suddenly understood that he has no place to put it as there was no room left on the special shelf in the cupboard. He will have to choose another shelf, but which one should he c... | 1 | #!/usr/bin/python
import sys
n, k = [int (x) for x in sys.stdin.readline ().split ()]
a = [int (x) for x in sys.stdin.readline ().split ()]
c, a = a[0], a[1:]
assert len (a) == c
a += [n + 1]
p = 0
res = 0
for b in a:
res += (b - p + k - 1) / k
p = b
print res - 1
|
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems.
This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to... | 3 | s= ''
for i in range(1, 1001):
s += str(i)
n = int(input())
print(s[n-1]) |
There are n persons who initially don't know each other. On each morning, two of them, who were not friends before, become friends.
We want to plan a trip for every evening of m days. On each trip, you have to select a group of people that will go on the trip. For every person, one of the following should hold:
* ... | 1 | n, m, k=map(int, raw_input().split())
edge=[map(int, raw_input().split()) for i in xrange(m)]
adj=[[] for i in xrange(n+1)]
deg=[0 for i in xrange(n+1)]
for x, y in edge:
adj[x]+=[y]
adj[y]+=[x]
deg[x]+=1
deg[y]+=1
q=[]
first=0
removed=set()
def bfs():
global first
while first<len(q):
cur=q[first]
first+=1
... |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | a = int(input())
while a < 1 or a > 10:
a = int(input())
b = int(input())
while b < 1 or b > 10:
b = int(input())
c = int(input())
while c < 1 or c > 10:
c = int(input())
s=a+b+c
if s<(a+b)*c:
s=(a+b)*c
if s<a*(b+c):
s=a*(b+c)
if s<a+b*c:
s=a+b*c
if s<a*b+c:
s=a*b+c
if s<a*b*c:
s=a*b*c
p... |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | number = int(input())
seq = input()
f_s = 0
s_f = 0
previous = seq[0]
for i in seq[1:]:
if i != previous:
if i == 'S':
f_s += 1
else:
s_f += 1
previous = i
if s_f > f_s:
print("YES")
else:
print("NO")
|
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | 3 | n,s=list(map(int,input().split()))
n1=(n+s-1)//n
print(n1)
|
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer!
Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher... | 1 | def clear(a):
s=""
for i in a:
if(i!='_' and i!=';' and i!='-'):
s+=i
return s.lower()
a={}
for i in range(3):
a[i]=clear(raw_input());
r={}
for i in range(27):
r[i]=None
for i in range(3):
for j in range(3):
if i!=j:
for k in range(3):
if... |
Bob has a permutation of integers from 1 to n. Denote this permutation as p. The i-th element of p will be denoted as pi. For all pairs of distinct integers i, j between 1 and n, he wrote the number ai, j = min(pi, pj). He writes ai, i = 0 for all integer i from 1 to n.
Bob gave you all the values of ai, j that he wro... | 3 | n = int(input())
s = []
for _ in range(n):
l = [int(b) for b in input().split()]
s.append(max(l))
i = s.index(max(s))
s[i] = n
for c in s:
print(f'{c}', end=' ')
|
n children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation a1, a2, ..., an of length n. It is an integer sequence such that each integer from 1 to n appears exactly once in it.
The game consists of m steps. On each step the current leader with index i counts out ai... | 3 | n, m = [int(number) for number in input().split()]
indices = [int(number) for number in input().split()]
res = [0] * (n+1)
kids = {i for i in range(1, n+1)}
current = indices[0]
flag = False
for i, index in enumerate(indices[1:]):
a = index - current if index > current else n - current + index
if a in ki... |
Alice has just learnt about primeStrings. A string is a primeString if the number of distinct alphabets used in the string is a prime and also the number of occurrences of each alphabet in the string is also a prime.
Given a String you need to tell if it is a primeString or not.
Input:
First line contains T which is t... | 1 | def eratosthenes2(n):
multiples = set()
primes = []
for i in range(2, n+1):
if i not in multiples:
primes.append(i)
multiples.update(range(i*i, n+1, i))
return primes
def is_prime_string(string):
primes = []
chars = set(string)
primes.append(len(chars))
... |
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertic... | 3 | from collections import deque
import sys
input = sys.stdin.readline
N = int(input())
G = [[] for _ in range(N)]
for _ in range(N):
ls = list(map(int, input().split()))
u = ls[0] - 1
for v in ls[2:]:
G[u].append(v - 1)
dist = [-1] * N
que = deque([0])
dist[0] = 0
while que:
v = que.popleft()
... |
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 1 | from sys import stdin
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm2(a, b):
return (a * b) / gcd(max(a, b), min(a, b))
def lcm3(a, b, c):
return lcm2(a, lcm2(b, c))
def lcm4(a, b, c, d):
return lcm2(lcm2(a, b), lcm2(c, d))
def main():
k = int(stdin.readline())... |
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise.
Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i... | 3 | n,m = [int(i) for i in input().split()]
tasks = [1] + [int(i) for i in input().split()]
res = 0
i = 0
while i < m:
if tasks[i] < tasks[i+1]:
res+=tasks[i+1] - tasks[i]
elif tasks[i] > tasks[i+1]:
res+=n - tasks[i] + tasks[i+1]
else:
while tasks[i] == tasks[i+1]:
i+=1
... |
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a... | 3 | n, m = map(int, input().split())
a_plus = input().split().count('1')
a_min = min(a_plus, n - a_plus) * 2
res = []
for i in range(m):
l, r = map(int, input().split())
length = r - l + 1
res.append('0' if length > a_min or length % 2 else '1')
print('\n'.join(res)) |
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do... | 1 | x=list(raw_input())
y=list(raw_input())
a=[]
for i in range(len(x)):
a.append(str(int(x[i])^int(y[i])))
print ''.join(a) |
Takahashi has N balls. Initially, an integer A_i is written on the i-th ball.
He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls.
Find the minimum number of balls that Takahashi needs to rewrite the integers on them.
Constraints
* 1 \leq K \leq N... | 3 | import collections
N, K = map(int, input().split())
A = list(map(int, input().split()))
c = collections.Counter(A).most_common()
ans = 0
L = len(c)
if L >= K:
for i in range(K, L):
ans += c[i][1]
print(ans)
|
You are given a huge integer a consisting of n digits (n is between 1 and 3 ⋅ 10^5, inclusive). It may contain leading zeros.
You can swap two digits on adjacent (neighboring) positions if the swapping digits are of different parity (that is, they have different remainders when divided by 2).
For example, if a = 032... | 3 | from sys import stdin
def input():
return stdin.readline()[:-1]
def intput():
return int(input())
def sinput():
return input().split()
def intsput():
return map(int, sinput())
t = intput()
for _ in range(t):
a = input()
oddbuff = []
evenbuff = []
for x in a:
x = int(x)
... |
A and B are preparing themselves for programming contests.
To train their logical thinking and solve problems better, A and B decided to play chess. During the game A wondered whose position is now stronger.
For each chess piece we know its weight:
* the queen's weight is 9,
* the rook's weight is 5,
* the ... | 3 | white = 0
black = 0
for i in range(8):
line = input()
for j in line:
if j == 'Q':
white += 9
elif j == 'R':
white += 5
elif j == 'B' or j == 'N':
white += 3
elif j == 'P':
white += 1
elif j == 'q':
black += 9
... |
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size n× n and he wants to traverse his grid f... | 3 | ans = []
for i in range(int(input())):
n = int(input())
grid = []
for j in range(n):
grid.append(input())
s_right, s_down = int(grid[0][1]), int(grid[1][0])
f_left, f_up = int(grid[n-1][n-2]), int(grid[n-2][n-1])
s_sum = s_right + s_down
f_sum = f_left + f_... |
A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | 3 | n=int(input())
for i in range(n):
a,b=map(int,input().split())
if(a>b):
print((b*(b+1)//2))
else:
print(a*(a-1)//2+1) |
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock.
You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ... | 3 | n = int(input())
a = [int(x) for x in input().split()]
s = a[-1]
j = n - 1
for i in range(n - 2, -1, -1):
if a[i] >= a[j]:
a[i] = max(a[j] - 1, 0)
j -= 1
s += a[i]
print(s)
|
You are given an array a consisting of n integers. You can perform the following operations arbitrary number of times (possibly, zero):
1. Choose a pair of indices (i, j) such that |i-j|=1 (indices i and j are adjacent) and set a_i := a_i + |a_i - a_j|;
2. Choose a pair of indices (i, j) such that |i-j|=1 (indice... | 3 | n = int(input())
a = list(map(int, input().split(" ")))
cnt = {}
ans = 0
val = 0
for i in range(0, n):
try:
cnt[a[i]] += 1
if ans < cnt[a[i]]:
ans = cnt[a[i]]
pos = i
val = a[i]
except:
cnt[a[i]] = 1
if ans < cnt[a[i]]:
ans = cnt[a[... |
You have a digit sequence S of length 4. You are wondering which of the following formats S is in:
* YYMM format: the last two digits of the year and the two-digit representation of the month (example: `01` for January), concatenated in this order
* MMYY format: the two-digit representation of the month and the last t... | 3 | s=input()
a=int(s[:2])
b=int(s[2:])
if 0<a<13 and 0<b<13:
print('AMBIGUOUS')
elif 0<a<13:
print('MMYY')
elif 0<b<13:
print('YYMM')
else:
print('NA') |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | s=list(input())
t=[int(i) for i in s]
ans,temp=1,1
for i in range(1,len(t)):
if(t[i]==t[i-1]):
temp+=1
else:
ans=max(ans,temp)
temp=1
ans=max(ans,temp)
if(ans>=7):
print("YES")
else:
print("NO") |
Vector Willman and Array Bolt are the two most famous athletes of Byteforces. They are going to compete in a race with a distance of L meters today.
<image>
Willman and Bolt have exactly the same speed, so when they compete the result is always a tie. That is a problem for the organizers because they want a winner.
... | 3 |
def gcd(a, b):
while a!=0 and b!=0:
if a > b:
a = a % b
else:
b = b % a
return a + b
t, a, b = map(int, input().split())
pnk = min(a, b)
nod = gcd(a, b)
nok = (a * b) // nod
ans = pnk * (t // nok)
ans += min(pnk, t % nok + 1)
ans -= 1
nd = gcd(ans, t)
#nd = 1
ans = ... |
Given are integers a,b,c and d. If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?
Constraints
* -10^9 \leq a \leq b \leq 10^9
* -10^9 \leq c \leq d \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the follo... | 1 | from __future__ import division, print_function
import bisect
import math
import heapq
import itertools
import sys
from collections import deque
from atexit import register
from collections import Counter
from functools import reduce
if sys.version_info[0] < 3:
from io import BytesIO as stream
else:
from io imp... |
Polycarp is going to participate in the contest. It starts at h_1:m_1 and ends at h_2:m_2. It is guaranteed that the contest lasts an even number of minutes (i.e. m_1 \% 2 = m_2 \% 2, where x \% y is x modulo y). It is also guaranteed that the entire contest is held during a single day. And finally it is guaranteed tha... | 3 | T1 = input()
T2 = input()
h1 = int(T1[:2])
m1 = int(T1[3:])
h2 = int(T2[:2])
m2 = int(T2[3:])
h = (h2 - h1)//2
h3 = (h2 - h1)/2
m = (m2 - m1)//2
H = h1 + h
M = m1 + m
#print("M:",M)
if M>=60:
M=M-60
H+=1
if h3 - h ==0:
H = "0"+str(H)
M = "0"+str(M)
if len(H)==3 and len(M)==3:
print(H[1:]+":"+M[1:... |
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replace... | 3 | num=input()
latin=input()
string=input()
latin1=[]
latin2=[]
counter=0
nums=num.split()
if int(nums[0])>int(nums[1])+1:
bool=False
else:
test=True
for i in latin:
if i=='*':
counter+=1
if counter==0:
latin1.append(i)
elif counter==1 and i!='*':
lat... |
Bear Limak wants to become the largest of bears, or at least to become larger than his brother Bob.
Right now, Limak and Bob weigh a and b respectively. It's guaranteed that Limak's weight is smaller than or equal to his brother's weight.
Limak eats a lot and his weight is tripled after every year, while Bob's weight... | 3 | a, b = [int(i) for i in input().split()]
i = 0
while a <= b:
a *= 3
b *= 2
i += 1
print(i)
|
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | a = int(input())
n = 1
if a % 5 == 0:
n -= 1
print(a // 5 + n) |
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly x chunks. Now he wonders whether he can buy exactly th... | 1 | for _ in range(input()):
print ['YES','NO'][input()in[1,2,4,5,8,11]] |
You are given a 4-character string S consisting of uppercase English letters. Determine if S consists of exactly two kinds of characters which both appear twice in S.
Constraints
* The length of S is 4.
* S consists of uppercase English letters.
Input
Input is given from Standard Input in the following format:
S
... | 1 | moji = raw_input()
a,b,c,d = list(moji)
moji = list(moji)
if moji.count(a) == moji.count(b):
if moji.count(b) == moji.count(c):
if moji.count(c) == 2:
print "Yes"
exit()
print "No" |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 | t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
x=a.count(0)
if sum(a)+x == 0:
print(x+1)
else:
print(x) |
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | t=int(input())
while(t>0):
t-=1
n,m=map(int,input().split())
if(n==1):
print(0)
elif(n==2):
print(m)
else:
print(min(2,n-1)*m)
|
Awruk is taking part in elections in his school. It is the final round. He has only one opponent — Elodreip. The are n students in the school. Each student has exactly k votes and is obligated to use all of them. So Awruk knows that if a person gives a_i votes for Elodreip, than he will get exactly k - a_i votes from t... | 3 | n = int(input())
a = list(map(int,input().split()))
k = max(a)
v =[]
for i in a:
v.append(k-i)
z = sum(v)
while sum(a)>=z:
z+=n
k+=1
print(k)
|
For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | 3 | n=int(input())
for i in range(n):
a,b=map(int,input().split())
l=list(map(int,input().split()))
l=sum(l)
if l==b:
print("YES")
else:
print("NO")
|
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0.
In one operation, you can choose two different indices i and j (1 ≤ i, j ≤ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](... | 1 | from __future__ import division, print_function
_interactive = False
def main():
for _ in range(int(input())):
n = int(input())
ar = input_as_list()
m = min(ar)
nar = []
mult = []
for x in ar:
if x % m == 0:
mult += [x]
na... |
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made lik... | 3 | i=int(input())
for i in range(0,i):
s=input()
if len(s)<=10:
print(s)
else:
print(s[0],end="")
print(len(s)-2,end='')
print(s[-1],end='')
print('\n') |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 3 | X = int(input())
if X < 6 or X % 2 != 0:
print(0)
exit()
print(X // 4 if X / 4 != X // 4 else X // 4 - 1)
|
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct.
When a query appears server may react in three possible ways:
1. If server is free and... | 3 | import queue
n, b = list(map(int, input().split()))
class Task:
def __init__(self, time: int, duration: int, index: int) -> None:
super().__init__()
self.time = time
self.duration = duration
self.index = index
remaining = queue.Queue()
running = False
finish_time = 0 # Runnin... |
Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s... | 3 | t = int(input())
for j in range(t):
n = int(input())
a=True
if n==2:
print(2)
print(1,2)
else:
print(2)
cnt=0
print(n,n-2)
print(n-1,n-1)
for j in range(n-1,0,-1):
if cnt==n-3:
break
print(j,j-2)
... |
You are given a string S consisting of `0` and `1`. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into `0` by repeating the following operation some number of times.
* Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfi... | 3 | def solve(string):
l = [s == "1" for s in string]
l_r = l[::-1]
index = 0
h = len(string) // 2
for i, (c, n, c_r, n_r) in enumerate(zip(l[:h], l[1:h + 1], l_r[:h], l_r[1:h + 1])):
if c ^ n or c_r ^ n_r:
index = i + 1
return str(len(string) - index)
if __name__ == '__main__'... |
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.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s=input()
p=0
if(len(s)>1):
for i in s:
if(i=='4' or i=='7'):
p=1+p
if(p==4 or p==7):
print("YES")
else:
print("NO")
|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ... | 3 | k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
count=0
ar=[ i for i in range(1,d+1)]
for i in ar:
if i%k!=0 and i%l!=0 and i%m!=0 and i%n!=0:
count+=1
print(d-count) |
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc... | 3 | n = int(input())
pushs = 1
bottoms = 0
for i in range(n, 1, -1):
pushs += i
pushs += bottoms * (i - 1)
bottoms += 1
print(pushs)
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | def Convertir(A):
NA=[]
for K in A:
NA=NA+[K]
return NA
Dat=input()
Cad=Convertir(Dat)
Cad=Cad+[""]
Cad=Cad+[""]
Cad=Cad+[""]
Res=""
K=0
while(K<(len(Cad)-3)):
if((Cad[K]=="W")and(Cad[K+1]=="U")and(Cad[K+2]=="B")):
if((len(Res)!=0)):
Res=Res+" "
K=K+3
else:
... |
Vanya got n cubes. He decided to build a pyramid from them. Vanya wants to build the pyramid as follows: the top level of the pyramid must consist of 1 cube, the second level must consist of 1 + 2 = 3 cubes, the third level must have 1 + 2 + 3 = 6 cubes, and so on. Thus, the i-th level of the pyramid must have 1 + 2 + ... | 3 |
n = int(input())
i = 1
total_cube = 0
while total_cube <= n:
total_cube += (i*(i+1))//2
i+=1
print(i-2) |
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | 3 | import math
import sys
import itertools
def sa(Type= int):
return [Type(x) for x in input().split()]
def solve(t):
n = input()
arr = sa()
oddInEven = 0
evenInOdd = 0
for idx, x in enumerate(arr):
xOdd = x % 2 == 1
iOdd = idx % 2 == 1
if xOdd and not iOdd:
oddInEven += 1
elif not x... |
Let's call a number k-good if it contains all digits not exceeding k (0, ..., k). You've got a number k and an array a containing n numbers. Find out how many k-good numbers are in a (count each number every time it occurs in array a).
Input
The first line contains integers n and k (1 ≤ n ≤ 100, 0 ≤ k ≤ 9). The i-th ... | 1 | n,k=map(int,raw_input().split())
print n-len([i for i in range(n) if set(range(k+1)) - set(map(int,raw_input()))])
|
Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them... | 1 | n = int(raw_input())
a = map(int, raw_input().split())
ok = True
b = [[a[i], a[i+1]] for i in xrange(n-1)]
for i in xrange(n-1):
b[i].sort()
for j in xrange(i):
if b[i][0] < b[j][0] < b[i][1] < b[j][1] or b[j][0] < b[i][0] < b[j][1] < b[i][1]:
ok = False
print "no" if ok else "yes"
|
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins.
He wants to distribute all these n coins between his sisters in such a way that ... | 3 | t=int(input())
for i in range(t):
a,b,c,n=[int(x) for x in input().split()]
d=max(a,b)
m=max(d,c)
d=3*m-a-b-c
if (n-d)%3==0 and n>=d:
print("YES")
else:
print("NO") |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | '''
Name : Jaymeet Mehta
codeforces id :mj_13
Problem :
'''
from sys import stdin,stdout
import math
test=int(stdin.readline())
for _ in range(test):
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
pos=a[0]>0
i=0
sum=0
out=False
while i<n:
if pos:
el... |
Vova's house is an array consisting of n elements (yeah, this is the first problem, I think, where someone lives in the array). There are heaters in some positions of the array. The i-th element of the array is 1 if there is a heater in the position i, otherwise the i-th element of the array is 0.
Each heater has a va... | 3 | n, r = map(int, input().split())
a = list(map(int, input().split()))
cur = 0
res = 0
while cur < n:
b = max(0,cur-r+1)
c = a[b:cur+r]
if sum(c):
i = len(c) - c[-1::-1].index(1) - 1
cur = b + i + r
res += 1
else:
print(-1)
break
else:
print(res) |
Given are an integer X and an integer sequence of length N: p_1, \ldots, p_N.
Among the integers not contained in the sequence p_1, \ldots, p_N (not necessarily positive), find the integer nearest to X, that is, find the integer whose absolute difference with X is the minimum. If there are multiple such integers, repo... | 3 | x, n = map(int, input().split())
a = set(map(int, input().split()))
print(min((i for i in range(102) if i not in a), key=lambda y:abs(x-y)))
|
You are given a permutation p of length n. Remove one element from permutation to make the number of records the maximum possible.
We remind that in a sequence of numbers a1, a2, ..., ak the element ai is a record if for every integer j (1 ≤ j < i) the following holds: aj < ai.
Input
The first line contains the onl... | 3 | n = int(input())
if n == 0: exit(0)
p = [0] + input().split(" ")
r = (n + 1) * [0]
max_1 = -1
max_2 = -1
for i in range(1, n + 1):
p[i] = int(p[i])
# print(p[i], max_1, max_2)
if p[i] > max_1:
max_2 = max_1
max_1 = p[i]
r[p[i]] -= 1
elif p[i] > max_2:
r[max_1] += 1
max_2 = p[i]
ans = 100001
val = -10... |
T is playing a game with his friend, HL.
There are n piles of stones, the i-th pile initially has a_i stones.
T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th... | 3 | from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop,heapify
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 998244353... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n=int(input())
a=list(map(int,input().split()))
a.sort()
for i in range(n):
if sum(a[:n-i-1])<sum(a[n-i-1:]):
print(i+1)
break |
Arkady and his friends love playing checkers on an n × n field. The rows and the columns of the field are enumerated from 1 to n.
The friends have recently won a championship, so Arkady wants to please them with some candies. Remembering an old parable (but not its moral), Arkady wants to give to his friends one set o... | 3 | n, m = map(int, input().split())
ans = 0
for i in range(1, m + 1):
for j in range(1, m + 1):
if (i ** 2 + j ** 2) % m == 0:
if n % m >= i:
if n % m >= j:
ans += (n // m + 1) * (n // m + 1)
else:
ans += (n // m + 1) * (n // m... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
line = [int(x) for x in input().split()]
if line[0] % 2 == line[1] % 2:
a = line[0] % 2
else:
a = line[2] % 2
for i in range(n):
if line[i] % 2 != a:
print(i+1)
|
There are n children, who study at the school №41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right.
Children can do the following: in one second several pairs of neighboring... | 3 | #!/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():
n , k = [int(n) for n in input().split... |
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 ... | 1 | line = raw_input()
line = line.split()
rows = int(line[0])
cols = int(line[1])
violas = int(line[2])
minVs = int(line[3])
board = []
for i in range(rows):
r = []
for j in range(cols):
r.append(0)
board.append(r)
for i in range(violas):
line = raw_input()
line = line.split()
x = int(line[0])-1
y = int(line[1]... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n, t = map(int, input().split())
q = input()
def get_s(q):
s = ""
i = 0
while i < n - 1:
if q[i] == 'B' and q[i + 1] == 'G':
s += "GB"
i += 2
else:
s += q[i]
i += 1
if len(s) == n - 1:
s += q[n - 1]
return s
for _ in range(t... |
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling... | 3 | n = int(input())
s = [int(x) for x in input().split()]
s.sort()
print(*s , sep = " ") |
Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i.
He wrote an integer X on the blackboard, then performed the following operation N times:
* Choose one element from S and remove it.
* Let x be the number written on the blackboard now, and y be the integer removed from S. Repla... | 3 | import sys
input = sys.stdin.readline
mod=10**9+7
N,X=map(int,input().split())
S=list(map(int,input().split()))
S.sort(reverse=True)
DP={X:1}
for i in range(N):
s=S[i]
NDP=dict()
for d in DP:
if d<s:
NDP[d]=(NDP.get(d,0)+DP[d]*(N-i))%mod
else:
NDP[d]=(NDP.g... |
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n=int(input())
l=[1]*n
for i in range(n):
l[i]=[1]*n
for i in range(n-1):
for j in range(n-1):
l[i+1][j+1]=l[i][j+1]+l[i+1][j]
print(l[n-1][n-1])
|
You want to perform the combo on your opponent in one popular fighting game. The combo is the string s consisting of n lowercase Latin letters. To perform the combo, you have to press all buttons in the order they appear in s. I.e. if s="abca" then you have to press 'a', then 'b', 'c' and 'a' again.
You know that you ... | 3 | l3=[]
for i in range(ord('a'),ord('z')+1):
l3.append(chr(i))
for _ in range(int(input())):
n,m=map(int,input().split())
s=input()
l1=list(map(int,input().split()))
l1.append(n)
l2=[0]*(n+1)
for i in range(m+1):
l2[l1[i]]+=1
for i in range(n-1,0,-1):
l2[i]+=l2[i+1]
d=d... |
There are N cities and M roads. The i-th road (1≤i≤M) connects two cities a_i and b_i (1≤a_i,b_i≤N) bidirectionally. There may be more than one road that connects the same pair of two cities. For each city, how many roads are connected to the city?
Constraints
* 2≤N,M≤50
* 1≤a_i,b_i≤N
* a_i ≠ b_i
* All input values a... | 3 | n,m=map(int,input().split())
s=' '.join([input() for _ in [0]*m])
for i in range(1,n+1):print(s.split().count(str(i))) |
You have a fence consisting of n vertical boards. The width of each board is 1. The height of the i-th board is a_i. You think that the fence is great if there is no pair of adjacent boards having the same height. More formally, the fence is great if and only if for all indices from 2 to n, the condition a_{i-1} ≠ a_i ... | 3 | from sys import stdin
input=stdin.readline
for _ in range(int(input())):
n=int(input())
lis=[]
for i in range(n):
lis.append(list(map(int,input().split())))
dp=[]
for i in range(n):
dp.append([0]*3)
dp[0][0]=0
dp[0][1]=lis[0][1]
dp[0][2]=lis[0][1]*2
for i in range(1,... |
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b.
Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ... | 3 | from collections import Counter
import math
import sys
from bisect import bisect,bisect_left,bisect_right
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def mod()... |
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K × K square. Below is an example of a checked pattern of side 3:
cba927b2484f... | 3 | def main():
n, k = map(int, input().split())
mp1 = [[0] * k for _ in range(k)]
mp2 = [[0] * k for _ in range(k)]
for _ in range(n):
x, y, c = input().split()
t = int(x) // k + int(y) // k
x = int(x) % k
y = int(y) % k
if c == "B":
t += 1
if t % 2:
mp1[y][x] += 1
else:
... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | (n, k)= input().split()
k = int(k)
while k>0:
if n[-1] is "0":
n = str(int(n)//10)
else:
n = str(int(n)-1)
k -=1
print(n) |
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≤ i ≤ k). The store has an infinite number of packages of each type.
Polycarp wants to choose one type of packages and then buy several (one or... | 3 | import math
for _ in range(int(input())):
n, k = map(int, input().split())
ans = n
i = 1
while i * i <= n and i <= k:
if n % i == 0:
if n // i <= k:
ans = i
break
ans = min(ans, n // i)
i += 1
print(ans) |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | flag = 1
first_string = str(input())
second_string = str(input())
j = int(len(second_string))
for i in range(0,len(first_string)):
j -= 1
if first_string[i] != second_string[j]:
flag = 0
if flag == 1:
print("YES")
else:
print("NO")
|
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a × b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents... | 3 | _ = input()
arr = [str(len(x)) for x in input().replace('W', ' ').split()]
print(len(arr))
print(' '.join(arr)) |
Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | 3 | N, K = map(int, input().split())
print(min(N %K, -(N %K -K))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.