problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
For an integer N, we will choose a permutation \\{P_1, P_2, ..., P_N\\} of \\{1, 2, ..., N\\}.
Then, for each i=1,2,...,N, let M_i be the remainder when i is divided by P_i.
Find the maximum possible value of M_1 + M_2 + \cdots + M_N.
Constraints
* N is an integer satisfying 1 \leq N \leq 10^9.
Input
Input is giv... | 1 | n = int(raw_input())
print (n-1)*n/2 |
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not.
Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro... | 3 | '''
Created on Jun 30, 2016
@author: Md. Rezwanul Haque
'''
s = input()
ss = s[::-1]
res = s+ss
print(res) |
You are given a trapezoid. The lengths of its upper base, lower base, and height are a, b, and h, respectively.
<image>
An example of a trapezoid
Find the area of this trapezoid.
Constraints
* 1β¦aβ¦100
* 1β¦bβ¦100
* 1β¦hβ¦100
* All input values are integers.
* h is even.
Input
The input is given from Standard Input i... | 3 | l=[int(input()) for _ in [0]*3]
print((l[0]+l[1])*l[2]//2) |
Every summer Vitya comes to visit his grandmother in the countryside. This summer, he got a huge wart. Every grandma knows that one should treat warts when the moon goes down. Thus, Vitya has to catch the moment when the moon is down.
Moon cycle lasts 30 days. The size of the visible part of the moon (in Vitya's units... | 3 | N = int(input())
A = list(map(int, input().split()))
if N == 1:
if A[0] == 0:
print("UP")
elif A[0] == 15:
print("DOWN")
else:
print(-1)
else:
if A[-1] == 0:
print("UP")
elif A[-1] == 15:
print("DOWN")
else:
if A[-1] > A[-2]:
print("UP... |
k people want to split n candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from 1 to k, and Arkady is the first of them. To split the candies, Arkady will choose an integer x and then give the first x candies to himself, the next x candies to the second ... | 1 | n,k,m,d=map(int,raw_input().split())
s=0
for i in range(d):
t=(k*i)+1
r=n/t
r=min(r,m)
w=r*(i+1)
if(w>s):
s=w
print s |
You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t... | 3 | import sys
I=sys.stdin.readline
ans=""
for _ in range(int(I())):
n=int(I())
arr=list(map(int,I().split()))
grp=[arr[0]]
for i in range(1,n):
flag=1
for j in range(len(grp)):
if abs(grp[j]-arr[i])<=1:
flag=0
break
if flag:
grp.append(arr[i])
if n-len(grp)>0:
ans+="{}\n".format(2)
else:
ans... |
Sasha is a very happy guy, that's why he is always on the move. There are n cities in the country where Sasha lives. They are all located on one straight line, and for convenience, they are numbered from 1 to n in increasing order. The distance between any two adjacent cities is equal to 1 kilometer. Since all roads in... | 3 | dis,cap=map(int,input().split())
#req fuel will be one less than the distance
cost=0
if dis<=cap:
#here the minimum cost will be the distance itself
cost=dis-1
else:
cost+=cap
#intially just fill the tank and then
for i in range(2,dis-cap+1):#gives upto which part the tank should be given fuel
... |
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 ok(x):
while x % 2 == 0:
x //= 2
return x
t = int(input())
for i in range(t):
a,b = map(int,input().split())
if b > a:
c = a
a = b
b = c
r = ok(a)
r2 = ok(b)
if r != r2:
print("-1")
else:
ans = 0
a //= b
ans = 0
... |
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character... | 3 | #Codeforces 731 A - Night at the Museum
base = ord('a')
total = ord('z')-base+1
s = input()
current = 0
moves = 0
for c in s:
newp = ord(c)-base
op1 = abs(current-newp)
op2 = 26-op1
mn = min(op1,op2)
moves += mn
current = newp
print(moves)
|
One day, Twilight Sparkle is interested in how to sort a sequence of integers a1, a2, ..., an in non-decreasing order. Being a young unicorn, the only operation she can perform is a unit shift. That is, she can move the last element of the sequence to its beginning:
a1, a2, ..., an β an, a1, a2, ..., an - 1.
Help Twi... | 3 | n = int(input())
s = list(map(int,input().split()))
for x in range(1,n):
if s[x-1]>s[x]:
print ((-1,n-x)[sorted(s) == s[x:] + s[:x]])
break
else:
print (0)
# Made By Mostafa_Khaled |
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002.
You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2.
Let's define the ternary XOR operation β of two ternary n... | 3 | t=int(input())
for i in range(t):
n=int(input())
s=input()
s1=str()
s2=str()
flag=0
for j in range(n):
if flag==0:
if s[j]=='2':
s1+='1'
s2+='1'
elif s[j]=='0':
s1+='0'
s2+='0'
else:
flag=1
s1+='1'
s2+='0'
else:
... |
You have given an array a of length n and an integer x to a brand new robot. What the robot does is the following: it iterates over the elements of the array, let the current element be q. If q is divisible by x, the robot adds x copies of the integer q/x to the end of the array, and moves on to the next element. Note ... | 3 | t=int(input())
for _ in range(t):
n,x=list(map(int,input().split()))
a=list(map(int,input().split()))
m,ind=10**(9),0
for i in range(n):
if a[i]%x!=0:
ind=i
m=0
break
else:
c=0
t=a[i]
while t%x==0:
t=... |
We held two competitions: Coding Contest and Robot Maneuver.
In each competition, the contestants taking the 3-rd, 2-nd, and 1-st places receive 100000, 200000, and 300000 yen (the currency of Japan), respectively. Furthermore, a contestant taking the first place in both competitions receives an additional 400000 yen.... | 3 | x, y = map(int, input().split())
c = 0
if x <= 3:
c += 100000 * (4 - x)
if y <= 3:
c += 100000 * (4 - y)
if x == y == 1:
c += 400000
print(c)
|
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order β their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | sums = list(map(int, input().split()))
sums.sort()
num1 = sums[-1] - sums[-2]
num2 = sums[0] - num1
num3 = sums[-1] - num1 - num2
print(num1, num2, num3)
|
Takahashi has two positive integers A and B.
It is known that A plus B equals N. Find the minimum possible value of "the sum of the digits of A" plus "the sum of the digits of B" (in base 10).
Constraints
* 2 β€ N β€ 10^5
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Outp... | 3 | N = int(input())
if N%10 ==0:
ans = 10
else:
NN = list(str(N))
ans = 0
for i in NN:
ans += int(i)
print(ans)
|
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 | def solve(s):
n = len(s)
arr = []
c = 0
for i in s:
if i == "0":
if c > 0:
arr.append(c)
c = 0
else:
c += 1
if c > 0:
arr.append(c)
arr.sort(reverse=True)
i = 0
ans = 0
while i < len(arr):
ans +... |
Ujan decided to make a new wooden roof for the house. He has n rectangular planks numbered from 1 to n. The i-th plank has size a_i Γ 1 (that is, the width is 1 and the height is a_i).
Now, Ujan wants to make a square roof. He will first choose some of the planks and place them side by side in some order. Then he will... | 3 | for _ in range(int(input())):
n = int(input())
a = [int(s) for s in input().split()]
a = sorted(a)[::-1]
m = 0
for i in range(1, n+1):
m = max(m, min(i, a[i-1]))
print(m) |
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | 3 | #https://codeforces.com/problemset/problem/9/A
def gcd(a,b):
if a%b==0:
return b
return gcd(b,a%b)
a,b=map(int,input().split())
n=6-max(a,b)+1
d=6
g=gcd(n,d)
n=n//g
d=d//g
print(n,'/',d,sep='')
|
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | def binarysearch(L,left,right,k):
mid=(left+right)//2
if(L[left]==k):
return left
elif(L[right]==k):
return right
elif(L[mid]==k):
return mid
elif(L[right]<k) or (L[left]>k):
return -1
elif(L[mid]<k):
return binarysearch(L,mid+1,right,k)
elif(L[mid]>k):
return binarysearch(L,left,mid,k)
else:
ret... |
Holidays have finished. Thanks to the help of the hacker Leha, Noora managed to enter the university of her dreams which is located in a town Pavlopolis. It's well known that universities provide students with dormitory for the period of university studies. Consequently Noora had to leave ViΔkopolis and move to Pavlopo... | 3 | from math import factorial, gcd
a, b = map(int, input().split())
print(factorial(min(a, b)))
|
Each student eagerly awaits the day he would pass the exams successfully. Thus, Vasya was ready to celebrate, but, alas, he didn't pass it. However, many of Vasya's fellow students from the same group were more successful and celebrated after the exam.
Some of them celebrated in the BugDonalds restaurant, some of them... | 3 | a , b , c , n = map( int , input().split( ) )
ans = n - ((a+b)-c)
if ans<=0 or a<c or b<c:
print(-1)
else:
print(ans) |
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | line = input()
lst = list(line)
letters = []
excl = [" ",",","{","}"]
for k in lst:
if(k not in excl):
if(k not in letters):
letters.append(k)
print(len(letters)) |
Write a program which solve a simultaneous equation:
ax + by = c
dx + ey = f
The program should print x and y for given a, b, c, d, e and f (-1,000 β€ a, b, c, d, e, f β€ 1,000). You can suppose that given equation has a unique solution.
Input
The input consists of several data sets, 1 line for each data set. In a ... | 3 | while True:
try:
a, b, c, d, e, f = map(float, input().split())
n = a*e - b*d
if n != 0:
x = (c*e - b*f) / n
y = (a*f - c*d) / n
print('{:.3f} {:.3f}'.format(x+0, y+0))
except:
break
|
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones.
Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ... | 1 | n = int(raw_input())
s = map(int, list(raw_input()))
k = sum(s)
n = n-k
if k > n: print k-n
else: print n-k
|
In Berland it is the holiday of equality. In honor of the holiday the king decided to equalize the welfare of all citizens in Berland by the expense of the state treasury.
Totally in Berland there are n citizens, the welfare of each of them is estimated as the integer in ai burles (burle is the currency in Berland).
... | 1 | import math
import random
def close(x):
if math.fabs(round(x) - x) < 0.000001:
return int(round(x))
return int(x)
def inp():
return int(raw_input().strip())
def inp_arr():
return map(int, raw_input().strip().split())
n = inp()
arr = inp_arr()
if n == 1:
print 0
else:
m = max(*arr... |
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh... | 3 | n = int(input())
t = list(map(int, input().split()))
n = len(t)
t.sort()
ans = 1
s = t[0]
for i in range(1,n):
if s <= t[i]:
ans += 1
s += t[i]
print(ans)
|
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 β€ i β€ j β€ n - 1), that <image>... | 3 | def countways(a, n):
cnt = [0 for i in range(n)]
s = 0
s = sum(a)
if (s % 3 != 0):
return 0
s //= 3
ss = 0
for i in range(n - 1, -1, -1):
ss += a[i]
if (ss == s):
cnt[i] = 1
for i in range(n - 2, -1, -1):
cnt[i] += cnt[i + 1]
ans = 0
ss... |
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 | year = input()
for i in range(8000):
year = int(year)
year += 1
year = str(year)
if year.count(year[0]) == year.count(year[1]) == year.count(year[2]) == year.count(year[3]) == 1:
break
print(year)
|
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The on... | 1 | print sum(2**k for k in range(1, input() + 1)) |
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... | 1 | a = input()
if a % 2 == 0 and a != 2:
print("YES")
else:
print("NO") |
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy... | 3 | vectors = int(input())
x, y, z = 0, 0, 0
for vector in range(vectors):
tx, ty, tz = (map(int,input().split()))
x += tx
y += ty
z += tz
if x == y and y == z and x == 0:
print("YES")
else:
print("NO") |
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 | def stone_on_table() :
n = int(input())
stones = input().upper()
if n > 50 or n < 1 or len(stones) != n:
return
for i in stones :
if i != 'R' and i != 'B' and i != 'G':
return
count = 0
for i in range(len(stones)-1) :
if stones[i] == stones[i+1] :
... |
A monster is chasing after Rick and Morty on another planet. They're so frightened that sometimes they scream. More accurately, Rick screams at times b, b + a, b + 2a, b + 3a, ... and Morty screams at times d, d + c, d + 2c, d + 3c, ....
<image>
The Monster will catch them if at any point they scream at the same tim... | 1 | a, b = map(int,raw_input().split())
c, d = map(int,raw_input().split())
rick = [b + i * a for i in range(102)]
morty = [d + i * c for i in range(102)]
ans = 100000
for x in rick:
if x in morty:
ans = x
break
for x in morty:
if x in rick:
ans = min(ans, x)
break
if ans == 10000... |
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())
s=0
while a<=b:
s+=1
a=int(a*3)
b=int(b*2)
print(s) |
You are given an array of n integers a_1,a_2,...,a_n.
You have to create an array of n integers b_1,b_2,...,b_n such that:
* The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_... | 3 | for _ in range(int(input())):
n = int(input())
data = list(map(int, input().split()))
minus = 0
plus = 0
for x in data:
if x < 0:
minus += -x
else:
plus += x
if sum(data) == 0:
print("NO")
else:
if minus > plus:
data.... |
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task.
Recently, out of blue Captain Flint has been interested in ma... | 3 | nearly_prime = [6, 10, 14, 15, 21]
sum_ = 6 + 10 + 14
t = int(input())
for _ in range(t):
n = int(input())
if n <= sum_:
print("NO")
else:
for bit_state in range(1 << 5):
cnt = 0
tmp = []
for i in range(5):
if (1 << i) & bit_state:
... |
Luba has to do n chores today. i-th chore takes ai units of time to complete. It is guaranteed that for every <image> the condition ai β₯ ai - 1 is met, so the sequence is sorted.
Also Luba can work really hard on some chores. She can choose not more than k any chores and do each of them in x units of time instead of a... | 3 | n,k,x = map(int, input().split())
a = list(map(int, input().split()))
a = a[::-1]
for i in range(k):
a[i] = min(a[i], x)
print(sum(a)) |
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
* ... | 3 | s = input()
a = len(s)
numbers = {}
for x in range(a):
for y in range(x + 1, a + 1):
t = s[x:y]
for z in t:
p = int(z)
if p != 4 and p != 7:
break
else:
p = int(t)
if not p in numbers:
numbers[p] = 0
... |
The Third Doctor Who once correctly said that travel between parallel universes is "like travelling sideways". However, he incorrectly thought that there were infinite parallel universes, whereas in fact, as we now all know, there will never be more than 250.
Heidi recently got her hands on a multiverse observation to... | 3 | n, k, m, t = map(int, input().split())
for i in range(t):
a, b = map(int, input().split())
if a:
if b<=k and n+1<=m:
k+=1
n+=1
elif b>k and n+1<=m:
n+=1
else:
if b<k:
k-=b
n-=b
elif b>=k:
n-=(n-b)
... |
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 | # a = str(raw_input())
# b = str(raw_input())
# c = len(a)
# d = len(b)
# f = 0
# if c > d:
# e = c-d
# f = str(b)+ ('0' * e)
# elif d > c:
# e = d - c
# f = str(a)+ ('0' * e)
# #int(a)
# #int(f)
# #print(type(a),type(f))
# if int(a) - int(f) > 0:
# print(">")
# elif int(a) - int(f) < 0 :
# pr... |
One day Sasha visited the farmer 2D and his famous magnetic farm. On this farm, the crop grows due to the influence of a special magnetic field. Maintaining of the magnetic field is provided by n machines, and the power of the i-th machine is a_i.
This year 2D decided to cultivate a new culture, but what exactly he d... | 3 | import sys
n = int(sys.stdin.readline())
a = [int(tmp) for tmp in sys.stdin.readline().split()]
lf = [0] * 101
for ea in a:
lf[ea] += 1
md = 0
i = 1
j = 100
m = 2
while i * m < j and lf[i] == 0:
i += 1
while i * m < j and lf[j] == 0:
j -= 1
while m * i < j:
while m * i < j:
if lf[j] == 0:
... |
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... | 3 | s = input()
size = len(s)
cnt_upper = 0
cnt_lower = 0
for i in range(size):
if(s[i].islower()):
cnt_lower += 1
elif(s[i].isupper()):
cnt_upper += 1
if(cnt_lower>=cnt_upper):
print(s.lower())
else:
print(s.upper()) |
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()
c=0
for i in s:
if(i=='4' or i=='7'):
c+=1
if(c==4 or c==7):
print('YES')
else:
print('NO')
|
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 | no_stops = int(input())
current_capactiy = 0
max_capacity = 0
for i in range(no_stops):
inp = input()
exited, entered = int(inp.split(' ')[0]), int(inp.split(' ')[1])
current_capactiy = current_capactiy - exited + entered
if current_capactiy > max_capacity:
max_capacity = current_capactiy
pri... |
Masha has three sticks of length a, b and c centimeters respectively. In one minute Masha can pick one arbitrary stick and increase its length by one centimeter. She is not allowed to break sticks.
What is the minimum number of minutes she needs to spend increasing the stick's length in order to be able to assemble a ... | 1 | import sys
a,b,c=map(int,sys.stdin.readline().split())
maxi=max(a,b,c)
if maxi==a:
if b+c<=a:
ans=a-(b+c)+1
else:
ans=0
elif maxi==b:
if a+c<=b:
ans=b-(a+c)+1
else:
ans=0
else:
if a+b<=c:
ans=c-(a+b)+1
else:
ans=0
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 | import math
n,m=list(map(int,input().split()))
ans=0
for i in range(1,n+1):
ans+=math.ceil(((i+m)//5*5-i)/5)
print(ans) |
You are given k sequences of integers. The length of the i-th sequence equals to n_i.
You have to choose exactly two sequences i and j (i β j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the... | 3 | import sys
Q = int(input())
tot = []
totlen = 0
for i in range(Q):
n = int(input())
l = list(map(int,input().split()))
s = sum(l)
totlen += n
for j in range(n):
tot += [[s-l[j] , i+1 , j+1]]
tot.sort()
for i in range(totlen-1):
if tot[i][0] == tot[i+1][0]:
if tot[i][1] !=... |
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n.
Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times.
Alice wins if she beats Bob in at lea... | 3 | import math
t = int(input())
while t:
t -= 1
n = int(input())
a, b, c = list(map(int, input().split()))
s = input()
ans = 0
s1 = [None] * n
i = 0
for char in s:
if char == 'R':
if b > 0:
b -= 1
ans += 1
s1[i] = 'P'
... |
Two players are playing a game. The game is played on a sequence of positive integer pairs. The players make their moves alternatively. During his move the player chooses a pair and decreases the larger integer in the pair by a positive multiple of the smaller integer in the pair in such a way that both integers in the... | 1 | #!/usr/bin/env python
#-*- coding:utf-8 -*-
def convert_pair(a, b):
res = []
if a < b:
a, b = b, a
while b:
res.append(a / b)
a, b = b, a % b
res[-1] -= 1
while res[-1] == 0:
del res[-1]
return tuple(res)
def grundy(col):
res = 0
for N in reversed(col)... |
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 | def compressIfLong(string: str) -> str:
stringLength = len(string)
if stringLength > 10:
return string[0] + str(stringLength-2) + string[stringLength-1]
return string
def main():
testCases = int(input().strip())
for _ in range(testCases):
string = input().strip()
print(comp... |
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th... | 1 | #!/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
import random
import collections
import math
import itert... |
Little boy Petya loves stairs very much. But he is bored from simple going up and down them β he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
No... | 3 | n, m = map(int, input().split())
if m == 0: print('YES')
else:
t = list(map(int, input().split()))
t.sort()
if t[0] == 1 or t[-1] == n: print('NO')
else:
k = s = 0
for i in t:
if i == k:
s += 1
k += 1
if s > 1:
... |
Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.
Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death. As he wants to live, he cannot eat one in su... | 3 | A,B,C=map(int,input().split())
if A+B>=C:
print(B+C)
else:
print(B*2+A+1)
|
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order.
According to the schedule, a stud... | 3 | n, a, c = int(input()), [], 0
for i in range(n):
x, y = list(map(int, input().split()))
a.append([x, y])
a.sort()
for i in range(n):
if a[i][1] >= c:
c = a[i][1]
else:
c = a[i][0]
print(c) |
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help.
Artem wants to paint an n Γ m board. Each cell of the board should be colored in white or black.
Lets B be the number of black cells that have at least one white neighbor adja... | 3 | t = int(input())
for i in range(t):
n, m = map(int, input().split())
for i in range(n-1):
print("W" + "B" * (m-1))
print("B" * m) |
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 3 | from collections import deque
n,m = map(int, input().split())
# print(n,m)
graph={}
graph[n]=[n-1,n*2]
queue=deque()
queue+=[n]
searched={}
k=[1]
i=1
s=0
def check_number(a):
if (a==m):
return True
if (a>m):
graph[a]=[a-1]
if (a<m):
graph[a] = [a-1, 2*a]
searched[a]=1
retu... |
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 |
def main():
t=int(input())
for _ in range(t):
n,k=map(int,input().split())
s=input()
l=0
r=l+1
ans=0
while r<n :
if s[r]=='1':
if s[l]=='0' and r<n:
len=r-l
len-=k
elif ... |
You have n students under your control and you have to compose exactly two teams consisting of some subset of your students. Each student had his own skill, the i-th student skill is denoted by an integer a_i (different students can have the same skills).
So, about the teams. Firstly, these two teams should have the s... | 3 | from collections import Counter
for _ in range(int(input())):
ans = 0
n = int(input())
ac = Counter(list(map(int, input().split())))
kl = len(ac.keys())
if kl == 1:
if n == 1:
print(0)
else:
print(1)
continue
for k, v in ac.most_common():
i... |
Taro is playing with a puzzle that places numbers 1-9 in 9x9 squares. In this puzzle, you have to arrange the numbers according to the following rules.
* One number appears exactly once in the same column
* A number appears exactly once on the same line
* In each of the 3x3 ranges separated by double lines, a number a... | 1 | R=[0,3,6]
N=range(9)
Z=[0]*9
n=input()
while n:
M=[]
F=[[" " for _ in Z] for _ in Z]
M=[map(int,raw_input().split()) for _ in Z]
M1=[[M[y][x] for y in N] for x in N]
M2=[M[y][x:x+3]+M[y+1][x:x+3]+M[y+2][x:x+3] for y in R for x in R]
for y in N:
A=M[y]
for x in N:
A1=M2[x/3+y/3*3]
a=A[x]... |
Returning back to problem solving, Gildong is now studying about palindromes. He learned that a palindrome is a string that is the same as its reverse. For example, strings "pop", "noon", "x", and "kkkkkk" are palindromes, while strings "moon", "tv", and "abab" are not. An empty string is also a palindrome.
Gildong lo... | 3 | def isPalindrome(s):
rev = ''.join(reversed(s))
if (s == rev):
return True
return False
n,l=map(int , input().strip().split())
arr=[]
for i in range(n):
arr.append(input())
raj=list()
visited=[0]*n
for i in range(n):
s=arr[i][::-1]
for j in range(n):
if(arr[j]==s and visit... |
Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the... | 3 | # print(-5//5)
a,b,c=map(int,input().split(' '))
if( a<b and c<0) or (b<a and c>0):
print('NO')
quit()
if c==0:
if a==b:
print('YES')
else :
print('NO')
quit()
d=(b-a)//c
# print(d)
if d*c+a==b:
print("YES")
else :
print('NO')
|
A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w... | 3 | import sys
ii = lambda: sys.stdin.readline().strip()
idata = lambda: [int(x) for x in ii().split()]
def solve():
n, k = idata()
data = list(map(str, ii()))
slov = {}
for i in range(k):
slov[i] = '?'
for i in range(n):
if data[i] != '?':
if slov[i % k] != '?':
... |
For some binary string s (i.e. each character s_i is either '0' or '1'), all pairs of consecutive (adjacent) characters were written. In other words, all substrings of length 2 were written. For each pair (substring of length 2), the number of '1' (ones) in it was calculated.
You are given three numbers:
* n_0 β th... | 3 | t = int(input())
for t in range(t):
n0, n1, n2 = [int(i) for i in input().split(" ")]
ans = ""
extra0 = extra1 = 1
if n1 == 0:
extra0 = extra1 = 0
if n0 > 0:
extra0 = 1
else:
extra1 = 1
ans += "0"*(n0+extra0)
ans += "1"*(n2+extra1)
for i in ran... |
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a:
* Remove any two elements from a and append their sum to... | 3 | for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split(" ")))
e = [] ; o = []
for i in range(len(l)):
if (l[i]%2 == 0):
e.append(i+1)
else:
o.append(i+1)
if (len(e)%2 == 1):
e.pop(-1) ; o.pop(-1)
else:
if (len(e) >= 2):
e.pop(-1)
e.pop(-1)
else:
o.pop(-1)
o.pop(-... |
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | 3 | str = input()
print (25*len(str)+26) |
Polycarp was gifted an array a of length n. Polycarp considers an array beautiful if there exists a number C, such that each number in the array occurs either zero or C times. Polycarp wants to remove some elements from the array a to make it beautiful.
For example, if n=6 and a = [1, 3, 2, 1, 4, 2], then the followin... | 1 |
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
t=int(input())
for _ in ra... |
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 | n=int(raw_input())
arr=[]
for i in range(n):
arr.append(str(raw_input()))
for k in arr:
if len(k)>10:
print k[0]+str(len(k)-2)+k[-1]
else:
print k
|
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
from functools import lru_cache #use @lru_cache(None)
if os.path.exists('in.txt'): sys.stdin=open('in.txt','r')
if os.path.exists('out.txt'): sys.stdout=open('out.txt', 'w')
#
def input(): return sys.stdin.readline()
def mapi(arg=0): ret... |
ZS the Coder is playing a game. There is a number displayed on the screen and there are two buttons, ' + ' (plus) and '<image>' (square root). Initially, the number 2 is displayed on the screen. There are n + 1 levels in the game and ZS the Coder start at the level 1.
When ZS the Coder is at level k, he can :
1. Pr... | 3 | n = int(input())
for i in range(0,n) :
if i == 0 :
print(2)
else :
print((i+2)*(i+2)*(i+1)-(i)) |
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i β j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d).
For example, the following sequences are good:
* [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum ... | 3 | from sys import stdin,stdout
from math import ceil,log
def main():
d={}
n=int(stdin.readline())
a=list(map(int,stdin.readline().split( )))
m=-1;mm=10**10
for v in a:
if v not in d:
d[v]=1
else:
d[v]+=1
m=max(m,v)
mm=min(mm,v)
ans=0
for v in a:
exponent=ceil(log(v,2))
power=2**exponent
fi... |
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly gre... | 3 | #Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
for _ in range(int(input())):
k, n, a, b = map(int, input().split())
x = (k-n*b)//(a-b)
if k <= n*b:
print(-1)
else:
if (k-n*... |
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 β€ n β€ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 3 | n = int(input())
f = 0
x = -1
if n % 2 == 0:
f = n // 2
else:
f = n // 2 - n
print(f) |
Today, Mezo is playing a game. Zoma, a character in that game, is initially at position x = 0. Mezo starts sending n commands to Zoma. There are two possible commands:
* 'L' (Left) sets the position x: =x - 1;
* 'R' (Right) sets the position x: =x + 1.
Unfortunately, Mezo's controller malfunctions sometimes. ... | 1 | print(input()+1) |
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | 3 | N = int(input())
for _ in range(N):
num = int(input())
if num % 2 == 1:
print("7", end="")
else:
print("1", end="")
num //= 2
for _ in range(num - 1):
print("1", end="")
print()
|
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... | 3 | n, x = map(int, input().split())
if n == 1 and x == 10:
print('-1')
else:
if x == 10:
print('1', end = '')
while n > 1:
n -= 1
print('0', end = '')
else:
while n > 0:
print(x, end = '')
n -= 1
|
Snuke has decided to use a robot to clean his room.
There are N pieces of trash on a number line. The i-th piece from the left is at position x_i. We would like to put all of them in a trash bin at position 0.
For the positions of the pieces of trash, 0 < x_1 < x_2 < ... < x_{N} \leq 10^{9} holds.
The robot is initi... | 3 | I=lambda:map(int,input().split())
N,X=I()
w=[0]
for i in I():w+=[w[-1]+i]
print(min(5*w[N]+k*X+sum(2*w[j]for j in range(N-k*2,0,-k))for k in range(1,N+1))+N*X) |
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | 3 | # Problem 136 A - Presents
# input
n = int(input())
p_nums = list(map(int, input().split()))
# initialization
ans_nums = [0]*n
# count
for i in range(n):
p = p_nums[i]
ans_nums[p-1] = i + 1
# output
print(" ".join(list(map(str, ans_nums))))
|
You are given two positive integers a and b.
In one move, you can change a in the following way:
* Choose any positive odd integer x (x > 0) and replace a with a+x;
* choose any positive even integer y (y > 0) and replace a with a-y.
You can perform as many such operations as you want. You can choose the sam... | 3 | n = int(input())
for i in range(n):
a, b = map(int, input().split())
if a == b:
print(0)
else:
if a > b and (a - b) % 2 == 0:
print(1)
elif a > b and (a - b) % 2 == 1:
print(2)
elif a < b and (b - a) % 2 == 0:
print(2)
elif a < b an... |
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q... | 1 | n,x=map(int,raw_input().split())
c=0
for i in range(n):
a=raw_input()
s=a[0]
n=int(a[2:len(a)])
if(s=='-'):
n=(-1)*n
if x+n<0:
c+=1
else:
x+=n
print x,c |
There are n points on the plane, (x_1,y_1), (x_2,y_2), β¦, (x_n,y_n).
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
I... | 3 | """
Satwik_Tiwari ;) .
20 june , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IO... |
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... | 3 | import random, math
n = [int(x) for x in input().split()]
if 10 ** n[0] - 1 < n[1]:
print(-1)
exit(0)
x = random.randint(10 ** (n[0] - 1), 10 ** n[0] - 1)
if x % n[1] != 0:
x1 = (x // n[1]) * n[1]
x2 = math.ceil(x / n[1]) * n[1]
print(x if x % n[1] == 0 else (x1 if x1 >= 10 ** (n[0] - 1) and x1 <= 10 ** n[0] else ... |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | 3 | for _ in range(int(input())):
a = list(map(int, input().split()))
b = list(map(int, input().split()))
cnt = 0
mn = min(a[2], b[1])
cnt += mn * 2
a[2] -= mn
b[1] -= mn
# print(a, b)
mn = min(a[2], b[2])
a[2] -= mn
b[2] -= mn
# print(a, b)
mn = min(a[2], b[0])
a[2] -= mn
b[0] -= mn
# print(a, b)
mn = mi... |
Snuke loves working out. He is now exercising N times.
Before he starts exercising, his power is 1. After he exercises for the i-th time, his power gets multiplied by i.
Find Snuke's power after he exercises N times. Since the answer can be extremely large, print the answer modulo 10^{9}+7.
Constraints
* 1 β€ N β€ 10... | 3 | n=int(input())
p=1
for i in range(1,n+1):
p=p*i%(10**9+7)
print(p)
|
Polycarp is sad β New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them ... | 3 | t=int(input())
while(t!=0):
r,g,b=sorted(list(map(int,input().split())))
if(r==g and g==b and b==r):
print("Yes")
elif (g<=b<=r+g+1):
print("Yes")
else:
print("No")
#print(r)
#print(g)
#print(b)
t-=1 |
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... | 1 | s = raw_input()
d = {}
for i, c in enumerate(s):
if c not in d:
d[c] = []
d[c].append(i)
pos = {}
i = 0
ok = True
for c in "hello":
if c not in d:
ok = False
break
if c not in pos:
pos[c] = 0
e = d[c]
found = False
for j in range(pos[c], len(e)):
if e[j] >= i:
found = True
pos[c] = j + 1
i ... |
You are given three positive (i.e. strictly greater than zero) integers x, y and z.
Your task is to find positive integers a, b and c such that x = max(a, b), y = max(a, c) and z = max(b, c), or determine that it is impossible to find such a, b and c.
You have to answer t independent test cases. Print required a, b a... | 3 | from math import *
from copy import *
from string import * # alpha = ascii_lowercase
from random import *
from sys import stdin,stdout
from sys import maxsize
from operator import * # d = sorted(d.items(), key=itemgetter(1))
from itertools import *
from collections import Counter # d = dict(Counter(l))
import ma... |
The country of Byalechinsk is running elections involving n candidates. The country consists of m cities. We know how many people in each city voted for each candidate.
The electoral system in the country is pretty unusual. At the first stage of elections the votes are counted for each city: it is assumed that in each... | 3 | def list(l):
d=[]
for i in range(len(l)):
d.append(int(l[i]))
return d
l=input()
l=l.split()
n=int(l[0])
m=int(l[1])
s=[]
for k in range(n):
s.append(0)
for i in range(m):
a=list(input().split())
j=a.index(max(a))
s[j]+=1
print(s.index(max(s))+1) |
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute.
He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it... | 1 | n, s = map(int, raw_input().split())
t = None
for i in range(n):
h, m = map(int, raw_input().split())
t1 = h * 60 + m
if t is None:
if t1 >= s + 1:
print("0 0")
exit(0)
else:
if t1 - t - 1 >= 2 * s + 1:
t += s + 1
h = t // 60
m ... |
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn.
More formally, the guys take turns giving each ot... | 3 | a,b=[int(i) for i in input().split()]
count=1
while(True):
if(count%2==1):
if(a>=count):
a-=count
count+=1
else:
print("Vladik")
break
else:
if(b>=count):
b-=count
count+=1
else:
print("Valera")... |
You've got a 5 Γ 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | #coding=utf-8
#i=lambda:map(int,input().split())
r = []
c = [0, 0, 0, 0, 0]
for i in range(5):
i = input().strip()
i_ = list(map(int, i.split()))
for i in range(5):
c[i] = c[i] + i_[i]
r.append(sum(i_))
res = abs(2 - r.index(1)) + abs(2 - c.index(1))
print(res)
|
Bees Alice and Alesya gave beekeeper Polina famous card game "Set" as a Christmas present. The deck consists of cards that vary in four features across three options for each kind of feature: number of shapes, shape, shading, and color. In this game, some combinations of three cards are said to make up a set. For every... | 3 | n, k = [int(x) for x in input().strip().split()]
def match(a, b):
s = []
for i in range(k):
if a[i] == b[i]:
s.append(a[i])
elif a[i] == 'S':
if b[i] == 'E':
s.append('T')
elif b[i] == 'T':
s.append('E')
elif a[i] == 'E':
if b[i] == 'S':
s.append('T')
... |
Marina loves strings of the same length and Vasya loves when there is a third string, different from them in exactly t characters. Help Vasya find at least one such string.
More formally, you are given two strings s1, s2 of length n and number t. Let's denote as f(a, b) the number of characters in which strings a and ... | 1 | n,k=map(int,raw_input().split())
a=list(raw_input())
b=list(raw_input())
c=a[:]
d=[i for i in range(n) if a[i]!=b[i]]
while k and len(d)>k:
i=d.pop()
c[i]=a[i]
i=d.pop()
c[i]=b[i]
k-=1
while d and k:
i=d.pop()
c[i]=[x for x in 'abc' if x!=a[i] and x!=b[i]][0]
k-=1
if k:
for i in range(n):
if a[i]=... |
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s.
You have to answer t independent test cases.
Input
The first line of the input co... | 3 | import sys
from math import sqrt
from collections import defaultdict
inpt = sys.stdin.readline
def inp():
return(int(inpt()))
def inlist():
return(list(map(int,inpt().split())))
def instr():
s = inpt()
return(list(s[:len(s)-1]))
def invr():
return(map(int,inpt().split()))
class Graph:
def ... |
Iahub likes chess very much. He even invented a new chess piece named Coder. A Coder can move (and attack) one square horizontally or vertically. More precisely, if the Coder is located at position (x, y), he can move to (or attack) positions (x + 1, y), (xβ1, y), (x, y + 1) and (x, yβ1).
Iahub wants to know how many ... | 1 |
I=lambda:map(int, raw_input().split())
n = input()
print n*(n/2) + ((n+1)/2)*(n%2)
for i in xrange(n):
print ['C.', '.C'][i%2]*(n/2)+['C', '.'][i%2]*(n%2)
|
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 | string = list(input())
num = 0
a = string.count('a')
if a > 0:
num += 1
b = string.count('b')
if b > 0:
num += 1
c = string.count('c')
if c > 0:
num += 1
d = string.count('d')
if d > 0:
num += 1
e = string.count('e')
if e > 0:
num += 1
f = string.count('f')
if f > 0:
num += 1
g = string.count('g... |
Codeforces user' handle color depends on his rating β it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance.
Anton wants the color of hi... | 3 | amount = int(input())
found = False
for i in range(amount):
if not found:
name, before, after = map(str, input().split())
before = int(before)
after = int(after)
if 2400 <= before < after:
found = True
break
print('YES' if found else 'NO')
|
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 β€ i, j β€ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | def func():
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
b = sorted(list(map(int, input().split())))
i = 0
j = n-1
while i < k and a[i] < b[j]:
a[i], b[j] = b[j], a[i]
i += 1
j -= 1
return sum(a)
for _ in range(int(input())):
print... |
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve... | 3 | n, m = map(int, input().split())
x=n
def loop(n, m):
global x
while n>=m:
if n%m==0:
x += n//m
return loop(n//m, m)
else:
y = n//m + n%m
x += n//m
return loop(y, m)
loop(n, m)
print(x)
|
You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line contains the integer n (2 β€ n β€ 2Β·105). The second line contains elements of the sequence a1, ... | 1 | n=input()
a=map(int,raw_input().split())
s=sum(a)
b=[]
for i in range(n):
if a[i]*n==s:
b.append(i+1)
print len(b)
if len(b)!=0:
print ' '.join(map(str,b)) |
Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider... | 1 | n = int(raw_input())
sx, sy, sxy, ans = {},{},{},0
for i in xrange(n):
(a,b) = map(int, raw_input().split())
ans += sx.get(a,0) + sy.get(b,0) - sxy.get((a,b),0)
sx[a] = sx.get(a,0) + 1
sy[b] = sy.get(b,0) + 1
sxy[(a,b)] = sxy.get((a,b),0) + 1
print ans |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.