problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Russian Translation Available
You have a graph with N vertices and M edges. Someone has chosen N-1 edges of these M and claims that they form a spanning tree. Just check whether it's true or not.
Input
The first line contains one integer T denoting the number of test cases.
Each test case starts with a line containi... | 1 | def dfs(arr,n):
check=[]
stk=[]
stk.append(0)
check.append(0)
while len(stk)!=0:
front=stk.pop()
toadd=arr[front]
for i in toadd:
if i not in check:
check.append(i)
stk.append(i)
if len(check)==n:
return True
else:
return False
t=input()
for i in range(0,t):
listmp=list(raw_input().sp... |
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following:
1. Add the integer xi to the first ai elements of the sequence.
2. Append an integer ki to the end of the sequenc... | 1 | n=int(raw_input())
arr=[0]
checker=[0]
su=0.
for _ in range(n):
inp=[int(x) for x in raw_input().split()]
if inp[0]==1:
su+=inp[1]*inp[2]
checker[inp[1]-1]+=inp[2]
elif inp[0]==2:
su+=inp[1]
checker.append(0)
arr.append(inp[1])
elif inp[0]==3:
t=check... |
Little penguin Polo adores strings. But most of all he adores strings of length n.
One day he wanted to find a string that meets the following conditions:
1. The string consists of n lowercase English letters (that is, the string's length equals n), exactly k of these letters are distinct.
2. No two neighbouring... | 1 | import sys
s = sys.stdin.readline()
st = list(s.split(' '))
n = int(st[0])
k = int(st[1])
def stroka(n,k):
rez = ''
if n==k:
for i in range(n):
rez += chr(i+97)
return rez
elif k==1:
if n == 1: return 'a'
else: return -1
elif n<k:
return -1
else:
... |
You are given a rectangular grid with n rows and m columns. The cell located on the i-th row from the top and the j-th column from the left has a value a_{ij} written in it.
You can perform the following operation any number of times (possibly zero):
* Choose any two adjacent cells and multiply the values in them b... | 3 | from sys import stdin
input=stdin.readline
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
a=[0]*(n*m)
negs=0
for i in range(n):
k=list(map(int,input().split()))
for j in range(m):
a[m*i+j] = abs(k[j])
if k[j] < 0: negs += 1
a.sort()
negs %=... |
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution.... | 3 | n = int(input())
num = 0
for i in range(n):
line =[int(i) for i in input().split()]
x = sum(line)
if x >= 2:
num = num + 1
print(num)
|
You are a lover of bacteria. You want to raise some bacteria in a box.
Initially, the box is empty. Each morning, you can put any number of bacteria into the box. And each night, every bacterium in the box will split into two bacteria. You hope to see exactly x bacteria in the box at some moment.
What is the minimu... | 3 | import operator
import functools
bacterias = input()
nbac = functools.reduce(operator.add,map(int,bin(int(bacterias))[2:]))
print(nbac) |
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes.
Some examples of beautiful numbers:
* 12 (110);
* 1102 (610);
* 11110002 (12010);
* 111110... | 3 | a=[1,6,28,120,496,2016,8128,32640]
b=int(input())
for i in range(0,8):
if b%a[i]==0:
c=a[i]
print(str(c)) |
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so ... | 3 | n=int(input())
intervals={}
idx=0
adj={}
def is_path(s,e):
if s==e:
return True
vis[s]=1
for i in adj[s]:
if not vis[i]:
if is_path(i,e):
return True
return False
for i in range(n):
a,b,c=map(int,input().split())
if a==1:
idx+=1
adj[idx]=[]
for j in intervals:
(d,e)=intervals[j]
if d<b<e o... |
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 ... | 3 | # ΠΠ΅Π»ΠΎ ΠΎ Π½ΡΠ»ΡΡ
ΠΈ Π΅Π΄ΠΈΠ½ΠΈΡΠ°Ρ
https://codeforces.com/problemset/problem/556/A
_ = input()
s = input()
print(abs(s.count('0') - s.count('1'))) |
Zane the wizard had never loved anyone before, until he fell in love with a girl, whose name remains unknown to us.
<image>
The girl lives in house m of a village. There are n houses in that village, lining in a straight line from left to right: house 1, house 2, ..., house n. The village is also well-structured: hou... | 3 | n,m,k =map(int , input().split())
l =input()
l=[int(i) for i in l.split()]
m=m-1
bef = l[:m][::-1]
af = l[m+1:]
t,tp,ti,tpi = 0,0,0,0
for i in af:
t+=1
if i<=k and i!=0:
ti=t*10
break
for i in bef:
tp+=1
if i<=k and i!=0:
tpi = tp*10
break
if ti!=0 and tpi!=0:
print... |
You are given an integer L. Construct a directed graph that satisfies the conditions below. The graph may contain multiple edges between the same pair of vertices. It can be proved that such a graph always exists.
* The number of vertices, N, is at most 20. The vertices are given ID numbers from 1 to N.
* The number o... | 3 | L = int(input())
Edges = []
n = 1
while 2**(n-1)-1 < L:
n += 1
n -= 1
for i in range(1, n):
Edges.append([i, i+1, 0])
Edges.append([i, i+1, 2**(i-1)])
remain = L - 2**(n-1)
for x in range(n-1, 0, -1):
if 2**(x-1) <= remain:
Edges.append([x, n, L-remain])
remain -= 2**(x-1)
print(n, ... |
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 β€ k β€ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it.
In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha... | 3 | t = int(input())
for _ in range(t):
x, y, n = map(int, input().split(' '))
m = int((n - y) / x)
k = m * x + y
print(k) |
The king of Berland organizes a ball! n pair are invited to the ball, they are numbered from 1 to n. Each pair consists of one man and one woman. Each dancer (either man or woman) has a monochrome costume. The color of each costume is represented by an integer from 1 to k, inclusive.
Let b_i be the color of the man's ... | 3 | n,k=map(int,input().split())
if n>k*(k-1):
print('NO')
else:
print('YES')
c=0
for i in range(1,k+1):
for j in range(i+1,k+1):
if c<n:
print (i,j)
c+=1
if c<n:
print(j,i)
c+=1
else:... |
Little Vasya went to the supermarket to get some groceries. He walked about the supermarket for a long time and got a basket full of products. Now he needs to choose the cashier to pay for the products.
There are n cashiers at the exit from the supermarket. At the moment the queue for the i-th cashier already has ki p... | 3 | import sys
n = int(input())
k = list(map(int, input().split()))
best = sys.maxsize
for i in range(0, n):
ls = list(map(int,input().split()))
s = sum(ls)
best = min(best, s * 5 + 15*len(ls))
print(best)
|
Sayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters.
It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wa... | 3 | from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
# setrecursionlimit(int(1e6))
INF = float('inf')
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt
def geti(): return map(int, input().strip().split()... |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | s = input()
s1=""
c=0
if(s[0].isupper()):
print(s)
else:
for i in s:
if(i.islower() and c == 0):
s1+=i.upper()
c = 1
else:
s1+=i
print(s1)
|
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi β a coordinate on the Ox axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another city (bec... | 3 | n = int(input())
l = list(map(int,input().split()))
x = []
for i in range(n):
ma = max(abs(l[i]-l[0]),abs(l[i]-l[-1]))
if i == 0:
mi = abs(l[i]-l[i+1])
elif i == n-1:
mi = abs(l[i]-l[i-1])
else:
mi = min(abs(l[i]-l[i-1]),abs(l[i]-l[i+1]))
print(mi,' ',ma)
|
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 | n = int(raw_input())
if n%2 == 0:
L = ["C."*(n/2), ".C"*(n/2)]
else:
L = ["C."*(n//2) + "C", ".C"*(n//2)+"."]
first = True
print (n*n+1)//2
for i in xrange(n):
if first:
print L[0]
else:
print L[1]
first = not first |
You are given a string S of length N. Among its subsequences, count the ones such that all characters are different, modulo 10^9+7. Two subsequences are considered different if their characters come from different positions in the string, even if they are the same as strings.
Here, a subsequence of a string is a conca... | 3 | P = 10**9 + 7
N = int(input())
S = input()
d = [0]*26
for s in S:
d[ord(s)-97] += 1
ans = 1
for num in d:
ans *= (num+1)
ans %= P
print((ans-1)%P) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 1 | def A():
s=raw_input().split()
n=int(s[0])
h=int(s[1])
l=raw_input().split()
res=0
for i in l:
if int(i)>h: res+=2
else: res+=1
print res
A()
|
AquaMoon had n strings of length m each. n is an odd number.
When AquaMoon was gone, Cirno tried to pair these n strings together. After making (n-1)/(2) pairs, she found out that there was exactly one string without the pair!
In her rage, she disrupted each pair of strings. For each pair, she selected some positions... | 3 | from sys import *
#from collections import Counter
input = lambda:stdin.readline()
int_arr = lambda : list(map(int,stdin.readline().strip().split()))
str_arr = lambda :list(map(str,stdin.readline().split()))
get_str = lambda : map(str,stdin.readline().strip().split())
get_int = lambda: map(int,stdin.readline().strip(... |
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this... | 3 | n,k=map(int,input().split())
x=list(map(int,input().split()))
sumi=0
maxi=-10000
for i in range(n):
sumi +=x[i]
for i in range(k):
ans=sumi
for j in range(i,n,k):
ans-=x[j]
maxi=max(maxi,abs(ans))
print(maxi)
|
Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | 3 | import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations,combinations
def data(): r... |
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
For a positive integer n, we call a... | 3 | import sys,math
input=sys.stdin.readline
t=int(input())
for r in range(t):
n = int(input())
for i in range(n):
print(i+1,end=" ")
print() |
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b.
The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part.
Constraints
* 0 β€ a, b β€ 20000
* No divisions by zero are given.
Input
The input c... | 1 | while True :
a, op, b = map(str, raw_input().split(" "))
a = int(a)
b = int(b)
if (op == "?") :
break
elif (op == "+") :
print("%d" % (a+b))
elif (op == "-") :
print("%d" % (a-b))
elif (op == "*") :
print("%d" % (a*b))
elif (op == "/") :
print("%d"... |
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())
d = 1
while(n > 0):
if d % m == 0:
n += 1
n -= 1
d += 1
print(d-1)
|
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 | #https://codeforces.com/problemset/problem/116/A
import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def read_lines(n):
return [sys.stdin.readline().strip() for _ in range(n)]
n=inp()
lines=read_lines(n)
stops=[]
for i in range(n):
a,b=map(int,lines[i].split())
if len(stops):
stops.appe... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 3 | s = list(input().split("WUB"))
ans = []
for i in s:
if i != " " and i != "":
ans.append(i)
print(" ".join(ans)) |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 β€ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | 3 | def bubbleSort(arr, pp):
n = len(arr)
# Traverse through all array elements
for i in range(n):
swapped = False
# Last i elements are already
# in place
for j in range(0, n - i - 1):
# traverse the array from 0 to
# n-i-1. Swap if the element
... |
You are given an array a_1, a_2, ... , a_n and two integers m and k.
You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r.
The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to β_{i=l}^{r} a_i - k β (r - l + 1)/(m) β, where β x β is the least integer greater than or equal to x.
The cost of empty... | 3 | n, m, k = map(int, input().strip().split())
a = list(map(int, input().strip().split()))
a = [0] + a
dp = [0] * 300005
ans = 0
for i in range(1, n + 1):
a[i] += a[i - 1]
for j in range(1, m + 1):
if i - j >= 0:
dp[i] = max(dp[i], a[i] - a[i - j] - k)
if i - m >= 0:
dp[i] = max(dp... |
Bear Limak likes watching sports on TV. He is going to watch a game today. The game lasts 90 minutes and there are no breaks.
Each minute can be either interesting or boring. If 15 consecutive minutes are boring then Limak immediately turns TV off.
You know that there will be n interesting minutes t1, t2, ..., tn. Yo... | 1 | raw_input()
interesting = set(map(int, raw_input().split()))
boredom = 0
for x in range(1, 91):
boredom += 1
if x in interesting:
boredom = 0
elif boredom == 15:
print(x)
import sys; sys.exit()
print(90)
|
You are going to hold a competition of one-to-one game called AtCoder Janken. (Janken is the Japanese name for Rock-paper-scissors.) N players will participate in this competition, and they are given distinct integers from 1 through N. The arena has M playing fields for two players. You need to assign each playing fiel... | 3 | N,M = list(map(int,input().split()))
if M%2==0:
for i in range(M//2):
print(i+1,M-i)
for i in range(M//2):
print(M+i+1,2*M-i+1)
else:
for i in range(M//2):
print(i+1,M-i)
for i in range(M//2+1):
print(M+i+1,2*M-i+1) |
Many of you know the famous Fibonacci sequence F:
F[1] = 1
F[2] = 1
F[i] = F[i - 1] + F[i - 2] for i > 2
Thus each number in sequence is a sum of two previous numbers except two first which are define as 1.
You've decided to create you own Fibonacci sequence. It's very similar to the one described above, but the firs... | 1 | def fib(a,b,n):
table=[0]*n
for i in range(n):
if i==0:
table[i]=a
elif i==1:
table[i]=b
else:
table[i]=table[i-1]+table[i-2]
return table[-1]
a,b,n = map(int,raw_input().split())
print fib(a,b,n) |
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy.
Input
The only line contains three integers n, a and ... | 1 | n, a, b = map(int, raw_input().split())
print min(n-1-a, b)+1
|
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 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 30 23:30:44 2020
@author: DELL
"""
n=int(input())
a=list(map(int,input().split()))
l=sorted(a)
c=0
for i in range(n-1):
if a[i]>a[i+1]:
if a[i+1:n]+a[0:i+1]==l:
c=(len(a[i+1:n]))
break
if a==l:
print(c)
elif c!=0:
print(c)
elif c==0... |
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k).
At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he... | 3 | ## necessary imports
import sys
input = sys.stdin.readline
# from math import *
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp
## gcd function
def gcd(a,b):
if a == 0:
return b
return gcd(b%a, a)
## nCr function efficient using Binomial Cofficie... |
You are given a set of all integers from l to r inclusive, l < r, (r - l + 1) β€ 3 β
10^5 and (r - l) is always odd.
You want to split these numbers into exactly (r - l + 1)/(2) pairs in such a way that for each pair (i, j) the greatest common divisor of i and j is equal to 1. Each number should appear in exactly one o... | 1 |
def solve():
l, r = map(int, raw_input().split())
print 'YES'
for i in range(l, r+1, 2):
print i, i+1
if __name__ == '__main__':
solve()
|
You are given an array a of n integers and an integer s. It is guaranteed that n is odd.
In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to s.
The median of the array with odd length is the ... | 3 | n, s = map(int, input().split())
arr = list(map(int, input().split()))
a_max = len([1 for i in arr if i > s])
a_min = len(arr)-a_max
import heapq
count = 0
if a_min > a_max:
b_min = heapq.nsmallest(a_min, arr)
b_min.sort(reverse = True)
for i in range(a_min - len(arr)//2):
count += s - b_min... |
There are n students in the first grade of Nlogonia high school. The principal wishes to split the students into two classrooms (each student must be in exactly one of the classrooms). Two distinct students whose name starts with the same letter will be chatty if they are put in the same classroom (because they must ha... | 3 | """for p in range(int(input())):
n,k=map(int,input().split(" "))
number=input().split(" ")
chances=[k for i in range(n)]
prev=-1
prev_updated=-1
last_used=False
toSub=0
start=0
prevSub=0
if(number[0]=='1'):
prev=0
prev_updated=0
start=1
for i in range(start,n):
if(number[i]=='1'):
# print("... |
You are given three strings A, B and C. Each of these is a string of length N consisting of lowercase English letters.
Our objective is to make all these three strings equal. For that, you can repeatedly perform the following operation:
* Operation: Choose one of the strings A, B and C, and specify an integer i betwe... | 3 | N = int(input())
A, B, C = input(), input(), input()
ans = 0
for a, b, c in zip(A, B, C):
L = len(set([a, b, c]))
if L == 3:
ans += 2
elif L == 2:
ans += 1
print(ans)
|
Xenia the beginner programmer has a sequence a, consisting of 2n non-negative integers: a1, a2, ..., a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value v for a.
Namely, it takes several iterations to calculate value v. At the first iteration, Xeni... | 3 | from operator import or_, xor
import sys
n, m = map(int, input().split())
t = [list(map(int, input().split()))]
for i in range(n):
if (i & 1 == 0):
t += [[t[i][j] | t[i][j+1] for j in range(0, len(t[i]), 2)]]
else:
t += [[t[i][j] ^ t[i][j+1] for j in range(0, len(t[i]), 2)]]
#print(t)
f... |
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())
for i in range(n):
word = raw_input()
if len(word) > 10:
new_word = "%s%d%s" % (word[0], len(word) - 2, word[-1])
else:
new_word = word
print(new_word)
|
Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch... | 3 | for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
t = 1
ans = 0
for i in range(n):
if i + 1 != a[i]:
if t > 0:
t = 0
ans += 1
else:
t = 1
print(min(ans,2)) |
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 | class Solution:
def resolve(self, n):
"""
:type n: int
:rtype: str
"""
b = n > 2
if b and n % 2 == 0:
return 'YES'
else:
return 'NO'
if __name__ == '__main__':
s = Solution()
n = int(input())
re = s.resolve(n)
print(re... |
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with tha... | 3 | F=lambda : map(int, input().split())
R=list(range(1, 10))
r1,r2=F()
c1,c2=F()
d1,d2=F()
z = [(a,b,c,d) for a in R for b in R for c in R for d in R if len(set((a,b,c,d))) > 3 and a+b == r1 and c+d == r2 and a+c == c1 and b+d == c2 and a+d == d1 and b+c == d2]
if z:z=z[0];print(z[0],z[1]);print(z[2],z[3])
else:print(-1)... |
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 1 | import sys
inputs = sys.stdin.readline()
print inputs[0].upper() + inputs[1:] |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | num = int(input())
cities = input()
score = 0
for i in range(len(cities)-1):
flight = cities[i:i+2]
if flight == 'SF':
score += 1
elif flight == 'FS':
score -= 1
if score > 0:
print('YES')
else:
print('NO')
|
There are a lot of things which could be cut β trees, paper, "the rope". In this problem you are going to cut a sequence of integers.
There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulti... | 3 | n, b = input().split()
n = int(n)
b = int(b)
a = [int(x) for x in input().split()]
odd = 0
not_odd = 0
pos = list()
for i in range(n-1):
if a[i] % 2 == 0:
not_odd += 1
else:
odd += 1
if not_odd == odd:
pos.append(abs(a[i+1] - a[i]))
pos.sort()
sum = 0
count = 0
for i in range(len(p... |
Ehab loves number theory, but for some reason he hates the number x. Given an array a, find the length of its longest subarray such that the sum of its elements isn't divisible by x, or determine that such subarray doesn't exist.
An array a is a subarray of an array b if a can be obtained from b by deletion of several... | 3 | t = int(input())
for q in range(t):
n, x = map(int, input().split())
mas = list(map(int, input().split()))
if sum(mas) % x != 0:
print(n)
else:
ans = []
for i in range(n):
if mas[i] % x != 0:
ans.append(i)
if len(ans):
print (max(n - ans[0] - 1, ans[-1]))
else:
print(-1)
|
You are given a rectangular board of M Γ N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squa... | 3 | m, n = input().split()
print(int(int(m)*int(n)/2)) |
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())
if n%2 == 0:
print(n//2)
else:
a = (n-1)//2
print(a-n) |
There was an electronic store heist last night.
All keyboards which were in the store yesterday were numbered in ascending order from some integer number x. For example, if x = 4 and there were 3 keyboards in the store, then the devices had indices 4, 5 and 6, and if x = 10 and there were 7 of them then the keyboards ... | 3 | n=int(input())
s=[int(i) for i in input().split()]
a=max(s)
b=min(s)
print(a-b-n+1) |
There are N towns on a line running east-west. The towns are numbered 1 through N, in order from west to east. Each point on the line has a one-dimensional coordinate, and a point that is farther east has a greater coordinate value. The coordinate of town i is X_i.
You are now at town 1, and you want to visit all the ... | 3 | n, a, b = map(int, input().split())
x = list(map(int, input().split()))
ans = 0
for i in range(n - 1):
d = x[i + 1] - x[i]
ans += min(d * a, b)
print(ans)
|
You are given a complete directed graph K_n with n vertices: each pair of vertices u β v in K_n have both directed edges (u, v) and (v, u); there are no self-loops.
You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices).
We can write such cycle as a list of... | 3 | t = int(input())
for _ in range(t):
n, l, r = map(int, input().split())
l -= 1
r -= 1
start_i = 1
pos = 0
while start_i < n:
cur_i_len = 2 * (n-start_i)
if pos + cur_i_len > l:
break
pos += cur_i_len
start_i += 1
wanted_len = r-l+1
... |
n! = n Γ (n β 1) Γ (n β 2) Γ ... Γ 3 Γ 2 Γ 1
Is called the factorial of n. For example, the factorial of 12
12! = 12 x 11 x 10 x 9 x 8 x 7 x 6 x 5 x 4 x 3 x 2 x 1 = 479001600
And there are two consecutive 0s at the end.
Write a program that inputs the integer n and outputs the number of consecutive 0s at the end of... | 3 | import math
while True:
b=0
a=int(input())
if a==0:
break
A=math. factorial(a)
while True:
if A%10==0:
b=b+1
A=A//10
else:
break
print(b)
|
PolandBall is a young, clever Ball. He is interested in prime numbers. He has stated a following hypothesis: "There exists such a positive integer n that for each positive integer m number nΒ·m + 1 is a prime number".
Unfortunately, PolandBall is not experienced yet and doesn't know that his hypothesis is incorrect. Co... | 3 | from math import *
n = int(input())
def isPrime(n):
if n == 1:
return False
if n == 2:
return True
for i in range(2, floor(sqrt(n))):
if n % i == 0:
return False
return True
res = 0
for i in range(1, 1001):
if not isPrime(n*i + 1):
res = i
... |
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts.
Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act... | 1 | h,s = 0,0
for __ in xrange(input()):
i = input()
s+= abs(h-i)+2
h=i
print s-1 |
Today's morning was exceptionally snowy. Meshanya decided to go outside and noticed a huge snowball rolling down the mountain! Luckily, there are two stones on that mountain.
Initially, snowball is at height h and it has weight w. Each second the following sequence of events happens: snowball's weights increases by i,... | 3 | w,h=list(map(int, input().split()))
w1, h1=list(map(int, input().split()))
w2, h2=list(map(int, input().split()))
if h1<h2:
w1, w2=w2, w1
h1, h2=h2, h1
for i in range(h, h1-1, -1):
w+=i
w-=w1
if w<0:
w=0
for i in range(h1-1, h2-1, -1):
w+=i
w-=w2
if w<0:
w=0
for i in range(h2-1, -1, -1):
w+=... |
Vasya has an array a consisting of positive integer numbers. Vasya wants to divide this array into two non-empty consecutive parts (the prefix and the suffix) so that the sum of all elements in the first part equals to the sum of elements in the second part. It is not always possible, so Vasya will move some element be... | 1 |
def JUDGE(a,SUM):
s = set()
lsum = 0
rsum = SUM
for i in range(0,len(a)):
lsum += a[i]
rsum -= a[i]
if(lsum == rsum):
return 1
elif(lsum > rsum):
diff = lsum - rsum
if(diff % 2 == 0):
diff /= 2
if(diff... |
Input
The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9.
Output
Output a single integer.
Examples
Input
A278832
Output
0
Input
A089956
Output
0
Input
A089957
Output
1
Input
A1440... | 1 | t = raw_input()
#t = "A089957"
t = int(t[1:])
if t%2 == 0:
print(0)
else:
print (1) |
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l β€ a,b,c β€ r, and then he computes the encrypted value m = n β
a + b - c.
Unfortunately, an adversa... | 3 | import sys
import math
from math import factorial, inf, gcd, sqrt
from heapq import *
from functools import *
from itertools import *
from collections import *
from typing import *
from bisect import *
import random
sys.setrecursionlimit(10**5)
def rarray():
return [int(i) for i in input().split()]
t = 1
t = in... |
The last stage of Football World Cup is played using the play-off system.
There are n teams left in this stage, they are enumerated from 1 to n. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third β with the four... | 3 | import math
n, a, b = map(int, input().split(" "))
# teams = [i+1 for i in range(n)]
# tuple_list = [(i, i+1) for i in range(1, len(teams), 2)]
# a_index, b_index = None, None
# for index, t in enumerate(tuple_list):
# if a in t: a_index = index
# if b in t: b_index = index
# diff = int(math.log2(abs(a_ind... |
A matrix of size n Γ m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 β€ i β€ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n Γ m. In one operation he can increase or decrease any numb... | 3 | ncases = int(input())
def to_int(s):
return int(s)
for tcase in range(ncases):
row_col = list(map(to_int, input().split(" ")))
nrows = row_col[0]
ncols = row_col[1]
matrix = []
for i in range(nrows):
matrix.append(list(map(to_int, input().split(" "))))
sum = 0
for i in ra... |
Asya loves animals very much. Recently, she purchased n kittens, enumerated them from 1 and n and then put them into the cage. The cage consists of one row of n cells, enumerated with integers from 1 to n from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n - 1 ... | 3 | import sys
import math
MAXN = 150001
parent = [None] * MAXN
rank = [0] * MAXN
lists = [None] * MAXN
def make_set(x):
parent[x] = x
lists[x] = [x]
def find_set(x):
if parent[x] == x:
return x
parent[x] = find_set(parent[x])
return parent[x]
def union(x, y):
x = find_set(x)
y = ... |
<image>
This figure shows railway tracks for reshuffling cars. The rail tracks end in the bottom and the top-left rail track is used for the entrace and the top-right rail track is used for the exit. Ten cars, which have numbers from 1 to 10 respectively, use the rail tracks.
We can simulate the movement (comings an... | 3 | import sys
def run():
cars = []
for _n in sys.stdin:
n = int(_n)
if n == 0:
print(cars.pop())
else:
cars.append(n)
if __name__ == '__main__':
run()
|
A magic number is a number formed by concatenation of numbers 1, 14 and 144. We can use each of these numbers any number of times. Therefore 14144, 141414 and 1411 are magic numbers but 1444, 514 and 414 are not.
You're given a number. Determine if it is a magic number or not.
Input
The first line of input contains ... | 3 | n=input()
l=len(n)
if n[0]!='1':
print("NO")
else:
flag=0
for i in range(1,l):
if n[i]=='1':
continue
elif n[i]=='4':
if n[i-1]=='1':
continue
elif i>1 and n[i-2]=='1':
continue
else:
... |
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 3 | t = int(input())
for i in range(t):
x, y, a, b = map(int, input().split())
if x == a:
print(abs(y-b))
elif y == b:
print(abs(x-a))
else:
print(abs(a-x)+abs(b-y)+2)
|
There are n emotes in very popular digital collectible card game (the game is pretty famous so we won't say its name). The i-th emote increases the opponent's happiness by a_i units (we all know that emotes in this game are used to make opponents happy).
You have time to use some emotes only m times. You are allowed t... | 3 | n,m,k=map(int,input().split())
numbers=list(map(int,input().split()))
y,x=sorted(numbers)[-2:]
val= ((m//(k+1))*((x*k)+y))
val2= (m%(k+1))*x
print(val+val2) |
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`.
You will appoint one of the N people as the leader, then command the rest of the... | 3 | N = int(input())
S = input()
r = 0
for i in range(1,N):
if S[i] == "E":
r += 1
ans = r
l = 0
for i in range(1,N):
if S[i-1] == "W":
l += 1
if S[i] == "E":
r -= 1
ans = min(ans, l + r)
print(ans) |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | for _ in range(int(input())):
s = input()
res = ""
for i in range(0, len(s), 2):
res += s[i]
print(res + s[-1])
|
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to... | 3 | x=list(map(int,input().split()))
x.sort()
a=0
a=x[1]-x[0]
a+=x[2]-x[1]
print(a) |
You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score.
You want to in... | 3 | n = int(input())
lst = []
for i in range(n):
s,p = input().split()
lst.append((s,-int(p),i+1))
lst.sort()
for s,p,k in lst:
print(k)
|
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n,h=map(int,input().split())
l=[int(l) for l in input().split()]
w=n
for i in l:
if(i>h):
w+=1
print(w) |
There are N cities. There are also K roads and L railways, extending between the cities. The i-th road bidirectionally connects the p_i-th and q_i-th cities, and the i-th railway bidirectionally connects the r_i-th and s_i-th cities. No two roads connect the same pair of cities. Similarly, no two railways connect the s... | 3 | #!/usr/bin/env pypy3
import collections
class UnionFind(object):
def __init__(self, number_of_nodes):
self.par = list(range(number_of_nodes))
self.rank = [0] * number_of_nodes
def root(self, node):
if self.par[node] == node:
return node
else:
r = self... |
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 | T = int(input().strip())
def cover(row, x,y):
if 2*x <=y:
return x*sum(row)
res = 0
for j in row:
res += y*(j //2) + x * (j % 2)
return res
for t in range(T):
n, m, x, y = list(map(int, input().split()))
cost = 0
for _ in range(n):
row = list(map(len, input().strip(... |
Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles.
A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the sma... | 3 | import sys; Case=1
Case=int(sys.stdin.buffer.readline())
def centroid(g):
n=len(g)
centroid=[]
size=[0 for i in range(n)]
@recursive
def dfs(node,par):
size[node]=1
iscent=True
for nei in g[node]:
if nei!=par:
yield dfs(nei,node)
s... |
You are given string s of length n consisting of 0-s and 1-s. You build an infinite string t as a concatenation of an infinite number of strings s, or t = ssss ... For example, if s = 10010, then t = 100101001010010...
Calculate the number of prefixes of t with balance equal to x. The balance of some string q is equal... | 1 | t = input()
for i in range(t):
n,x = map(int,raw_input().split(" "))
arr = map(int,raw_input())
ans = [0]
a = 0
b = 0
for i in range(n):
if arr[i] == 1:
a += 1
else:
b += 1
ans.append(b-a)
v = ans[-1]
if v == 0:
if x in ans:
print -1
else:
print 0
continue
ret = 0
for i in range(n):
... |
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the... | 3 | #https://codeforces.com/contest/1375/problem/B
def nbr(arr,n,m):
for i in range(n):
for j in range(m):
nbr = 0
if (i>0 and j>0) and (i<n-1 and j<m-1):
nbr = 4
elif (i==0 and j==0) or (i==n-1 and j==m-1):
nbr=2
elif (i==n-1 and j==0) or (j==m-1 and i==0):
nbr = 2
else:
nbr =3
if ... |
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 | n = int(input())
cnt=0
for i in range(n):
s=input()
if(s.find("+")!=-1): cnt+=1
else :cnt-=1
print(cnt)
|
Naruto has sneaked into the Orochimaru's lair and is now looking for Sasuke. There are T rooms there. Every room has a door into it, each door can be described by the number n of seals on it and their integer energies a_1, a_2, ..., a_n. All energies a_i are nonzero and do not exceed 100 by absolute value. Also, n is e... | 3 | doors = int(input())
n = []
m = []
for i in range(0, doors):
n.append(int(input()))
m.append(list(map(int, input().split())))
for q in range(0, len(n)):
ans = []
for j in range(0, len(m[q])):
if (j+1)%2 == 0:
ans.append(-m[q][j])
else:
ans.append(m[q][j])
prin... |
Given is an integer S. Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions:
* 0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9
* The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2.
We can prove that ther... | 3 | S=int(input())
a,b=10**9,1
d=(S+a-1)//a
c=a*d-S
print(0,0,a,b,c,d) |
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | import sys
input = sys.stdin.readline
# Input Functions
# Take integer input
def inp():
return(int(input()))
# Take list input
def inlt():
return(list(map(int, input().split())))
# Take string as list of characters
def insr():
s = input()
return(list(s[:len(s) - 1]))
# Take space separated integer var... |
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance... | 3 | import sys
import math
n=[int(i) for i in input().split()][0]
ar=[int(i) for i in input().split()]
print(max( abs(ar.index(n)),abs(ar.index(n)-n+1), abs(ar.index(1)),abs(ar.index(1)-n+1), ))
sys.stdout.close();
|
There are N slimes standing on a number line. The i-th slime from the left is at position x_i.
It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.
Niwango will perform N-1 operations. The i-th operation consists of the following procedures:
* Choose an integer k between 1 and N-i (inclusive) with equ... | 3 | import math
import random
from operator import itemgetter
import re
import sys
from itertools import accumulate
from collections import defaultdict
from collections import deque
from bisect import bisect_left,bisect
from heapq import heappop,heappush
from fractions import gcd
from copy import deepcopy
import functools
... |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 |
n = int(input())
arr = list(map(int,input().strip().split()))
ans = 0
mp = {}
mp[1] = 0
mp[2] = 0
mp[3] = 0
mp[4] = 0
for i in range(n):
mp[arr[i]]+=1
ans += mp[4]
mp[4] = 0
if mp[3] > mp[1]:
ans+=mp[1]
mp[3]-=mp[1]
mp[1]= 0
else:
ans+=mp[3]
mp[1] -=mp[3]
mp[3] = 0
ans+=mp[3]
mp[3... |
Given is a string S representing the day of the week today.
S is `SUN`, `MON`, `TUE`, `WED`, `THU`, `FRI`, or `SAT`, for Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, and Saturday, respectively.
After how many days is the next Sunday (tomorrow or later)?
Constraints
* S is `SUN`, `MON`, `TUE`, `WED`, `THU`,... | 3 | s = [0, "SAT", "FRI", "THU", "WED", "TUE", "MON", "SUN"]
print(s.index(input())) |
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has a candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make b went out candles into a new candle. As a result, this new candle can be used like... | 1 | n,k = map(int,raw_input().split())
print (n - 1)/(k - 1) + n |
You are given an integer n (n β₯ 0) represented with k digits in base (radix) b. So,
$$$n = a_1 β
b^{k-1} + a_2 β
b^{k-2} + β¦ a_{k-1} β
b + a_k.$$$
For example, if b=17, k=3 and a=[11, 15, 7] then n=11β
17^2+15β
17+7=3179+255+7=3441.
Determine whether n is even or odd.
Input
The first line contains two integers b and... | 3 | first = input().split(' ')
b = int(first[0])
k = int(first[1])
second = input().split(' ')
a = [int(i) for i in second]
n = 0
for i in range(k):
if k-i-1 == 0:
tmp = a[i]
else:
tmp = a[i] * b
tmp = tmp % 10
n += tmp
if n > 10:
n = n % 10
if n & 0x1 == 0:
print('even')
e... |
The only difference between easy and hard versions is constraints.
The BerTV channel every day broadcasts one episode of one of the k TV shows. You know the schedule for the next n days: a sequence of integers a_1, a_2, ..., a_n (1 β€ a_i β€ k), where a_i is the show, the episode of which will be shown in i-th day.
The... | 3 | t = int(input())
for u in range(t):
n, k, d = map(int, input().split())
a = list(map(int, input().split()))
c = [0] * k
for i in range(d):
c[a[i] - 1] += 1
ans = 0
mn_ans= 0
for i in range(k):
if c[i] != 0:
ans += 1
mn_ans = ans
for i in range(d, n):
... |
High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. W... | 3 | from collections import deque
n,k=map(int,input().split())
s=input()
ca=cb=0
q=deque();ans=0
for i in s:
if i=='a':
ca+=1
else:
cb+=1
q.append(i)
while(q and min(ca,cb)>k):
if q[0]=='a':
ca-=1
else:
cb-=1
q.popleft()
ans=max(ans,len(q))... |
AtCoDeer is thinking of painting an infinite two-dimensional grid in a checked pattern of side K. Here, a checked pattern of side K is a pattern where each square is painted black or white so that each connected component of each color is a K Γ K square. Below is an example of a checked pattern of side 3:
cba927b2484f... | 3 | n,k=map(int,input().split())
l=[input().split() for _ in range(n)]
w=[[0]*(k+1) for _ in range(k+1)]
b=[[0]*(k+1) for _ in range(k+1)]
for i in range(n):
if ((int(l[i][0])//k+int(l[i][1])//k)%2==0)^(l[i][2]=='W'):
b[int(l[i][0])%k][int(l[i][1])%k]+=1
else:
w[int(l[i][0])%k][int(l[i][1])%k]+=1
f... |
Methodius received an email from his friend Polycarp. However, Polycarp's keyboard is broken, so pressing a key on it once may cause the corresponding symbol to appear more than once (if you press a key on a regular keyboard, it prints exactly one symbol).
For example, as a result of typing the word "hello", the follo... | 3 | q = int(input())
for _ in range(q):
a1 = list(input())
b1 = list(input())
a = []; b = []
k = 1
for i in range(1, len(a1)):
if a1[i] != a1[i - 1]:
a.append([a1[i - 1], k])
k = 1
else:
k += 1
a.append([a1[-1], k])
k = 1
for i in range(1, ... |
Amer cabs has released a scheme through which a user gets a free drive when he shares a reference code with another Amer app user. Given N number of app users, output total number of free drives gained by all of them. Two same users cannot share reference code more than once.
Input Format
The first line contains th... | 1 | for _ in range(input()):
n = input()
print (n)*(n-1)/2 |
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 | l,b=[int(l) for l in input().split()]
y=1
while True:
y+=1
l=l*3
b=b*2
if l>b:
break
print(y-1)
|
You are given a special jigsaw puzzle consisting of nβ
m identical pieces. Every piece has three tabs and one blank, as pictured below.
<image>
The jigsaw puzzle is considered solved if the following conditions hold:
1. The pieces are arranged into a grid with n rows and m columns.
2. For any two pieces that sh... | 3 | t = int(input())
for _ in range(t):
[n, m] = [int(x) for x in input().split()]
if n == 1 or m == 1:
print('YES')
elif n == 2 and m == 2:
print('YES')
else:
print('NO')
|
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i... | 3 | n,k = map(int,input().split())
a=input()
b=a[:];c=[];
max=-1
for i in range(len(a)):
if a[i]!='1':
count=b.count(a[i])
a=a.replace(a[i],'1')
c.append(count)
c.sort()
flag=0;total=0;
for i in range(len(c)-1,-1,-1):
preflag=flag
flag+=c[i]
if flag<k:
total+=c[i]*c[i]
... |
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons... | 3 | s = input()
t = input()
f = 0
if(len(s)==len(t)):
for i in range(len(s)):
g = ord(s[i])
if(s[i] == 'a' or s[i]=='e' or s[i]=='i' or s[i]=='o' or s[i]=='u'):
if(t[i] == 'a' or t[i]=='e' or t[i]=='i' or t[i]=='o' or t[i]=='u'):
continue
else:
f=1... |
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | 3 | n=int(input())
a=list(map(int,input().split()))
a.sort();b=[];c=[]
for i in range(n):
if a[i]>=0:
b=a[i:]
break
c.append(a[i])
r=sum(b)
c=c[::-1]
if r%2!=0:
print(r)
else:
m=k=-10e9
for i in b:
if (r-i)%2!=0:
k=r-i;break
for i in c:
if (r+i)%2!=0:
... |
VK news recommendation system daily selects interesting publications of one of n disjoint categories for each user. Each publication belongs to exactly one category. For each category i batch algorithm selects a_i publications.
The latest A/B test suggests that users are reading recommended publications more actively ... | 3 |
import collections
union_arr =collections.defaultdict(int)
def func():
n_cates = int(input())
cate_i = list(map(int,input().split()))
time_i = list(map(int,input().split()))
idx = [index for index,value in sorted(list(enumerate(time_i)),reverse=True,key=lambda x:x[1])]
cate_i = [cate_i[i] for i in ... |
Nastia has 2 positive integers A and B. She defines that:
* The integer is good if it is divisible by A β
B;
* Otherwise, the integer is nearly good, if it is divisible by A.
For example, if A = 6 and B = 4, the integers 24 and 72 are good, the integers 6, 660 and 12 are nearly good, the integers 16, 7 are ne... | 3 | from sys import stdin
input=stdin.readline
t=int(input())
for _ in range(t):
a,b=map(int,input().split())
if b==1:
print("NO")
continue
print("YES")
print(a,(a*b),(a*(b+1)))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.