problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | from sys import stdin, stdout
def main():
n = int(stdin.readline().rstrip())
stops = []
for num in range(0, n):
stops.append(list(map(int, stdin.readline().rstrip().split())))
capacity = 0
passengers = 0
for stop in stops:
passengers = passengers - stop[0]
passengers ... |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n Γ n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 1 | n = input()
k = (n - 1) / 2
for i in xrange(k):
print ((k - i) * '*') + 'D' * (i * 2 + 1) + ((k - i) * '*')
for i in xrange(k , -1 , -1):
print ((k - i) * '*') + 'D' * (i * 2 + 1) + ((k - i) * '*')
|
Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 β€ m β€ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | 3 | n = int(input())
s = input()
ans = ""
i = 0
y = 0
while i < n:
ans += s[i]
y += 1
i += y
print(ans) |
The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But ... | 3 | import sys, os
import math
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
n,... |
You have been given a String S. You need to find and print whether this string is a palindrome or not. If yes, print "YES" (without quotes), else print "NO" (without quotes).
Input Format
The first and only line of input contains the String S. The String shall consist of lowercase English alphabets only.
Output Form... | 1 | n=raw_input('')
def palindrome(n):
index=0
check=True
while index<len(n):
if n[index]==n[-1-index]:
index+=1
return True
return False
if palindrome(n)==True:
print "YES"
else:
print "NO" |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) β f(n-2) when n > 1, where β de... | 3 | no_of_testcases=int(input())
def convert_to_binary(binary_list):
length_of_final_list=len(binary_list)
counter=length_of_final_list-1
decimal_no=0
while(counter>=0):
decimal_no=decimal_no+int(binary_list[counter])*pow(2,length_of_final_list-1-counter)
counter=counter-1
return decimal... |
Nikolay has only recently started in competitive programming, but already qualified to the finals of one prestigious olympiad. There going to be n participants, one of whom is Nikolay. Like any good olympiad, it consists of two rounds. Tired of the traditional rules, in which the participant who solved the largest numb... | 3 | from sys import stdin
T=int(stdin.readline().strip())
for caso in range(T):
n,b,c=map(int,stdin.readline().strip().split())
x=max(1,b+c+1-n)
print(min(x,n),min(b+c-1,n))
|
AtCoDeer has three cards, one red, one green and one blue.
An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.
We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.
Is this integer... | 3 | print(['NO','YES'][int(input().replace(' ',''))%4==0]) |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | t = int(input())
for _ in range(t):
n = int(input())
s = input()
if '8' in s and n - s.find('8') >= 11:
print('YES')
else:
print('NO')
|
There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | 3 | import math
from sys import stdin
from sys import setrecursionlimit
setrecursionlimit(100000)
def put(): return map(int, stdin.readline().split())
for _ in range(int(input())):
n=int(input())
s=input()
s=s.replace(" ","")
ind=s.find("1")
s=s[ind:]
s=s[-1::-1]
ind=s.find("1")
s=s[ind:]
s=s[-1::-1]
# print(s)... |
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks.
Determine whether the Cossack can reward all participants, giving each of them at leas... | 3 | x,y,z=map(int,input().split())
if x<=y and x<=z:
print("YES")
else:
print("NO") |
Jerry is a little mouse. He is trying to survive from the cat Tom. Jerry is carrying a parallelepiped-like piece of cheese of size A Γ B Γ C. It is necessary to trail this cheese to the Jerry's house. There are several entrances in the Jerry's house. Each entrance is a rounded hole having its own radius R. Could you he... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
from sys import stdin, exit
from math import hypot
def main(readline=stdin.readline):
answer = ('NA', 'OK')
while 1:
height, width, depth = (float(s) for s in readline().split())
if not height:
exit()
h... |
Vasya has a string s of length n. He decides to make the following modification to the string:
1. Pick an integer k, (1 β€ k β€ n).
2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through:
* qwe... | 3 | import sys
input=sys.stdin.readline
t=int(input())
for i in range(t):
n=int(input())
stri=input()
stri=stri[0:n]
z='z'*(50002)
if n==1:
print(stri)
print(1)
else:
count=0
if n%2==1:
for i in range(1,n+1):
if i%2==0:
... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | 3 | for t in range(int(input())):
s = input().strip()
n = len(s)
ones = []
i = 0
sums = 0
while i<n-1:
if s[i]=='1':
sums += 1
if s[i+1]=='0':
ones.append(sums)
sums = 0
i += 1
if sums>0 and i==n-1:
ones.append(sums+... |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 3 | n = int(input())
print(n // 2)
res = list()
if n % 2:
res = [3] + [2] * ((n - 3) // 2)
else:
res = [2] * (n // 2)
print(*res) |
Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a becomes empty, the two players perform the following operation alternately, starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, whe... | 3 | n = int(input())
a = list(map(int,input().split()))
dp = [[0]*(n) for i in range(n)]
if n%2 == 0:
for i in range(n):
dp[i][i] = -a[i]
else:
for i in range(n):
dp[i][i] = a[i]
for i in range(1,n):
for j in range(n-i):
if (n-i)%2==1:
dp[j][i+j] = max(dp[j][i+j-1]+a[i+j],dp[... |
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 | import math
t, b, w = list(map(int, input().split()))
if(b==w):
print("1/1");
exit(0);
lcm = b//math.gcd(b,w)*w
x = t//lcm
ans = min(b, w)-1
ans += (x-1)*min(b,w)
ans += min(t-x*lcm+1, min(b,w))
a = math.gcd(t,ans)
t = t//a
ans = ans//a
print(str(ans)+'/'+str(t))
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | n,m = [int(i) for i in input().split()]
f = [int(i) for i in input().split()]
f.sort()
S = f[m-1]-f[0]
for i in range(m-n+1):
s = f[i+n-1]-f[i]
if s<S : S = s
print(S) |
Okabe needs to renovate the Future Gadget Laboratory after he tried doing some crazy experiments! The lab is represented as an n by n square grid of integers. A good lab is defined as a lab in which every number not equal to 1 can be expressed as the sum of a number in the same row and a number in the same column. In o... | 3 | from itertools import product
n = int(input())
A = [list(map(int, input().split())) for _ in range(n)]
for i,j in product(range(n), repeat=2):
if A[i][j] > 1 and all(A[i][k]+A[m][j]!=A[i][j]
for k,m in product(range(n), repeat=2)):
print('No')
break
else:
print('Yes'... |
Polycarpus has n markers and m marker caps. Each marker is described by two numbers: xi is the color and yi is the diameter. Correspondingly, each cap is described by two numbers: aj is the color and bj is the diameter. Cap (aj, bj) can close marker (xi, yi) only if their diameters match, that is, bj = yi. Besides, a m... | 1 | from collections import defaultdict, Counter
n, m = tuple( [int(t) for t in raw_input().split() ] )
D_F, D_K = defaultdict(list), defaultdict(list)
for i in range(n):
c, d = tuple( [int(t) for t in raw_input().split() ] )
D_F[d].append(c)
for j in range(m):
c, d = tuple( [int(t) for t in raw_input().split() ] )
... |
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if... | 3 | s=input()
n=len(s)
sb = 1
for i in range(n):
if sb==1 and s[i]=='h':
sb+=1
if sb==2 and s[i]=='e':
sb+=1
if sb==3 and s[i]=='l':
sb+=1
continue
if sb==4 and s[i]=='l':
sb+=1
if sb==5 and s[i]=='o':
sb+=1
if sb==6:
print('YES')
else:
print('NO') |
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ... | 3 | def main():
n, m = map(int, input().split())
s = list(map(int, input().split()))
d = [i for i in s if i < 0]
if len(d) <= m:
print(abs(sum(d)))
else:
d.sort()
print(abs(sum(d[:m])))
if __name__ == '__main__':
main()
|
Some number of chocolate pieces were prepared for a training camp. The camp had N participants and lasted for D days. The i-th participant (1 \leq i \leq N) ate one chocolate piece on each of the following days in the camp: the 1-st day, the (A_i + 1)-th day, the (2A_i + 1)-th day, and so on. As a result, there were X ... | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*
N = int(raw_input())
D, X = map(int, raw_input().split())
A = []
for i in range(N):
A.append(int(raw_input()))
k = []
ans = X + N
for i in range(N):
k.append(0)
while 1:
if 1 + k[i] * A[i] > D:
k[i] -= 1
break
else:
... |
Draw a chessboard which has a height of H cm and a width of W cm. For example, the following figure shows a chessboard which has a height of 6 cm and a width of 10 cm.
.#.#.#.#.
.#.#.#.#.#
.#.#.#.#.
.#.#.#.#.#
.#.#.#.#.
.#.#.#.#.#
Note that the top left corner should be drawn by '#'.
Constraints
* 1 β€ H β€ 300
* 1... | 1 | while 1:
H, W = map(int, raw_input().split())
s = ""
if H == 0 and W == 0:
break
for i in range(H):
for j in range(W):
if i%2 == 0:
if j%2 == 0:
s = s + "#"
else:
s = s + "."
else:
if j%2 == 0:
s = s + "."
else:
s = s ... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | y = int(input())
i = y
flag =0
while(1):
if(len(set(str(i)))==4):
if(i-y > 0):
flag = 1
ans = i
if(flag == 1):
break
i += 1
print(ans)
|
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them.
Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1.
Input
T... | 1 | a=raw_input().split()
n=int(a[0])
t=int(a[1])
i=pow(10,n-1)
co=0
while(i<pow(10,n)):
if(i%t==0):
co+=1
k=i
break
i+=1
if(co==0): print -1
else: print k
|
This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | 3 | # ------------------- 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 file.mode... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 3 | n,k=map(int,input().split())
a=[int(i) for i in input().split()]
sorted(a)
count=0
for i in range(n):
if a[i]==0:
continue
if a[i]>=a[k-1]:
count+=1
print(count)
|
You are given two integers a and b. You may perform any number of operations on them (possibly zero).
During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations.
Is it possible to mak... | 3 | for i in range(int(input())):
a,b = [int(j) for j in input().split()]
if((a+b)%3!=0 or abs(a-b)>min(a,b)):
print('NO')
else:
print('YES')
|
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 | n=int(input())
r=list(map(int,str(n)))
a=r.count(4)
b=r.count(7)
if(a+b==4 or a+b==7):
print("YES")
else:
print("NO") |
Binary trees are defined recursively. A binary tree T is a structure defined on a finite set of nodes that either
* contains no nodes, or
* is composed of three disjoint sets of nodes:
- a root node.
- a binary tree called its left subtree.
- a binary tree called its right subtree.
Your task is to write a program ... | 3 | class BinaryTree:
class Node:
def __init__(self, num, left_child, right_child):
self.id = num
self.left_child = left_child
self.right_child = right_child
def __init__(self, n):
self.nodes = [None] * n
self.root_id = int(n * (n - 1) / 2)
... |
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re... | 3 | import math
for _ in range(int(input())):
n,k = map(int,input().split())
s=input()
s=list(s)
s.sort()
small=s[0]
ans=""
rest=[]
if s[0]==s[-1]:
l=len(s)
ans+=(math.ceil(l/k))*s[0]
else:
t=s.count(small)//k
rest = s[k:]
if t>0:
... |
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 = map(int,input(" ").split())
i=0
while (a<=b):
a=a*3
b=b*2
i=i+1
print(i) |
You are given an integer N. Find the number of the positive divisors of N!, modulo 10^9+7.
Constraints
* 1β€Nβ€10^3
Input
The input is given from Standard Input in the following format:
N
Output
Print the number of the positive divisors of N!, modulo 10^9+7.
Examples
Input
3
Output
4
Input
6
Output
3... | 3 | from math import factorial
from collections import Counter
n = factorial(int(input()))
res = []
x = n
y = 2
while y*y <= x:
while x % y == 0:
res.append(y)
x //= y
y += 1
if x > 1:
res.append(x)
res = Counter(res)
ans = 1
for v in res.values():
ans = ans*(v+1) % (10**9+7)
print(ans) |
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ... | 3 | n = int(input())
a = []
b = []
pas = 0
for _ in range(n):
(a1 , b1) = map(int,input().split())
a.append(a1)
b.append(b1)
sum_val = 0
for i in range(n):
sum_val = sum_val + (b[i] - a[i])
if sum_val >= pas:
pas = sum_val
print(pas)
|
Let {\rm comb}(n,r) be the number of ways to choose r objects from among n objects, disregarding order. From n non-negative integers a_1, a_2, ..., a_n, select two numbers a_i > a_j so that {\rm comb}(a_i,a_j) is maximized. If there are multiple pairs that maximize the value, any of them is accepted.
Constraints
* 2 ... | 3 | n = int(input())
a = list(map(int, input().split()))
a.sort()
x,a = a[-1],a[:-1]
temp = []
for i in a:
temp.append(abs(x/2-i))
y=a[temp.index(min(temp))]
print(x,y) |
You are the gym teacher in the school.
There are n students in the row. And there are two rivalling students among them. The first one is in position a, the second in position b. Positions are numbered from 1 to n from left to right.
Since they are rivals, you want to maximize the distance between them. If students a... | 3 | t = int(input())
for i in range(t):
n, x, a, b = map(int, input().split())
if b > a:
a, b = b, a
while a < n and x > 0:
a += 1
x -= 1
while b > 1 and x > 0:
b -= 1
x -= 1
print(a-b) |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | s=input()
p=s.lower()
#print(p)
q=""
i=0
if(len(p)<=100):
for item in p:
if(p.index(item)==i):
q = q + item
i = i + 1
#print(q)
#print(len(q))
if(len(q)%2==0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!")
|
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 | i = int(input())
list_input = list(map(int,input().split()))
list_input = sorted(list_input)
print(*list_input) |
You are given a positive integer m and two integer sequence: a=[a_1, a_2, β¦, a_n] and b=[b_1, b_2, β¦, b_n]. Both of these sequence have a length n.
Permutation is a sequence of n different positive integers from 1 to n. For example, these sequences are permutations: [1], [1,2], [2,1], [6,7,3,4,1,2,5]. These are not: [... | 3 | n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
b.sort()
min_x = m
for i in range(n):
x = (b[0] - a[i]) % m
c = a.copy()
for j in range(n):
c[j] = (c[j] + x) % m
c.sort()
if c == b:
min_x = min(min_x, x)
print(min_x)
|
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed.
There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st... | 3 | #1017A in codeforces
#english, german, math, history
# uid 1 - n (thomas is 1)
n = int(input())
thomas = sum(list(map(int,input().split())))
rank = 1
for _ in range(n-1):
marks = sum(list(map(int,input().split())))
if marks>thomas:
rank+=1
print(rank) |
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... | 3 | a=input()
n=len(a)
alist=list(a)
blist=list(input())
i=0
c=[0]*n
while i<n:
if alist[i]==blist[i]:
c[i]='0'
elif alist[i]!=blist[i]:
c[i]='1'
i=i+1
str1=''.join(c)
print (str1)
|
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second β number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 β AB, column 52 is marked by AZ. After ZZ there follow th... | 1 | def printcol(c):
if c==0:
return ""
return printcol((c - 1)/26) + chr(((c - 1)% 26) + ord('A'))
cnt = int(raw_input())
while cnt!=0:
cnt-=1
line=raw_input()
count=0
for i in range(len(line)-1):
if line[i]<="Z" and line[i]>="A":
if line[i+1]>="0" and line[i+1]<="9":
... |
When new students come to the Specialized Educational and Scientific Centre (SESC) they need to start many things from the beginning. Sometimes the teachers say (not always unfairly) that we cannot even count. So our teachers decided to teach us arithmetics from the start. And what is the best way to teach students add... | 3 | import math as m
s = input().split("=")
left = s[0].split("+")
a = len(left[0])
b = len(left[1])
right = len(s[1])
if a+b+right % 2 == 1:
print("Impossible")
elif m.fabs(right-a-b) != 2 and a+b != right:
print("Impossible")
elif a+b == right:
print(a*"|","+",b*"|","=",right*"|",sep="")
elif right-a-b == 2... |
In the snake exhibition, there are n rooms (numbered 0 to n - 1) arranged in a circle, with a snake in each room. The rooms are connected by n conveyor belts, and the i-th conveyor belt connects the rooms i and (i+1) mod n. In the other words, rooms 0 and 1, 1 and 2, β¦, n-2 and n-1, n-1 and 0 are connected with conveyo... | 3 | TC = int(input())
for tc in range(TC):
n = int(input())
s = input()
hasCW = False
hasCCW = False
for c in s:
if c == '>':
hasCW = True
if c == '<':
hasCCW = True
if hasCW and hasCCW:
s += s[0]
ans = 0;
for i in range(... |
Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers.
A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if:
* Its elements are in increasing o... | 1 | import os
import sys
import math
def main():
n = 1300000
isprime = [True] * n
for i in xrange(4, n, 2):
isprime[i] = False
for i in xrange(3, int(math.sqrt(n) + 2), 2):
if (isprime[i] == True):
for j in xrange(i * i, n, i * 2):
isprime[j] = False
primes = []
k = int(raw_... |
In Arcady's garden there grows a peculiar apple-tree that fruits one time per year. Its peculiarity can be explained in following way: there are n inflorescences, numbered from 1 to n. Inflorescence number 1 is situated near base of tree and any other inflorescence with number i (i > 1) is situated at the top of branch... | 3 | import sys, math
#f = open('input/input_2', 'r')
f = sys.stdin
N = int(f.readline())
pl = list(map(int, f.readline().split()))
e = [[] for _ in range(N+1)]
lv = [0] * (N+1)
for i, p in enumerate(pl):
e[p].append(i+2)
c = [0] * (N+1)
for i in range(1, N+1):
c[lv[i]] = 1 - c[lv[i]]
for j in e[i]:
lv[j] = l... |
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes.
Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it.
2 coverings are different if some 2 triangles are covered by the same diamond shape in ... | 3 | t = int(input())
ans = [0 for _ in range(t)]
for i in range(t):
n = int(input())
ans[i] = n
print(*ans, sep='\n') |
1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:
* the dogs numbered 1,2,\cdots,26 were respectively given the names `a`, `b`, ..., `z`;
* the dogs numbered 27,28,29,\... | 3 | MOD=10**9+1
n=int(input())
ans=''
while n:
ans=chr(ord('a')+(n+25)%26)+ans
n=(n-1)//26
print(ans) |
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 | s = input().split()
l = int(s[0])
b = int(s[1])
c = 0
while(l < b):
l *= 3
b *= 2
c +=1
if(l == b):
print(c+1)
else:
print(c) |
There is a cave consisting of N rooms and M one-directional passages. The rooms are numbered 1 through N.
Takahashi is now in Room 1, and Room N has the exit. The i-th passage connects Room s_i and Room t_i (s_i < t_i) and can only be traversed in the direction from Room s_i to Room t_i. It is known that, for each roo... | 3 | n, m = map(int, input().split())
edges_from = [[] for _ in range(n)]
for _ in range(m):
_from, to = map(lambda x: int(x)-1, input().split())
edges_from[_from].append(to)
E_dist_to_goal = [0] * n
for node in range(n-2, -1, -1):
routes = edges_from[node]
num_of_routes = len(routes)
for next_node in ... |
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations.
You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers.
Input
The first line of the input con... | 3 | n1, r1 = map(int, input().split())
v1 = 0
x1 = 1
for d in list(map(int, input().split()))[::-1]:
v1 += d * x1
x1 *= r1
r2 = int(input().split()[1])
v2 = 0
x2 = 1
for d in list(map(int, input().split()))[::-1]:
v2 += d * x2
x2 *= r2
print('>' if v1 > v2 else ('<' if v1 < v2 else '='))
|
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ... | 3 | for _ in range(int(input())):
n = int(input())
a = [int(i) for i in input().split()]
a.reverse()
l = a.copy()
for i in range(1, n):
l[i] = min(l[i - 1], a[i])
ans = 0
for i in range(n):
if a[i] > l[i]:
ans += 1
print(ans)
|
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers β the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column ... | 3 | ct=0
a, b = map(int, input().split(' '))
x=[0]*5
for i in range(1, b+1):
x[i%5]+=1
for i in range(1, a+1):
ct+=x[(0-i)%5]
print(ct)
|
In some game by Playrix it takes t minutes for an oven to bake k carrot cakes, all cakes are ready at the same moment t minutes after they started baking. Arkady needs at least n cakes to complete a task, but he currently don't have any. However, he has infinitely many ingredients and one oven. Moreover, Arkady can bui... | 3 | """Template for Python Competitive Programmers prepared by Mayank Chaudhary """
# to use the print and division function of Python3
from __future__ import division, print_function
"""value of mod"""
MOD = 998244353
mod = 10**9 + 7
"""use resource"""
# import resource
# resource.setrlimit(resource.RLIMIT_STACK, [0x10... |
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 β₯ w_2. In this game, exactly one ship is used... | 1 | a, b, c, d = map(int, (raw_input().split()))
print ((a+2)*(b+1)-(a*b))+((c+2)*(d+1)-(c*d))+(abs(a-c)) |
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 | for _ in range(int(input())):
n, m = list(map(int, input().split()))
a = list(map(int, input().split()))
print("YES" if sum(a) == m else "NO") |
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero.
For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not.
Now, you ha... | 3 | def spi(e):
if e == 1:
return 3
elif e == 2:
return 2
elif e == 3:
return 1
else:
return e%2
q = int(input())
b=[]
for i in range(q):
b.append( int(input()) )
for i in range(q):
print(spi(b[i]))
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | n = int(input())
polyhedrons = []
sum_of_faces = 0
for x in range(n):
polyhedrons.append(str(input()))
for x in polyhedrons:
if x == 'Tetrahedron':
sum_of_faces += 4
elif x == 'Cube':
sum_of_faces += 6
elif x == 'Octahedron':
sum_of_faces += 8
elif x == 'Dodecahedron':
... |
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork.
For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ... | 3 | x,y=list(map(int,input().split()))
if 2*(x+1)<y:
print(-1)
exit(0)
if x>y+1:
print(-1)
exit(0)
if x==y+1:
print("0"+"10"*y)
elif x==y:
print("10"*y)
elif 2*x>y:
t=y-x
print("110"*t+"10"*(x-t))
elif 2*x==y:
print("110"*x)
else:
t=y-2*x
print("110"*x+"1"*t) |
You are given a garland consisting of n lamps. States of the lamps are represented by the string s of length n. The i-th character of the string s_i equals '0' if the i-th lamp is turned off or '1' if the i-th lamp is turned on. You are also given a positive integer k.
In one move, you can choose one lamp and change i... | 3 | import sys
input = sys.stdin.readline
t = int(input())
out = []
for i in range(t):
n,k = map(int,input().split())
s = list(input())
count = [0]
for j in s:
if j == "1":
count.append(count[-1]+1)
else:
count.append(count[-1])
ans = count[-1]
dp = []
... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | str = input()
inpt = ""
n = int(str)
x = 0
for i in range(n):
inpt = input()
#print(inpt[0:2]+" - "+inpt[1:3])
if(inpt[0:2] == "++" or inpt[1:3] == "++"):
x += 1
#print("x = {} plus 1".format(x))
elif(inpt[0:2] == "--" or inpt[1:3] == "--"):
x -= 1
#print("x = {} minus 1".format(x))
print(x) |
NN is an experienced internet user and that means he spends a lot of time on the social media. Once he found the following image on the Net, which asked him to compare the sizes of inner circles:
<image>
It turned out that the circles are equal. NN was very surprised by this fact, so he decided to create a similar pi... | 3 | n, r = map(int, input().split())
from math import sin, pi
k = sin(pi/n)
print(r * k /( 1-k)) |
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... | 3 | import sys
RI = lambda : [int(x) for x in sys.stdin.readline().split()]
ri = lambda : sys.stdin.readline().strip()
for _ in range(int(ri())):
n,k = RI()
a = RI()
arr = []
outflag = True
for i in a:
temp = i
bit = []
flag = True
while temp > 0:
temp1 =... |
Vanya got an important task β he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the bo... | 3 | n = input()
l=len(n)
n=int(n)
d=0
for i in range(1, l):
d=d+(9*(10**(i-1)))*i
d=d+(((n+1)-10**(l-1))*l)
print(d)
|
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | if __name__ == '__main__':
for _ in range(int(input())):
n = input()
a = n[len(n)-2:]
b = n[len(n)-4:]
c = n[len(n)-5:]
if a == 'po':
print('FILIPINO')
elif b == 'desu' or b == 'masu':
print('JAPANESE')
else:
if c == 'mnida':
print('KOREAN') |
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ... | 3 | # bad_prices.py
for z in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
k = a[n-1]
cnt = 0
for i in range(n-2,-1,-1):
if a[i]>k:
cnt+=1
else:
k = min(k,a[i])
print(cnt) |
There are N dots in a two-dimensional plane. The coordinates of the i-th dot are (x_i, y_i).
We will repeat the following operation as long as possible:
* Choose four integers a, b, c, d (a \neq c, b \neq d) such that there are dots at exactly three of the positions (a, b), (a, d), (c, b) and (c, d), and add a dot at... | 3 | from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
def main():
N = int(input())
V = 100005
to = defaultdict(list)
for _ in range(N):
X, Y = map(int, input().split())
Y += V
to[X].append(Y)
to[Y].append(X)
visited = [0] * (2 * V)
cnt ... |
We'll define S(n) for positive integer n as follows: the number of the n's digits in the decimal base. For example, S(893) = 3, S(114514) = 6.
You want to make a consecutive integer sequence starting from number m (m, m + 1, ...). But you need to pay S(n)Β·k to add the number n to the sequence.
You can spend a cost up... | 1 | w, m, k = map(int, raw_input().split())
sl = len(str(m))
mx = 10**sl - 1
av = w
counter = 0
while (mx-m+1)*k*sl < av:
counter += mx - m + 1
av -= (mx-m+1)*k*sl
m = mx + 1
sl += 1
mx = 10**sl - 1
if av > 0:
counter += av / (sl*k)
print counter |
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple... | 3 | n = int(input())
a = [int(x) for x in input().split()]
mini = min(a)
maxi = max(a)
c = 0
for x in a:
if x!=mini and x!=maxi:
c+=1
print(c) |
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 | arr=list(map(int,input().strip().split()))
n=arr[0]
m=arr[1]
l=list(map(int,input().strip().split()))
count=l[0]-1
for i in range(1,m):
if l[i]>=l[i-1]:
count=count+l[i]-l[i-1]
else:
count+=n+l[i]-l[i-1]
print(count) |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | import sys
n, m = map(int,input().split())
array = list(map(int,input().split()))
array.sort()
izpis = [0] * (m-n+1)
naj = 1000
if n == m:
print(str(array[n-1] - array[0]))
sys.exit()
for i in range(0,m-n+1):
#print('array[i+n-1]: ',str(array[i+n-1]))
#print('array[i]: ',str(array[i]))
izpis[i] = (a... |
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It... | 3 | n=int(input())
s=int(n/2)
#a=list(map(int,input().split()))
a=[int(x) for x in input()]
if a.count(4)+a.count(7)==n and sum(a[:s])==sum(a[s:]):
print("YES")
else:
print("NO") |
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the... | 3 | def main():
n_students = int(input())
students = [int(i) for i in input().split()]
ranks = set(students)
count_rank = [0] * ( max(students) + 1 )
for rank in ranks:
count_rank[rank] = students.count(rank)
res = ""
for student in students:
res += str(sum(count_rank[student+1:... |
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... | 1 | ###
for _ in range(input()):
a = raw_input()
if(len(a)>=11):
print a[0] + str(len(a) - 2) + a[-1]
else:
print a |
Chef, Artem and Eugene are the best of friends and teammates. Recently, they won a lot of money at the Are You Feeling Lucky Cup. Having put their fortune to test and emerging victorious, they are now busy enjoying their wealth. Eugene wanted to drink it all away. Chef and Artem had better plans.
Chef and Artem decide... | 1 | T = int(raw_input())
for t in xrange(T):
tickets = map(float, raw_input().split(" "))
print tickets[0] / ( tickets[0] + tickets[1] ) |
A lot of people in Berland hates rain, but you do not. Rain pacifies, puts your thoughts in order. By these years you have developed a good tradition β when it rains, you go on the street and stay silent for a moment, contemplate all around you, enjoy freshness, think about big deeds you have to do.
Today everything ... | 3 | import math
def main():
d, h, v, e = [int(v) for v in input().split()]
sq = math.pi * d * d / 4
total = sq * h
delta = -v + sq * e
if delta>0:
print("NO")
else:
time_v = -1*total/(delta)
print("YES")
print(time_v)
if __name__ == "__main__":
main()
|
Although Inzane successfully found his beloved bone, Zane, his owner, has yet to return. To search for Zane, he would need a lot of money, of which he sadly has none. To deal with the problem, he has decided to hack the banks.
<image>
There are n banks, numbered from 1 to n. There are also n - 1 wires connecting the ... | 3 | import sys
def solve():
n=int(sys.stdin.readline())
d=list(map(int,sys.stdin.readline().split()))
s=[[] for g in d]
mx_tmp=max(d)
mx_tmp2=max(g for g in d+[-2e9] if g<mx_tmp)
mxpt=[mx_tmp,mx_tmp2]
mxcnt=[d.count(mx_tmp),d.count(mx_tmp2)]
for i in range(1,n):
a,b=map(int,sys.stdin.readline().split())
a-=1;
... |
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.
Anton can perform the following sequence of operations any number of ti... | 3 | from sys import stdin,stdout
Pi = lambda x: stdout.write(str(x) + '\n')
Ps = lambda x: stdout.write(str(x))
S = lambda x: x*(x+1) // 2
I = lambda x: 1+(2*x)
R = lambda:stdin.readline()
Ri = lambda x:map(int,x.split())
Rs = lambda x:map(str,x.split())
Rf = lambda x:map(float,x.split())
MaxN = int(1e5) + 10
def main():
... |
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β an excerpt from contest rules.
A total of n participants took part in the contest (n β₯ k), and you already know their scores. Calculate how many ... | 1 | n,k = map(int,raw_input().split())
l = list(map(int,raw_input().split()))
count = 0
for i in range (0,len(l)):
if l[i] >= l[k-1] and l[i] > 0:
count += 1
print count |
Squirrel Liss lived in a forest peacefully, but unexpected trouble happens. Stones fall from a mountain. Initially Squirrel Liss occupies an interval [0, 1]. Next, n stones will fall and Liss will escape from the stones. The stones are numbered from 1 to n in order.
The stones always fall to the center of Liss's inter... | 1 | import sys
def main() :
coms = sys.stdin.readline().strip()
left = []
right = []
for i in range( len( coms ) ) :
if coms[ i ] == 'r' :
left.append( i + 1 )
else :
right.append( i + 1 )
for i in left :
print i
for i in reversed( right ) :
p... |
Vova, the Ultimate Thule new shaman, wants to build a pipeline. As there are exactly n houses in Ultimate Thule, Vova wants the city to have exactly n pipes, each such pipe should be connected to the water supply. A pipe can be connected to the water supply if there's water flowing out of it. Initially Vova has only on... | 1 | import math
n,k = map(int,raw_input().strip().split())
p=math.ceil((2*k-1 -(abs((2*k-1)**2-8*(n-1)))**(0.5))/2.0)
print int(0 if(n==1) else 1 if(n<=k) else -1 if(((2*k-1)**2-8*(n-1))<0) else 2 if(p==1) else p)
|
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | t = int(input())
for i in range(t):
n = int(input())
ch1 = input()
ch2 = input()
L1 = [int(j) for j in ch1.split()]
L2 = [int(j) for j in ch2.split()]
ma = min(L1)
mb = min(L2)
move = - (ma + mb)*n
for k in range(n):
... |
Akari has n kinds of flowers, one of each kind.
She is going to choose one or more of these flowers to make a bouquet.
However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.
How many different bouquets are there that Akari can make?
Find the count modulo (10^9 + 7).
Here,... | 3 | n,a,b = map(int,input().split())
M=10**9+7
def comb(n,a):
X = 1
for i in range(n-a+1,n+1):
X = X*i%M
Y = 1
for i in range(1,a+1):
Y = Y*i%M
return X*pow(Y,M-2,M)
ans = pow(2,n,M)-1-comb(n,a)-comb(n,b)
print(ans%M) |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 1 | import fileinput, sys
w = fileinput.input()[0].strip()
sys.stdout.write(w.upper() if sum(1 for c in w if c.isupper()) > len(w) // 2 else w.lower())
|
In some social network, there are n users communicating with each other in m groups of friends. Let's analyze the process of distributing some news between users.
Initially, some user x receives the news from some source. Then he or she sends the news to his or her friends (two users are friends if there is at least o... | 1 | import sys
from collections import Counter
rl = lambda: sys.stdin.readline().split()
n, m = map(int, rl())
group = range(n)
rank = [1] * n
def find(u):
if group[u] != u:
group[u] = find(group[u])
return group[u]
def union(u, v):
u = find(u)
v = find(v)
if u == v:
return
... |
Masha has n types of tiles of size 2 Γ 2. Each cell of the tile contains one integer. Masha has an infinite number of tiles of each type.
Masha decides to construct the square of size m Γ m consisting of the given tiles. This square also has to be a symmetric with respect to the main diagonal matrix, and each cell of ... | 3 | t = int(input())
for i in range(t):
n = [int(x) for x in input().split(' ')]
flag = 'NO'
for j in range(n[0]):
r1 = [int(x) for x in input().split(' ')]
r2 = [int(x) for x in input().split(' ')]
if flag == 'NO' and r1[1] == r2[0]:
flag = 'YES'
if n[1] % 2 == 1 or n[1] < 2:
flag = 'NO'
pr... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a = input ()
b = int (a)
if b == 2 :
print("NO")
elif b!=2 and b%2==0:
print("YES")
else :
print("NO")
|
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) β f(n-2) when n > 1, where β de... | 3 | def f(a,b,n):
'''if(n==0):
return a
elif(n==1):
return b
else:
return f(a,b,n-1)^f(a,b,n-2)'''
r=[a,b,a^b]
return r[n%3]
#l1=(l[i+0]^l[i+1] for i in range)
n=int(input())
re=[]
for i in range(0,n):
a,b,n=list(map(int,input().split()))
re.append(f(a,b,n))
... |
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved.
The square still has a rectangular shape of n Γ m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav... | 3 | for _ in range(int(input())):
a, b, x, y = map(int, input().split())
ans = 0
for _ in range(a):
s = input()
h = s.count(".")
p = s.count("..")
if 2 * x <= y:
ans += h * x
else:
ans += p * y + (h - 2 * p) * x
print(ans)
|
A bracketed sequence is called correct (regular) if by inserting "+" and "1" you can get a well-formed mathematical expression from it. For example, sequences "(())()", "()" and "(()(()))" are correct, while ")(", "(()" and "(()))(" are not.
The teacher gave Dmitry's class a very strange task β she asked every student... | 3 | from sys import stdin
from math import ceil
#for _ in range(int(stdin.readline())):
n = int(stdin.readline())
s = stdin.readline().strip()
if n%2==0 and s.count('(') == s.count(')'):
count = 0
ans = []
start = 0
val = 0
for i in range(n):
if s[i] == ')':
val -= 1
ans... |
Professor GukiZ makes a new robot. The robot are in the point with coordinates (x1, y1) and should go to the point (x2, y2). In a single step the robot can change any of its coordinates (maybe both of them) by one (decrease or increase). So the robot can move in one of the 8 directions. Find the minimal number of steps... | 3 | [a, b] = map(int, input().split())
[c, d] = map(int, input().split())
max = max(abs(c - a), abs(b - d))
print(max)
|
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th... | 3 | A = list(map(int,input().split()))
c=0
A.sort()
for i in range(0,3):
if A[i]==A[i+1]:
c=c+1
print(c)
|
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time.
Help Yaroslav.
Input
The first line contains integer n (1 β€ n β€ 100) β the numb... | 3 | n = int(input())
a = list(map(int, input().split()))
mx = 0
for i in a: mx = max(mx, a.count(i))
if n%2==1:
if mx>(n//2)+1: print('NO')
else: print('YES')
else:
if mx>n//2: print('NO')
else: print('YES')
|
A shop sells N kinds of fruits, Fruit 1, \ldots, N, at prices of p_1, \ldots, p_N yen per item, respectively. (Yen is the currency of Japan.)
Here, we will choose K kinds of fruits and buy one of each chosen kind. Find the minimum possible total price of those fruits.
Constraints
* 1 \leq K \leq N \leq 1000
* 1 \leq... | 3 | n,k = map(int,input().split())
li = list(map(int,input().split()))
li.sort()
print(sum(li[:k])) |
You are given three integers a, b and x. Your task is to construct a binary string s of length n = a + b such that there are exactly a zeroes, exactly b ones and exactly x indices i (where 1 β€ i < n) such that s_i β s_{i + 1}. It is guaranteed that the answer always exists.
For example, for the string "01010" there ar... | 3 | a, b, x = map(int, input().split(' '))
s = ''
if x % 2 == 1:
if a > b:
for i in range(a-(x-1)//2):
s += '0'
for i in range((x-1)//2):
s += '10'
for i in range(b-(x-1)//2):
s += '1'
else:
for i in range(b-(x-1)//2):
s += '1'
... |
Panic is rising in the committee for doggo standardization β the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between dog... | 3 | import sys
n = int(input())
a = input()
a = list(a)
b = list(set(a))
k = []
if len(b) == 1:
print('Yes')
sys.exit()
for i in range(len(b)):
k.append(a.count(b[i]))
if max(k) > 1:
print('Yes')
else:
print('No')
|
There is a famous olympiad, which has more than a hundred participants. The Olympiad consists of two stages: the elimination stage, and the final stage. At least a hundred participants will advance to the final stage. The elimination stage in turn consists of two contests.
A result of the elimination stage is the tota... | 3 | import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def MI(): return map(int, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() ... |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
st = input()
prev_el = ""
i = 0
for el in st:
if(el == prev_el):
i += 1
else:
prev_el = el
print(i) |
You are given two positive integers n (1 β€ n β€ 10^9) and k (1 β€ k β€ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, β¦, a_k such that all a_i>0, n = a_1 + a_2 + β¦ + a_k and either all a_i are even or all a_i ar... | 3 | def parity(n,k):
lst = []
s = 'YES'
if n%2 !=0 and k%2 == 0:
return 'NO',[]
else:
if n%2 == 0 and k <= n//2:
lst+= ['2']*(k-1)
last = n-(2*(k-1))
if last %2 != 0 or last<=0:
return 'NO',[]
lst.append(str(last))
# elif n%2 == 0 and k > n//2 :
# lst += ['1']*(k-1)
# last = n-(1*(k... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.