problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i... | 3 | # https://codeforces.com/contest/16/problem/B
def single_integer():
return int(input())
def multi_integer():
return map(int, input().split())
def string():
return input()
def multi_string():
return input().split()
n, m = multi_integer()
matches = list()
for i in range(m):
matches.append(t... |
New AtCoder City has an infinite grid of streets, as follows:
* At the center of the city stands a clock tower. Let (0, 0) be the coordinates of this point.
* A straight street, which we will call East-West Main Street, runs east-west and passes the clock tower. It corresponds to the x-axis in the two-dimensional coor... | 3 | #! /usr/bin/env python3
import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)
N = int(readline())
XYP = [list(map(int, readline().split())) for _ in range(N)]
costs = [sys.maxsize] * N
for i, (x, y... |
Soon after the Chunga-Changa island was discovered, it started to acquire some forms of civilization and even market economy. A new currency arose, colloquially called "chizhik". One has to pay in chizhiks to buy a coconut now.
Sasha and Masha are about to buy some coconuts which are sold at price z chizhiks per cocon... | 3 | x, y, z = [int(i) for i in input().split()]
if x//z + y//z == (x+y)//z:
print((x+y)//z,0)
else:
print((x+y)//z, min(z - (x%z), z-(y%z)))
|
Vanya got an important task β he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers.
Vanya wants to know how many digits he will have to write down as he labels the bo... | 3 | n=int(input())
a=0
r=1
while n-r>=0:
a+=n-r+1
r*=10
print(a) |
We have three boxes A, B, and C, each of which contains an integer.
Currently, the boxes A, B, and C contain the integers X, Y, and Z, respectively.
We will now do the operations below in order. Find the content of each box afterward.
* Swap the contents of the boxes A and B
* Swap the contents of the boxes A and C
C... | 3 | a,b,c=input().split()
print("{} {} {}".format(c,a,b)) |
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance?
Input
The first... | 3 | n = int(input())
denom = [100,20,10,5,1]
bills = 0
for i in denom:
if n // i > 0:
bills += n // i
n -= (n // i) * i
print(bills)
|
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 | def myMethod(a,b):
y = 0
while(a<=b):
a = a*3
b = b*2
y+=1
return y
a, b= [int(x) for x in input().split()]
print(myMethod(a,b))
|
In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way:
* he creates an integer c as a result of bitwise summing of a and b without transfe... | 3 | t=int(input())
for i in range(t):
n=int(input())
l=input()
ctr=0
res=[]
for j in range(n):
if ctr==2:
if l[j]=='1':
res.append(0)
ctr=1
else:
res.append(1)
ctr=1
elif ctr==1:
... |
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed.
Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes.
Every time Polycarp wakes up, he decides if he wants to sleep... | 3 | t=int(input())
for _ in range(t):
#n=int(input())
a,b,c,d=map(int,input().split())
if(b>=a):
print(b)
continue
if(c<=d):
print(-1)
continue
a=a-b
print(b+(a+c-d-1)//(c-d)*c)
|
Takahashi has K 500-yen coins. (Yen is the currency of Japan.) If these coins add up to X yen or more, print `Yes`; otherwise, print `No`.
Constraints
* 1 \leq K \leq 100
* 1 \leq X \leq 10^5
Input
Input is given from Standard Input in the following format:
K X
Output
If the coins add up to X yen or more, prin... | 3 | K, X = map(int, input().split())
print(['No', 'Yes'][X<=K*500]) |
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as... | 3 | n=int(input())
a=[int(x) for x in input().split()]
arr=[0]*(n)
maxx=-1
maxcnt=0
for i in range(n-1):
if 2*a[i]>=a[i+1]:
arr[i]=1
else:
arr[i]=0
#print(arr)
for i in range(n):
if arr[i]==1:
maxcnt+=1
else:
maxx=max(maxx,maxcnt+1)
maxcnt=0
print(maxx)
|
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as... | 3 | n=int(input())
list1=[int(x) for x in input().split()]
answers=[]
i=0
while(i<(n-1)):
counter=0
#print("value of i:",i)
for j in range(i,n-1):
#print("value of jth term:",list1[j])
if(list1[j]*2>=list1[j+1] and list1[j]*2<=list1[j+1]*2):
counter+=1
else:
break... |
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each... | 3 | n = list(map(int,input().split()))
s = input()
for i in range(n[1]):
s = s.replace('BG','GB')
print(s)
|
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 | import math
m = []
i = 0
while i < 5:
m.append(input().split())
i += 1
i = 0
while i < 5:
j = 0
while j < 5:
if m[i][j] == '1':
print(abs(i-2)+abs(j-2))
break
j += 1
if j < 5:
break
i += 1
|
Inna loves digit 9 very much. That's why she asked Dima to write a small number consisting of nines. But Dima must have misunderstood her and he wrote a very large number a, consisting of digits from 1 to 9.
Inna wants to slightly alter the number Dima wrote so that in the end the number contained as many digits nine ... | 3 | s,a,c=input(),1,1
for i in range(1,len(s)):
if int(s[i])+int(s[i-1])==9:c+=1
elif c%2:a*=c//2+1;c=1
else:c=1
if(c%2):a*=c//2+1
print(a) |
Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | 1 | import sys
def main():
N = int(sys.stdin.readline())
k = N/2
A = [2] * k
if N % 2 == 1:
A[-1] = 3
print len(A)
print ' '.join(map(str, A))
if __name__ == '__main__':
main()
|
Anton's favourite geometric figures are regular polyhedrons. Note that there are five kinds of regular polyhedrons:
* Tetrahedron. Tetrahedron has 4 triangular faces.
* Cube. Cube has 6 square faces.
* Octahedron. Octahedron has 8 triangular faces.
* Dodecahedron. Dodecahedron has 12 pentagonal faces.
*... | 3 | n=int(input())
l=[]
c=0
d={"Tetrahedron":4,"Cube":6,"Octahedron":8,"Dodecahedron":12,"Icosahedron":20}
for i in range(n):
s=input()
l.append(s)
for i in range(len(l)):
if l[i] in d:
c+=d[l[i]]
print(c)
|
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 | a = []
l = 0
k = 0
for i in range(0, 5):
a.append([int(j) for j in input().split()])
for i in range(5):
for j in range(5):
if a[i][j] == 1:
k = i - 2
l = j - 2
if k < 0:
k = k * -1
if l < 0:
l = l * -1
print(k + l)
|
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid f... | 3 | for i in range(int(input())):
n=int(input())
l=list()
for i in range(n):
x=input()
lst=list()
for i in x:
lst.append(i)
l.append(lst)
l1=l[n-2][n-1]
l2=l[n-1][n-2]
f1=l[0][1]
f2=l[1][0]
if int(f1)==0 and int(f2)==0:
if int(l1)==0 and in... |
You are given two integers b and w. You have a chessboard of size 10^9 Γ 10^9 with the top left cell at (1; 1), the cell (1; 1) is painted white.
Your task is to find a connected component on this chessboard that contains exactly b black cells and exactly w white cells. Two cells are called connected if they share a s... | 3 | import sys
input = lambda: sys.stdin.readline().strip()
t = int(input())
for i in range(t):
b, w = map(int, input().split())
if w==b:
print("YES")
for i in range(1, 2*b+1):
print(2, i)
elif 3*b+1>=w>b:
print("YES")
for i in range(3, 2*b+2):
print(2, i... |
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them.
While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d... | 3 | import math
t=int(input())
for i in range(t):
a,b,c,d,k=map(int,input().split())
pen=math.ceil(a/c)
pencil=math.ceil(b/d)
if((pen+pencil)<=k):
print(str(pen)+" "+str(pencil))
else:
print(-1) |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 3 | guest = input()
host = input()
letter = input()
letter = list(letter)
count1, count2 = (0,)*2
for i in range(len(guest)):
for j in range(len(letter)):
if guest[i] == letter[j]:
count1 += 1
letter[j] = '0'
break
for i in range(len(host)):
for j in range(len(letter)):
... |
Recently, Norge found a string s = s_1 s_2 β¦ s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them!
A substring of s is a non-empty string x = s[a β¦ b] = s_{a} s_{a + 1} β¦ s_{b} (1 β€ a β€ b β€ n). For e... | 3 | num_input = input()
num_input = num_input.split(" ")
n = int(num_input[0])
k = int(num_input[1])
input_string = input()
can_use = input()
can_use = can_use.split(" ")
can_use_set = set()
for i in range(0, len(can_use)):
can_use_set.add(can_use[i])
res = ''
can_use_string = {}
for i in range (0, len(input_stri... |
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=map(int,input().split())
d={}
a=[]
import sys
input=sys.stdin.readline
for i in range(n):
s=input().rstrip()
a.append(s)
dd=set(a)
for i in range(n):
u="".join(a[i])
if u in d:
continue
d[u]=[0 for x in range(n)]
d[u][i]=1
for j in range(i+1,n):
if a[i]==a[j]:
... |
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of n parts and m ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The... | 1 | def main():
n, m = map(int, raw_input().split())
v = map(int, raw_input().split())
ans = 0
for i in xrange(m):
x, y = map(int, raw_input().split())
ans += min(v[x - 1], v[y - 1])
print ans
if __name__ == "__main__": main()
|
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase ... | 3 | k,n = input(),int(input())
l = list(map(int,input().split()))
print(sum([i*(l[ord(k[i-1])-97]) if i<=len(k) else max(l)*i for i in range(1,len(k)+n+1)])) |
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type:
1. + ai β add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur... | 3 | from sys import stdin
d,res,elem={},'','0101010101'
a=lambda:stdin.readline().split()
for _ in range(int(stdin.readline())):
c,x=map(str,a())
if c!='?':
x=[*x]
x=[elem[int(y)] for i,y in enumerate(x)]
x=''.join(x)
x=x[x.find('1'):]
if c=='+':
if d.get(x)==None:d[x]=0
... |
A sequence of n non-negative integers (n β₯ 2) a_1, a_2, ..., a_n is called good if for all i from 1 to n-1 the following condition holds true: $$$a_1 \: \& \: a_2 \: \& \: ... \: \& \: a_i = a_{i+1} \: \& \: a_{i+2} \: \& \: ... \: \& \: a_n, where \&$$$ denotes the [bitwise AND operation](https://en.wikipedia.org/wiki... | 3 |
from math import *
N=int(1e9+7)
f=[]
def fact():
global f
f.append(int(1))
for i in range(1, 200005):
f.append(int((f[len(f)-1]*i)%N))
fact()
for i in range(int(input())):
n=int(input())
arr=[int(i) for i in input().split()]
p=int(2**31-1)
c=[]
# c1=0
for i in range(0,n... |
A class of students wrote a multiple-choice test.
There are n students in the class. The test had m questions, each of them had 5 possible answers (A, B, C, D or E). There is exactly one correct answer for each question. The correct answer for question i worth a_i points. Incorrect answers are graded with zero points.... | 3 | n,m = list(map(int, input().split()))
sts = [[0,0,0,0,0] for _ in range(m)]
for i in range(n):
s = input()
for j,c in enumerate(s):
sts[j][int(ord(c[0])-ord('A'))]+=1
ansval = list(map(int, input().split()))
for i in range(m):
for j in range(5):
sts[i][j] *= ansval[i]
#print(sts)
sm = 0
for i in range(m):
sm +=... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n=int(input())
hate='I hate'
love='I love'
result=hate
current=love
for i in range(1,n):
result+=' that '+current
if (current==hate):
current=love
else:
current=hate
print(result+' it')
|
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B.
A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "c... | 3 | import sys
from itertools import permutations
#a=list(map(int,input().strip().split(' ')))
#n,k,s= map(int, sys.stdin.readline().split(' '))
s=str(input())
sr=s[::-1]
print(s+sr)
|
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party.
She invited n guests of the first type and m guests of the second type to the party. They will come to the ... | 3 | for _ in range(int(input())):
a, b, n, m = map(int,input().split())
rich = max(a, b)
poor = min(a, b)
if ((rich+ poor - m) >= n) and (poor >= m):
print("Yes")
else:
print("No") |
There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | 3 | n=int(input())
a=[int(x) for x in input().split(' ')]
b=[int(x) for x in range(n)]
for i in range(n-1):
for j in range(i+1, n):
if (a[i]>=a[j]):
a[i], a[j]=a[j], a[i]
b[i], b[j]=b[j], b[i]
for i in range(n//2):
print (b[i]+1, b[n-i-1]+1) |
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | 3 | for _ in range(int(input())):
n=int(input())
ar=list(map(int,input().split()))
br=list(map(int,input().split()))
ar.sort()
br.sort()
print(*ar)
print(*br) |
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 | n, m = map(int, input().split(" "))
counter = 0
for i in range(1, m+1):
counter += (n+(i % 5))//5
print(counter)
|
The football season has just ended in Berland. According to the rules of Berland football, each match is played between two teams. The result of each match is either a draw, or a victory of one of the playing teams. If a team wins the match, it gets w points, and the opposing team gets 0 points. If the game results in ... | 3 | n, p, w, d = map(int, input().split(' '))
x, y, z = 0, 0, 0
if p > n * w:
print('-1')
exit()
if p % d == 0:
y = int(p/d)
z = n - y
if y >= 0 and z >= 0:
print(str(x) + ' ' + str(y) + ' ' + str(z))
exit()
for i in range(1, min([w, d])+1):
if w % i == 0 and d % i == 0:
k ... |
You are given four integers a, b, x and y. Initially, a β₯ x and b β₯ y. You can do the following operation no more than n times:
* Choose either a or b and decrease it by one. However, as a result of this operation, value of a cannot become less than x, and value of b cannot become less than y.
Your task is to fi... | 3 | import math
for _ in range(int(input())):
a,b,x,y,n = [int(j) for j in input().split()]
if a<b:
a,b = b,a
x,y = y,x
a2,b2,n2= a,b,n
a1 = a- min(n,a-x)
n = n-(a-a1)
a=a1
b = b - min(n,b-y)
b3 = b2- min(n2,b2-y)
n2 = n2-(b2-b3)
b2=b3
a2 = a2 - min(n2,a2-x)... |
You have N bamboos. The lengths (in centimeters) of these are l_1, l_2, ..., l_N, respectively.
Your objective is to use some of these bamboos (possibly all) to obtain three bamboos of length A, B, C. For that, you can use the following three kinds of magics any number:
* Extension Magic: Consumes 1 MP (magic point).... | 3 | N, A, B, C = map(int, input().split(" "))
l = [int(input()) for i in range(N)]
INF = 10 ** 9
def dfs(cnt, a, b, c):
if cnt == N:
return abs(a-A)+abs(b-B)+abs(c-C)-30 if min(a,b,c)>0 else INF
ret1=dfs(cnt+1,a+l[cnt],b,c)+10
ret2=dfs(cnt+1,a,b+l[cnt],c)+10
ret3=dfs(cnt+1,a,b,c+l[cnt])+10
ret4=... |
We will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move... | 3 | n,m=map(int,input().split())
x=list(map(int,input().split()))
x.sort()
l=[]
for i in range(m-1):
l.append(x[i+1]-x[i])
l.sort(reverse=True)
cnt=sum(l[:n-1])
print(sum(l)-cnt)
|
Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (... | 3 | def binarySearch(arr, l, r, x):
ans=-1
while l <= r:
mid = l + (r - l)//2;
if arr[mid] >= x:
r=mid-1
ans= mid
elif arr[mid] < x:
l = mid + 1
else:
r = mid - 1
return ans
n,m=map(int,input().split())
if m==0:
print(n,... |
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. ... | 3 | from sys import stdin, stdout
n = stdin.readline()
n = int(n)
s= stdin.readline()
lc = s.count("L")
rc = s.count("R")
stdout.write(str(lc+rc+1)) |
The final match of the Berland Football Cup has been held recently. The referee has shown n yellow cards throughout the match. At the beginning of the match there were a_1 players in the first team and a_2 players in the second team.
The rules of sending players off the game are a bit different in Berland football. If... | 3 | a1=input()
a1=int(a1)
a2=input()
a2=int(a2)
k1=input()
k1=int(k1)
k2=input()
k2=int(k2)
n=input()
n=int(n)
mini=0
d={}
d[k1]=a1
d[k2]=a2
k=0
kk=0
mi=n
mini=min(k1,k2)
maxi=max(k1,k2)
for i in range(1,d[mini]+1):
if i*mini<=n:
k+=1
else:
break
mi-=k*mini
for i in range(1,d[maxi]+1):
if i*... |
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())
i1 = 0
i2 = 0
for i in range(t):
n = int(input())
x = input()
a = ''
b = ''
f = True
for c in x:
if c == '2':
if f:
a += '1'
b += '1'
else:
a += '0'
b += '2'
elif c == '1':
... |
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... | 3 | import sys
from collections import Counter
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
def countPrefix(s, x):
if x < 0:
s = s.replace('0', '#').replace('1', '0').replace('#', '1')
x = -x
... |
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 | s=raw_input()
if(s[0].islower()):
print(s[0].upper()+s[1:])
else:
print s |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | import cmath
import math
def prime(m):
p=0
for i in range(2,math.ceil(cmath.sqrt(m).real)+1):
if m%i==0:
p+=1
if p==0:
return 0
else:
return 1
n=int(input())
for i in range (3,n):
if prime(i)==1 and prime(n-i)==1:
print(i,n-i)
exit()
|
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are m containers, in the i-th container there are ai matchboxes, and each matchbox contains bi matches. All the matchboxes are of the same size. The burglar's rucksack can hold n matchboxes exactly. Your task i... | 3 | from sys import stdin
n,m = map(int,stdin.readline().split())
c = []
for _ in range(m):
c+=[tuple(map(int,stdin.readline().split()))]
c.sort(key=lambda x:x[1],reverse=True)
ans = 0
for a,b in c:
if n>a:
ans+=a*b
n-=a
else:
ans+=n*b
break
print(ans)
|
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For e... | 3 | n = int(input())
score = list(map(int, input().split()))
if len(score) == 1:
print(0)
quit()
max = score[0]
min = score[1]
s = []
if score[0] < score[1]:
max = score[1]
min = score[0]
if score[1] != score[0]:
s.append(2)
for i in range(2, n):
if score[i] > max:
max = score[i]
#pr... |
You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).
Input
The first line contains a single positive integer t (1 β€ t β€ 50) β the number of test cases in the test. Then t test cases follow.
Each test case consists of ... | 3 | for _ in range(int(input())):
n=int(input())
if(n>45): print(-1)
else:
x=""
s=9
while(s>0):
if(n>=s):
x+=str(s)
n-=s
s-=1
# x.reverse()
for i in range(len(x)-1,-1,-1):
print(x[i],end="")
print... |
Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct... | 1 | n, a, b = map(int, raw_input().split())
r = (a+b) % n
if r <= 0: r += n
print r |
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 | n=input()
b=0
c=0
for i in range(len(n)):
if 'a'<=n[i]<='z':
b+=1
else:
c+=1
if b>=c:
a=n.lower()
else:
a=n.upper()
print(a) |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | num = int(input())
arr = []
for i in range(num):
arr.append(input())
for i in range(num):
if "po" in arr[i][-2:]:
print("FILIPINO")
elif "su" in arr[i][-2:]:
print("JAPANESE")
else:
print("KOREAN") |
AtCoDeer the deer is seeing a quick report of election results on TV. Two candidates are standing for the election: Takahashi and Aoki. The report shows the ratio of the current numbers of votes the two candidates have obtained, but not the actual numbers of votes. AtCoDeer has checked the report N times, and when he c... | 3 | n=int(input())
x,y=map(int,input().split())
import math
for i in range(n-1):
t,a=map(int,input().split())
tbai=(x-1)//t+1
abai=(y-1)//a+1
bai=max(tbai,abai)
x=t*bai
y=a*bai
#print(x,y)
print(x+y) |
Today, Osama gave Fadi an integer X, and Fadi was wondering about the minimum possible value of max(a, b) such that LCM(a, b) equals X. Both a and b should be positive integers.
LCM(a, b) is the smallest positive integer that is divisible by both a and b. For example, LCM(6, 8) = 24, LCM(4, 12) = 12, LCM(2, 3) = 6.
O... | 3 | # -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
"""
created by shhuan at 2020/1/10 22:02
"""
def solve(X):
PX = X
SX = int(math.sqrt(X))
MAXN = SX + 1000
p = [True for _ in range(MAXN)]
... |
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help.
Innokentiy decides that new password should satisfy the following conditions:
* the length of the password must be equal to n,
* the password should con... | 3 | import string
alphabet = list(string.ascii_lowercase)
n, k = map(int, input().split())
for i in range(n):
print(alphabet[i%k], end='')
print()
|
Santa Claus has Robot which lives on the infinite grid and can move along its lines. He can also, having a sequence of m points p1, p2, ..., pm with integer coordinates, do the following: denote its initial location by p0. First, the robot will move from p0 to p1 along one of the shortest paths between them (please not... | 3 | L = int(input())
path = input()
movement = [0, 0]
#movement[0] - vertical
#movement[1] - horizontal
#0 - nothing
#1 - up/right
#2 - down/left
num_of_commands = 0
for i in range(L):
if path[i] == 'U':
if movement[0] == 0:
movement[0] = 1
elif movement[0] == 2:
num_of_commands ... |
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 | weight = float(input())
if weight % 2 == 0 and weight != 2:
print('YES')
else:
print('NO') |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | n = int(input())
k = []
for i in range(n):
n, m = map(int, input().split())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
f = False
for j in a:
if j in b:
f = True
k.append(j)
break
else:
f = False
if n... |
You are given an integer number n. The following algorithm is applied to it:
1. if n = 0, then end algorithm;
2. find the smallest prime divisor d of n;
3. subtract d from n and go to step 1.
Determine the number of subtrations the algorithm will make.
Input
The only line contains a single integer n (2 β€... | 3 | n = int(input())
done = 0
if n%2==0:
print(int(n/2) )
else:
for divisor in range(3,int(n**.5)+1 ):
if n%divisor==0:
print( int((n-divisor)/2 + 1 ))
done = 1
break
if done==0:
print(1)
|
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1β€iβ€N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th qu... | 1 | import sys
sys.setrecursionlimit(10 ** 8)
def dfs(now, par, d, dist, g):
dist[now] = d
for to, cost in g[now]:
if to == par: continue
dfs(to, now, d + cost, dist, g)
n = int(raw_input())
g = [[] for _ in xrange(n)]
for i in xrange(n - 1):
a, b, c = map(int, raw_input().split())
a -= 1... |
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 | for i in range(int(input())):
n=int(input())
for k in range(2,n+1):
if(n%((2**k)-1)==0):
print(n//((2**k)-1))
break
|
Lunar New Year is approaching, and you bought a matrix with lots of "crosses".
This matrix M of size n Γ n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 β€ i, j β€ n. We define a cross appearing in the i-th row and the j-th column (1 < i... | 3 | import sys
data = sys.stdin.read().splitlines()
n = int(data[0])
grid = [line for line in data[1:]]
cnt = 0
for i in range(1, n - 1):
for j in range(1, n - 1):
if grid[i][j] == grid[i - 1][j - 1] == grid[i - 1][j + 1] == grid[i + 1][j -
1] == grid[i + 1][j + 1] == 'X':
cnt += ... |
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the... | 3 | #### IMPORTANT LIBRARY ####
############################
### DO NOT USE import random --> 250ms to load the library
############################
### In case of extra libraries: https://github.com/cheran-senthil/PyRival
######################
####### IMPORT #######
######################
from functools import cm... |
You are given q queries in the following form:
Given three integers l_i, r_i and d_i, find minimum positive integer x_i such that it is divisible by d_i and it does not belong to the segment [l_i, r_i].
Can you answer all the queries?
Recall that a number x belongs to segment [l, r] if l β€ x β€ r.
Input
The first l... | 3 | t = int(input())
for i in range(t):
l, r, d = map(int, input().split())
if(d<l or d>r):
print(d)
else:
print((r//d)*d+d) |
Like any unknown mathematician, Yuri has favourite numbers: A, B, C, and D, where A β€ B β€ C β€ D. Yuri also likes triangles and once he thought: how many non-degenerate triangles with integer sides x, y, and z exist, such that A β€ x β€ B β€ y β€ C β€ z β€ D holds?
Yuri is preparing problems for a new contest now, so he is v... | 3 | a,b,c,d = list(map(int, input().split()))
rows, columns, maxEntry = c-b+1, b-a+1, d-c+1
count, prev = 0, 0
for n in range(1,a):
prev += (rows-sorted([n-maxEntry,rows,0])[1]-max(0,rows-n))
for n in range(a,b+1):
prev += (rows-sorted([n-maxEntry,rows,0])[1]-max(0,rows-n))
count += prev
print(count) |
The School β0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | t=int(input())
l=list(map(int,input().split()))
l1=[]
l2=[]
l3=[]
for i in range(t):
if(l[i]==1):
l1.append(i+1)
elif(l[i]==2):
l2.append(i+1)
else:
l3.append(i+1)
x=min(len(l1),(min(len(l2),len(l3))))
if(x==0):
print(0)
else:
print(x)
for i in range(x):
print(l1[... |
Vasya became interested in bioinformatics. He's going to write an article about similar cyclic DNA sequences, so he invented a new method for determining the similarity of cyclic sequences.
Let's assume that strings s and t have the same length n, then the function h(s, t) is defined as the number of positions in whic... | 3 | n = int(input())
s = input()
dflt = "ACGT"
a = []
a.append(s.count(dflt[0]))
a.append(s.count(dflt[1]))
a.append(s.count(dflt[2]))
a.append(s.count(dflt[3]))
k = 1
max = a[0]
for i in range(1, 4):
if a[i] > max:
k = 1
max = a[i]
elif a[i] == max:
k += 1
print((k ** n) % (10 ** 9 + 7)) |
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | def fun(n,str1):
list1=list(str1)
c=0
while(1):
k=0
i=0
while(i<n-1):
if list1[i]=='A' and list1[i+1]=='P':
list1[i+1]='A'
i=i+2
k=k+1
else:
i=i+1
if(k>0):
c=c+1
else:
... |
Joisino is working as a receptionist at a theater.
The theater has 100000 seats, numbered from 1 to 100000.
According to her memo, N groups of audiences have come so far, and the i-th group occupies the consecutive seats from Seat l_i to Seat r_i (inclusive).
How many people are sitting at the theater now?
Constrai... | 3 | n = int(input())
ans = 0
for _ in range(n):
a,b = map(int, input().split())
ans += b-a + 1
print(ans) |
Coding in Sprout (a programming language) is very intuitive. Chef is giving his minions a demonstration in Sprout and wants you to
help him determine if they are not too difficult for them.
A program in Sprout is written using three kinds of instructions.
Load Instruction: Load a value into buffer.
Increment Instr... | 1 | t=int(raw_input())
while t>0:
a=raw_input()
l=len(a)
count=l+1
for i in range(l-1):
p=ord(a[i])
q=ord(a[i+1])
if(p>q):
count+=(123-97-p+q)
else:
count+=(q-p)
if count<=(11*l):
print "YES"
else:
print "NO"
t-=1 |
You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | 3 | # Chan Elizabeth 2201797001
# Reference from Jason
sizeA = int(input())
elementA = input()
sizeB = int(input())
elementB = input()
def splitting(size, element):
num = []
split = element.split(" ")
for i in range(size):
num.append(int(split[i]))
return num
A = splitting(sizeA, elementA)
B = ... |
You are given two arrays of integers a_1,β¦,a_n and b_1,β¦,b_m.
Your task is to find a non-empty array c_1,β¦,c_k that is a subsequence of a_1,β¦,a_n, and also a subsequence of b_1,β¦,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | for i in range(int(input())):
n,m=map(int,input().split())
An=list(map(int,input().split()))
Bm=list(map(int,input().split()))
An_set=set(An)
Bm_set=set(Bm)
inter=An_set.intersection(Bm_set)
if(len(inter)==0):
print("NO")
else:
print("YES")
print(1,list(inter)[0])
|
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())-1
b = input()
count = 0
x = 0
y = 1
for colour in b:
if n>0:
if b[x] == b[y]:
count += 1
x += 1
y += 1
n -= 1
print(count) |
Today, Yasser and Adel are at the shop buying cupcakes. There are n cupcake types, arranged from 1 to n on the shelf, and there are infinitely many of each type. The tastiness of a cupcake of type i is an integer a_i. There are both tasty and nasty cupcakes, so the tastiness can be positive, zero or negative.
Yasser, ... | 3 | def isYasserHappy(tastiness):
summation = 0
total_sum = sum(tastiness)
for i in range(len(tastiness)):
if tastiness[i] <= 0 and (-tastiness[i] >= summation or -tastiness[i] >= total_sum - summation - tastiness[i]) :
return "NO"
summation += tastiness[i]
return "YES"
useless = int(input())
for i in range(use... |
This is the easy version of this problem. The only difference is the constraint on k β the number of gifts in the offer. In this version: k=2.
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky β today the offer "k of goods for the price of one" is held in store... | 3 | def ii(): return int(input())
def si(): return input()
def mi(): return map(int,input().split())
def li(): return list(mi())
for i in range(ii()):
n,p,k=mi()
a=li()
a.sort()
s=[]
if a[0]>p:
print(0)
else:
ans=0
for i in range(n):
if i>1:
... |
Write a program which reads three integers a, b and c, and prints "Yes" if a < b < c, otherwise "No".
Constraints
* 0 β€ a, b, c β€ 100
Input
Three integers a, b and c separated by a single space are given in a line.
Output
Print "Yes" or "No" in a line.
Examples
Input
1 3 8
Output
Yes
Input
3 8 1
Output... | 1 | a,b,c=raw_input().split()
if a<b<c:
print 'Yes'
else :
print 'No' |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner β Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | no_of_games = input()
game_winners = input()
anton = game_winners.count("A")
darwik = game_winners.count("D")
if anton > darwik :
print("Anton")
elif darwik == anton :
print("Friendship")
else :
print('Danik') |
We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied:
* For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers ar... | 3 | h, w, a, b = map(int, input().split())
row_0 = '0' * a + '1' * (w - a)
row_1 = '1' * a + '0' * (w - a)
for _ in range(b):
print(row_0)
for _ in range(h - b):
print(row_1) |
You are given an array a of n integers.
You want to make all elements of a equal to zero by doing the following operation exactly three times:
* Select a segment, for each number in this segment we can add a multiple of len to it, where len is the length of this segment (added integers can be different).
It can... | 1 |
from __future__ import division
import sys
input = sys.stdin.readline
import math
from math import sqrt, floor, ceil
from collections import Counter, defaultdict
from copy import deepcopy as dc
# from statistics import median, mean
############ ---- Input Functions ---- ############
def inp():
return(int(input()... |
Petya has n integers: 1, 2, 3, ..., n. He wants to split these integers in two non-empty groups in such a way that the absolute difference of sums of integers in each group is as small as possible.
Help Petya to split the integers. Each of n integers should be exactly in one group.
Input
The first line contains a s... | 3 | n = int(input())
l = []
r = []
ls = rs = 0
for i in range(n, 0, -1):
if ls <= rs:
ls += i
l.append(i)
else:
rs += i
r.append(i)
print (abs(ls-rs))
print(len(l), *l)
|
This is the easy version of the problem. The difference between the versions is the constraint on n and the required number of operations. You can make hacks only if all versions of the problem are solved.
There are two binary strings a and b of length n (a binary string is a string consisting of symbols 0 and 1). In ... | 3 | import math
t = int(input())
rez = []
def rev(a, n):
l = 0
r = n
for j in range(n+1):
if a[j] == "0":
a[j] = "1"
else:
a[j] = "0"
while l < r:
buf = a[l]
a[l] = a[r]
a[r] = buf
l+=1
r-=1
return a
for i in range(t):
... |
One day a highly important task was commissioned to Vasya β writing a program in a night. The program consists of n lines of code. Vasya is already exhausted, so he works like that: first he writes v lines of code, drinks a cup of tea, then he writes as much as <image> lines, drinks another cup of tea, then he writes <... | 3 | n,m=map(int,input().split())
l,r=0,n
mins=999999999999
while abs(l-r)!=1:
mid=(l+r)//2
cnt=0
mid_copy=mid
while mid>=1:
cnt+=mid
mid//=m
if n<=cnt:
mins=min(mins,mid_copy)
r=mid_copy
continue
if n==cnt:
print(min_copy)
break
if cnt>n:
... |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th... | 3 | from math import floor, sqrt
n, k = map(int, input().strip().split())
time = 240 - k
c = - floor((240 -k ) * 2 / 5)
print(min(n, floor(max((-1 + sqrt(1 - 4*c))/2, (-1 - sqrt(1 - 4*c))/2))))
|
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())
k = 0
while n > 0:
n -= 1
a, b, c = map(int, input().split())
d = a + b + c
if d >= 2:
k += 1
print(k) |
Fennec is fighting with N monsters.
The health of the i-th monster is H_i.
Fennec can do the following two actions:
* Attack: Fennec chooses one monster. That monster's health will decrease by 1.
* Special Move: Fennec chooses one monster. That monster's health will become 0.
There is no way other than Attack and... | 3 | N, K = map(int, input().split())
*H, = sorted(map(int, input().split()), reverse=True)
print(sum(H[K:]))
|
An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | 3 | # import time
def solve(n, deltas):
min_ = 1
l = [1]
for ele in deltas:
new = l[-1] + ele
min_ = min(min_, new)
l.append(new)
l_s = sorted(l)
for i, ele in enumerate(l_s):
if i != ele - min_:
return '-1'
return ' '.join(map(str, [ele - min_ + 1 for el... |
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | 3 | t = int(input())
for _ in range(t):
n, m = map(int, input().split())
a = list(map(int, input().split()))
total = sum(a)
if m <= total:
print(m)
else:
print(total)
|
Takahashi has N sticks that are distinguishable from each other. The length of the i-th stick is L_i.
He is going to form a triangle using three of these sticks. Let a, b, and c be the lengths of the three sticks used. Here, all of the following conditions must be satisfied:
* a < b + c
* b < c + a
* c < a + b
How... | 3 | from bisect import*
N,*L=map(int,open(0).read().split());L.sort()
a=0
for i in range(N):
for j in range(i+1,N):
a+=bisect_left(L,L[i]+L[j],j+1)-j-1
print(a) |
Notes
Template in C
Constraints
* 1 β€ n β€ 100000
* 1 β€ q β€ 1000
* 1 β€ timei β€ 50000
* 1 β€ length of namei β€ 10
* 1 β€ Sum of timei β€ 1000000
Input
n q
name1 time1
name2 time2
...
namen timen
In the first line the number of processes n and the quantum q are given separated by a single space.
In the following n li... | 3 | from collections import deque
n, q = map(int, input().split())
ps = [input().split() for _ in range(n)]
que = deque(ps)
time = 0
while que:
p, rest = que.popleft()
elapsed = min(q, int(rest))
time += elapsed
rest = str(int(rest) - elapsed)
if int(rest) > 0:
que.append([p, rest])
el... |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n β length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | 3 | t = int(input())
for _ in range(t):
n = int(input())
a = [int(s) for s in input().split(" ")]
zeroes = 0
ones = 0
output = ""
for num in a:
if num == 0:
zeroes += 1
else:
ones += 1
if zeroes >= n // 2:
print(zeroes)
print('0 ' * zeroes)... |
We have a grid with H rows and W columns. At first, all cells were painted white.
Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.
Compute the following:
* For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3Γ3 of the gr... | 3 | from collections import defaultdict
h,w,n=map(int,input().split())
d=defaultdict(int)
s=set()
for _ in range(n):
a,b=map(int,input().split())
a-=1
b-=1
for dy in [-2,-1,0]:
for dx in [-2,-1,0]:
ny,nx=a+dy,b+dx
if 0<=ny<h and 0<=nx<w and ny+2<h and nx+2<w:
d[(ny,nx)]+=1
s.add((ny,... |
You are given a three-digit positive integer N.
Determine whether N is a palindromic number.
Here, a palindromic number is an integer that reads the same backward as forward in decimal notation.
Constraints
* 100β€Nβ€999
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output... | 3 | s=input()
print("YNeos"[s[0] != s[2]::2]) |
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 | def gaurd(values,h):
total=0
for i in range(len(values)):
if values[i]<=h:
total=total+1
elif values[i]>h:
total=total+2
return total
n,h=map(int,input().split())
values=list(map(int,input().split()))
print(gaurd(values, h))
|
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 | def same_sums():
n = int(input())
# find sum minus each element
allarrs = []
for i in range(n):
input()
sequence = list(map(int, input().split()))
s = sum(sequence)
for element in range(len(sequence)):
sminusel = s - sequence[element]
allarrs.appe... |
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())
while (t>0):
x,y,n=input().split()
x,y,n=int(x),int(y),int(n)
n
temp=int(n/x)
ans=(x*temp)+y
if (ans>n):
temp-=1
ans=(x*temp)+y
print(ans)
t-=1 |
We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is `S`, it means it was sunny on the i-th day; if that character is `R`, it means it was rainy on that day.
Find the maximum number of consecutive rainy days in this period.
... | 3 | S=input().split("S")
ans=0
for i in S:
ans=max(ans,len(i))
print(ans)
#γγζγγ€γδΊΊγγγγͺγ |
You are given integers A and B, each between 1 and 3 (inclusive).
Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number.
Constraints
* All values in input are integers.
* 1 \leq A, B \leq 3
Input
Input is given from Standard Input in the following format:
A... | 3 | A, B = map(int, input().split())
print("Yes" if A*B%2 else "No")
|
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket.
For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ... | 3 | if __name__ == "__main__":
_ = input()
coins = list(map(int, input().split()))
occ = dict()
m = 0
for c in coins:
if c in occ:
occ[c] += 1
else:
occ[c] = 1
m = max(m, occ[c])
print(m) |
HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s... | 1 | n,= map(int,raw_input().split())
f = map(int,raw_input().split())
idx = [0 for i in f]
for i in xrange(len(f)):
idx[f[i] - 1] = i
print sum([abs(idx[i] - idx[i + 1]) for i in range(n - 1)])
|
A permutation p of size n is an array such that every integer from 1 to n occurs exactly once in this array.
Let's call a permutation an almost identity permutation iff there exist at least n - k indices i (1 β€ i β€ n) such that pi = i.
Your task is to count the number of almost identity permutations for given numbers... | 1 | n,k=map(int,raw_input().split())
ans=1
p=[0,1,1,2,9]
t=n
for i in range(2,k+1):
t=t*(n-i+1)//i
ans+=t*p[i]
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.