problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Mishka is a little polar bear. As known, little bears loves spending their free time playing dice for chocolates. Once in a wonderful sunny morning, walking around blocks of ice, Mishka met her friend Chris, and they started playing the game.
Rules of the game are very simple: at first number of rounds n is defined. I... | 3 | n = int(input())
countm = 0
countc = 0
for i in range(1, n + 1):
a, b = map(int, input().split())
if a > b:
countm += 1
elif b > a:
countc += 1
if countm > countc:
print("Mishka")
elif countm == countc:
print("Friendship is magic!^^")
else:
print("Chris") |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 1 | vowels = set(['a','e','i','o','u','y'])
string = raw_input().lower()
characters = []
k = 0
for i in string:
characters.append(i)
if characters[k] not in vowels:
characters[k] = "."+characters[k]
k += 1
else:
del characters[k]
string = ''.join(characters)
print string |
Polycarp lives on the coordinate axis Ox and travels from the point x=a to x=b. It moves uniformly rectilinearly at a speed of one unit of distance per minute.
On the axis Ox at the point x=c the base station of the mobile operator is placed. It is known that the radius of its coverage is r. Thus, if Polycarp is at a ... | 3 | from sys import stdin, exit
from math import *
def main():
def len_intersect(a, b, c, d):
if d <= a or c >= b:
return 0
u, v = (max(a, c), min(b, d))
return max(0, v - u)
for testcase in range(int(stdin.readline())):
a, b, c, r = map(int, stdin.readline().split())
... |
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Ki... | 3 | num = input().split('.')
if int(num[0]) % 10 == 9 :
print("GOTO Vasilisa.")
else:
if int(num[1][0]) >= 5:
print(int(num[0]) + 1)
else:
print(int(num[0]))
|
There are n children in Jzzhu's school. Jzzhu is going to give some candies to them. Let's number all the children from 1 to n. The i-th child wants to get at least ai candies.
Jzzhu asks children to line up. Initially, the i-th child stands at the i-th place of the line. Then Jzzhu start distribution of the candies. ... | 3 | import math
l0=input().split()
n=int(l0[0])
t=int(l0[1])
l=list(map(int,input().split()))
m=max(l)
y=math.ceil(m/t)-1
ll=[]
for i in range(n):
ll.append(l[i]-y*t)
c=0
for j in range(n):
if ll[j]>0:
c=j
print(c+1) |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
out = 0
for i in range(n):
v = list(map(int,input().split()))
if v[1]-v[0]>=2:
out +=1
print(out)
|
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ... | 3 | n = int(input())
res = False
for i in range(n):
a, b = map(int, input().split())
if a != b:
print('Happy Alex')
res = True
break
if not res:
print('Poor Alex')
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and ... | 3 | a, b = [int(x) for x in input().split()]
d1 = min(a, b)
a -= d1
b -= d1
d2 = max(a, b) // 2
print(d1, d2) |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | x=input()
if x.find("0000000")!=(-1) :
print("YES")
elif x.find("1111111")!=(-1) :
print("YES")
else:
print("NO") |
There are N gems. The value of the i-th gem is V_i.
You will choose some of these gems, possibly all or none, and get them.
However, you need to pay a cost of C_i to get the i-th gem.
Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid.
Find the maximum possible value of X-Y.
Co... | 1 | n=int(raw_input())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
t=0
for i in xrange(n):
d=a[i]-b[i]
if d>0:
t=t+d
print t
|
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ... | 3 | n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
del a[0],b[0]
for i in b:
a.append(i)
f,f2=0,0
for i in range(1,n+1):
s=0
for j in a:
if i==j:s=s+1;break
if s==1:f=f+1
else:f2=f2+1
if f2==0:print('I become the guy.')
if f2>0:print('Oh, my keyboard!')
|
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has n apartments that are numbered from 1 to n and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.
Maxim often visits h... | 3 | def f(l):
n,k = l
return [min(1,k,n-k),min(k<<1,n-k)]
l = list(map(int,input().split()))
print(*f(l))
|
The USA Construction Operation (USACO) recently ordered Farmer John to arrange a row of n haybale piles on the farm. The i-th pile contains a_i haybales.
However, Farmer John has just left for vacation, leaving Bessie all on her own. Every day, Bessie the naughty cow can choose to move one haybale in any pile to an a... | 3 | t = int(input())
for i in range(t):
n , d= map(int , input().split())
a = [ int(x) for x in input().split()]
s = 0; i=1
while i < n and d > 0 :
w = a[i ]*i
if w <= d:
s+=a[i] ; d= d-w
else :
s+=(d//i) ;d=0
i+=1
print(s+a[0])
|
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the... | 3 | q=input("")
q=int(q)
outs=[]
for i in range (q):
query=input("")
pile=query.split()
Sum=0
alice=0
bob=0
for j in range (3):
pile[j]=int(pile[j])
Sum=Sum+pile[j]
if Sum%2==0:
outs.append(Sum//2)
else:
pile.sort()
alice=pile[0]
bob=pile[1]
... |
Pavel made a photo of his favourite stars in the sky. His camera takes a photo of all points of the sky that belong to some rectangle with sides parallel to the coordinate axes.
Strictly speaking, it makes a photo of all points with coordinates (x, y), such that x_1 ≤ x ≤ x_2 and y_1 ≤ y ≤ y_2, where (x_1, y_1) and (x... | 3 | #there would be two sets
#first set both (x1,y1)(x2,y2) in two differnt sorted half sets
#second set boty (x1,y1)(x2,y2) in same sets
n=int(input());m=2*n
arr=list(map(int,input().split()));arr=sorted(arr)
set1_ans=(arr[n-1]-arr[0])*(arr[2*n-1]-arr[n])
#print(set1_ans)
set2_ans=1e20
for i in range(1,n):
a=(arr[2*n-1]... |
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems.
Polycarp decided to store the hash of the password, generated by the following algorithm:
1. take the password p, consisting of lowercase Latin letters, and shuffle the l... | 3 | t = int(input())
for i in range(t):
k = False;
p = list(input())
p.sort()
h = list(input())
if( len(p) == len(h) ):
h.sort()
if(p == h):
print("YES")
else:
print("NO")
k = True
else:
for i in range(0,len(h)-len(p)+1):
lis1 = h[i:i+len(p)]
lis1.sort()
if( lis1 == p ):
print("YES")
... |
You are given a string s consisting of lowercase English letters and a number k. Let's call a string consisting of lowercase English letters beautiful if the number of occurrences of each letter in that string is divisible by k. You are asked to find the lexicographically smallest beautiful string of length n, which is... | 3 | from collections import defaultdict
from itertools import accumulate
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ANS))+"\n")
'''
inf = 1000000000000... |
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())
n = 10 ** 9
Y = (n - (S % n)) % n
X = (S + Y) // n
print("0 0 1 {} {} {}".format(n, X, Y)) |
Valery is very interested in magic. Magic attracts him so much that he sees it everywhere. He explains any strange and weird phenomenon through intervention of supernatural forces. But who would have thought that even in a regular array of numbers Valera manages to see something beautiful and magical.
Valera absolutel... | 1 | def fuc(n):
if n == 1: return 1
else:
return n * (n - 1) / 2 + n
from collections import defaultdict
n = int(raw_input())
a = map(int, raw_input().split())
res = 0
prev = 0
total = 0
for i in xrange(n + 1):
if i == n or i != 0 and prev != a[i]:
res += fuc(total)
total = 1
else:
... |
According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'... | 3 | H,W = map(int, input().split())
board = [] * W
for i in range(H):
board.append(input())
ok = True
c = ""
for i in range(H):
for j in range(1, W):
if (board[i][j] != board[i][j - 1]):
ok = False
break
if (c == board[i][0]):
ok = False
break
c = board[i][0]... |
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent.
One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea... | 3 |
a=int(input())
b=list(map(int,input().split()))
d=0
for i in range(a):
d=d+b[i]
d=d/a
print("{:.12f}".format(d))
|
This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ... | 3 | s=input()
s=s.lower()
m=max(s)
print(m*s.count(m)) |
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning.
To check which buttons need replacement, Polycarp pressed som... | 3 | from itertools import groupby
t = int(input())
while t > 0:
l = []
t -= 1
s = input()
groups = [''.join(g) for _, g in groupby(s)]
for x in groups:
if len(x) % 2 == 1:
l.append(x[0])
ans = ""
l = sorted(set(l))
for i in l:
ans += i
print(ans)
... |
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 | t=int(input())
for i in range(t):
n=int(input())
l=[]
for j in range(n):
l.append(j+1)
print(*l) |
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... | 1 | if __name__ == '__main__':
nana,kam = map(int,raw_input().split(" "))
minimosn=0
for its in range(1, nana+1):
minimosn+=its*5
if(minimosn>240-kam):
print its-1
exit()
print its
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | a = input().lower()
b = input().lower()
if len(a) > len(b):
print(1)
elif len(a) == len(b):
ans = 0
for i in range(len(a)):
if ord(a[i]) > ord(b[i]):
ans = 1
break
elif ord(a[i]) < ord(b[i]):
ans = -1
break
else:
continue
print(ans)
else:
print(-1) |
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot.
He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a.
Will the robot be able to build the fence Emuskald... | 1 | import sys
N = int(sys.stdin.readline())
for i in range(N):
a = int(sys.stdin.readline())
n = 360.0 / (180 - a)
I = int(n)
if I == n:
print("YES")
else:
print("NO")
|
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | n,t=map(int,input().split())
m=[int(x) for x in input().split()]
s=[0]
i=0
while i<=n-2:
i=i+m[i]
s.append(i)
if t-1 in s:
print('YES')
else:
print('NO')
|
You are playing the following game with Joisino.
* Initially, you have a blank sheet of paper.
* Joisino announces a number. If that number is written on the sheet, erase the number from the sheet; if not, write the number on the sheet. This process is repeated N times.
* Then, you are asked a question: How many numbe... | 3 | N = int(input())
A = [int(input()) for _ in range(N)]
paper = set()
for a in A:
paper ^= {a}
print(len(paper)) |
Running with barriers on the circle track is very popular in the country where Dasha lives, so no wonder that on her way to classes she saw the following situation:
The track is the circle with length L, in distinct points of which there are n barriers. Athlete always run the track in counterclockwise direction if you... | 3 | n, l = (map(int, input().split(' ')))
if n == 1:
print("YES")
else:
a = list(map(int, input().split(' ')))
b = list(map(int, input().split(' ')))
a = a + a[:-1]
found = False
for i in range(n):
flag = True
for j in range(n-1):
k = i+j
diff_a = a[k+1]-a[k] if a[k+1] > a[k] else a[k+1]+l... |
Ilya is an experienced player in tic-tac-toe on the 4 × 4 field. He always starts and plays with Xs. He played a lot of games today with his friend Arseny. The friends became tired and didn't finish the last game. It was Ilya's turn in the game when they left it. Determine whether Ilya could have won the game by making... | 3 | T = {}
for i in range(4):
s = input()
for (j, c) in enumerate(s):
if c == 'x':
T[(i, j)] = 'x'
elif c == 'o':
T[(i, j)] = 'o'
def test(T, a):
e = 0
oc = 0
for (i, j) in a:
if (i, j) in T:
if T[(i, j)] == 'x':
oc += 1
... |
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 3 | import sys
t = int(sys.stdin.readline().strip())
for j in range(t):
n = int(input())
l = list(map(int, sys.stdin.readline().strip().split()))
l.sort()
ans = 0
i = 0
while i < n:
#print(i)
if i+l[i]<=n:
if l[i+l[i]-1] == l[i]:
i += l[i]
... |
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n.
* Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin... | 3 | n=int(input(""))
def lis(l2):
le=[1]
for k in range(2,len(l2)+1):
le.append(sum(l2[:k]))
le.append(le[len(le)-1]+2*l2[len(l)-1])
return le
if(n==1 or n==2):
print(n)
else:
l=[1,3]
for k in range(n-3):
l=lis(l)
print(2*l[len(l)-1])
|
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of... | 3 | n,k=map(int,input().split())
q=[0]*n
for i in range(n-1):
a,b=map(int,input().split())
q[a-1]+=1
q[b-1]+=1
c=0
for i in range(n):
if q[i]==1:
c+=1
print(2*k/c) |
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n.
He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se... | 3 |
def solve():
t = int(input())
for i in range(t):
n = int(input())
ans = (n-1)//2+1
print(ans)
if __name__ == '__main__':
solve()
|
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | 3 | preList = [4,7,44,47,74,77,444,447,474,477,744,747,774,777]
n = int(input())
for i in preList:
if i>n:
print("NO")
exit()
if n%i==0:
print("YES")
exit()
print("NO") |
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ... | 3 | t=int(input())
while t:
res=[]
s=input()
i=0
n=len(s)
while i<n:
#st=s[i-2]+s[i-1]+s[i]
if(i+4<n):
st=s[i]+s[i+1]+s[i+2]+s[i+3]+s[i+4]
if(st=='twone'):
res.append(i+2+1)
i=i+5
else:
st=s[i]+s[i+1]+s[i+2]
... |
Input
The input contains a single integer a (0 ≤ a ≤ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | 3 | x = int(input())
s = bin(x)[2:]
s = list('0'*(6-len(s))+s)
new = [0]*6
new[0] = s[0]
new[1] = s[5]
new[2] = s[3]
new[3] = s[2]
new[4] = s[4]
new[5] = s[1]
res = 0
for c in new:
res = 2 * res +int(c)
print(res) |
Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashta... | 1 | n = int(raw_input())
char = [''] * n
size = [0] * n
for i in range(n):
char[i] = raw_input()
size[i] = len(char[i])
for i in range(n - 1, 0, -1):
a = char[i - 1]
alen = size[i - 1]
b = char[i]
blen = size[i]
stop = min(alen, blen)
j = 0
flag = 0
while j < stop:
if a[j] > b[j]:
flag = -1
break
elif ... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 1 | n,k=map(int,raw_input().split(' '))
mid=(n/2)+(n%2)
print k*2-1 if(k<=mid) else (k-mid)*2 |
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 | n = input()
d = input()
num = {}
num['A'], num['D'] = 0, 0
for i in d:
num[i]+=1
if num['A'] > num['D']:
print("Anton")
elif num['A'] < num['D']:
print("Danik")
else:
print("Friendship") |
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences.
Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the... | 1 | # your code goes here
n=int(raw_input())
a=raw_input().split()
sum1=0
sum2=0
for i in a:
if int(i)>0:
sum1+=int(i)
else:
sum2+=int(i)
print sum1-sum2 |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | string = input()
l = []
for ch in string:
if ch not in l:
l.append(ch)
leng = len(l)
if(leng % 2 == 0):
print("CHAT WITH HER!")
else:
print("IGNORE HIM!") |
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis... | 3 |
x = [int(i) for i in input().split()]
s = x[0]
v1 = x[1]
v2 = x[2]
t1 = x[3]
t2 = x[4]
boy1 = s*v1 + t1*2
boy2 = s*v2 + t2*2
if boy1 > boy2:
print("Second")
elif boy1 < boy2:
print("First")
else :
print("Friendship") |
You know that Japan is the country with almost the largest 'electronic devices per person' ratio. So you might be quite surprised to find out that the primary school in Japan teaches to count using a Soroban — an abacus developed in Japan. This phenomenon has its reasons, of course, but we are not going to speak about ... | 3 |
I = lambda: map(int,input().split())
res = [ 'O-|-OOOO',
'O-|O-OOO',
'O-|OO-OO',
'O-|OOO-O',
'O-|OOOO-',
'-O|-OOOO',
'-O|O-OOO',
'-O|OO-OO',
'-O|OOO-O',
'-O|OOOO-']
n = input()
for i in n[::-1]:
print(res[int(i)]) |
Akari has n kinds of flowers, one of each kind.
She is going to choose one or more of these flowers to make a bouquet.
However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b.
How many different bouquets are there that Akari can make?
Find the count modulo (10^9 + 7).
Here,... | 3 | n,a,b = map(int,input().split())
mod = 1000000007
ans = pow(2,n,mod) - 1
def fur(n,k):
p,q = 1,1
for i in range(k):
p = p * (n-i) % mod
q = q * (i+1) % mod
return p * pow(q,mod-2,mod) % mod
print((ans - fur(n,a) - fur(n,b)) % mod) |
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 | def nCr(n, r):
return (fact(n) / (fact(r)
* fact(n - r)))
def fact(n):
res = 1
for i in range(2, n+1):
res = res * i
return res
n=int(input(''))
a=[]
cnt=0
for ii in range(n):
s=input('')
a.append(s[0])
for i in range(97,123):
t=a.count(c... |
You are given a following process.
There is a platform with n columns. 1 × 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all ... | 3 | #Winners never quit, quiters never win............................................................................
from collections import deque as de
import math
from collections import Counter as cnt
from functools import reduce
from typing import MutableMapping
def factors(n):
return set(reduce(list.__add__... |
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... | 3 | a, b = map(int, input().split())
cur_b = 0
counter = 0
while a > 0:
counter += a
cur_b += a
a, cur_b = cur_b // b, cur_b % b
print(counter) |
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subse... | 3 | n = int(input())
a = list(map(int, input().split(' ')))
if (n & 1) and (a[0] & 1) and (a[-1] & 1):
print("Yes")
else:
print("No")
|
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())
li = [100, 20,10,5,1]
res = 0
for i in li:
res += n//i
n -= (n//i)*i
print(res) |
We have a string of letters 'a' and 'b'. We want to perform some operations on it. On each step we choose one of substrings "ab" in the string and replace it with the string "bba". If we have no "ab" as a substring, our job is done. Print the minimum number of steps we should perform to make our job done modulo 109 + 7... | 3 | MOD = 10**9 + 7
s = input()
bcount, count = 0, 0
for c in reversed(s):
if c == 'b':
bcount += 1
else:
count = (count + bcount) % MOD
bcount = bcount * 2 % MOD
print(count)
|
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th... | 3 | # 数学 > 计算
import re
MAX_NUMBER = 26
countInBitArray = [1]
# w位的列有多少个
def countInBit(w):
if w >= len(countInBitArray):
count = countInBit(w - 1) * MAX_NUMBER
countInBitArray.append(count)
return countInBitArray[w]
countBeforeBitArray = [0]
# 前w位的列有多少个, 包括w位, 不包括0
def countBeforeBit(w):
... |
Kolya is going to make fresh orange juice. He has n oranges of sizes a1, a2, ..., an. Kolya will put them in the juicer in the fixed order, starting with orange of size a1, then orange of size a2 and so on. To be put in the juicer the orange must have size not exceeding b, so if Kolya sees an orange that is strictly gr... | 3 | det =list(map(int,input().split()))
oranges= list(map(int,input().split()))
n =det[0]
max_size = det[1]
waste_section =det[2]
total =0
times = 0
for i in oranges :
if i > max_size :
continue
else :
total =total +i
if total > waste_section :
times =times +1
... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | rooms = int(input())
pq = []
count = 0
for i in range(rooms):
x = input()
x = [int(x) for x in x.split()]
pq.append(x)
for p,q in pq:
if (p+2 == q) or (p+2 < q):
count += 1
print(count)
|
The map of the capital of Berland can be viewed on the infinite coordinate plane. Each point with integer coordinates contains a building, and there are streets connecting every building to four neighbouring buildings. All streets are parallel to the coordinate axes.
The main school of the capital is located in (s_x, ... | 3 | n, sx, sy = input().split()
n, sx, sy = int(n), int(sx), int(sy)
cl, cr, cu, cd = 0, 0, 0, 0
for i in range(n):
xi, yi = input().split()
xi, yi = int(xi), int(yi)
if xi < sx:
cl += 1
if xi > sx:
cr += 1
if yi < sy:
cd += 1
if yi > sy:
cu += 1
mx = max([cl, cr,... |
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | for test in range(int(input())):
n=int(input())
s=list(map(int,input().split()))
s.sort()
print(min(abs(s[i]-s[i+1]) for i in range(n-1))) |
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | t = int(input())
for _ in range(t):
n, k = map(int, input().split())
a = sorted(map(int, input().split()))
b = sorted(map(int, input().split()), reverse=True)
for i in range(k):
if a[i] >= b[i]:
break
else:
i = k
print(sum(a[i:]) + sum(b[:i]))
|
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | s = str(input())
j = []
s1 = set(s)
l = len(s1)
if l % 2 != 0:
print("IGNORE HIM!")
else:
print("CHAT WITH HER!") |
There is a beautiful garden of stones in Innopolis.
Its most beautiful place is the n piles with stones numbered from 1 to n.
EJOI participants have visited this place twice.
When they first visited it, the number of stones in piles was x_1, x_2, …, x_n, correspondingly. One of the participants wrote down this sequ... | 3 | n=int(input())
x=list(map(int,input().split()))
y=list(map(int,input().split()))
cx=sum(x)
cy=sum(y)
if cy>cx:
print('No')
else:
print('Yes') |
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 | """ Solution to Problem 4A on codeforce.com
Task: Given a number, print YES if the input can be divided into
two even parts, not necessarily equal, and NO in the opposite case."""
userInput = input();
def canDivideIntoTwoEvenParts(number):
if (number % 2 == 0 and number > 2):
return "YES"
else:
... |
Takahashi is going to buy N items one by one.
The price of the i-th item he buys is A_i yen (the currency of Japan).
He has M discount tickets, and he can use any number of them when buying an item.
If Y tickets are used when buying an item priced X yen, he can get the item for \frac{X}{2^Y} (rounded down to the nea... | 3 | import heapq
n,m=map(int,input().split())
a=[-int(x) for x in input().split()]
heapq.heapify(a)
for i in range(m):
t=heapq.heappop(a)
t=-t//2
heapq.heappush(a,-t)
print(-sum(a))
|
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move.
There are n doors, the i-th door initially has durability equal to a_i.
During your move you can try to br... | 1 | n,x,y = map(int,raw_input().split())
a = list(map(int,raw_input().split()))
if x > y:
print n
else:
count = 0
for i in a:
if i <=x:
count+=1
if count % 2 == 0:
print count/2
else:
print (count/2 + 1) |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | num_disks = int(input())
orig_state = [int(i) for i in input()]
last_state = [int(i) for i in input()]
def unlock(num_disks,orig_state,last_state):
l = [last_state[i] - orig_state[i] for i in range(num_disks)]
result = 0
for i in range(num_disks):
if abs(l[i]) > 5:
l[i] = 10 - abs(l[i])
... |
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers.
Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ... | 3 | R = lambda:map(int,input().split())
print(input(), 0, 0) |
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars.
Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles.
I... | 3 | n = int(input())
a = int(input())
b = int(input())
res = 0
numb = a if a >= b else b
no_numb = a if numb == b else b
if a==b:
if n%a==0:
print('YES')
print('%d %d'%(0,n/no_numb))
exit()
else:
print('NO')
exit()
for i in range(n//numb+1):
if (n-i*numb)%no_numb == ... |
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 | import math
def list_str(l, char):
output_str = ""
for i in range(len(l) - 1):
output_str += str(l[i]) + char
output_str += str(l[len(l) - 1])
return output_str
def str_list(s, char):
output_list = []
intermediate = ""
for i in range(len(s)):
if s[i] != char:
... |
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction <image> as a sum of three distinct positive fractions in form <image>.
Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that <image... | 1 | n=int(raw_input())
if n==1:
print -1
else:
print n,n+1,(n)*(n+1)
|
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | import sys
import math
input = sys.stdin.readline
n = int(input().strip(), 2)
x, ans = 1, 0
while x < n:
ans += 1
x *= 4
print(ans)
|
You are given a simple connected undirected graph consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M.
Edge i connects Vertex a_i and b_i bidirectionally.
Determine if three circuits (see Notes) can be formed using each of the edges exactly once.
Constraints
* A... | 3 | import sys
sys.setrecursionlimit(10**6)
n, m = [int(item) for item in input().split()]
edge = [[] for _ in range(n)]
def find_single_self_loop(start, prev, n):
if prev != -1 and len(edge[n]) != 2:
if n == start:
return True
else:
return False
for item in edge[n]:
... |
Draw a rectangle which has a height of H cm and a width of W cm. Draw a 1-cm square by single '#'.
Constraints
* 1 ≤ H ≤ 300
* 1 ≤ W ≤ 300
Input
The input consists of multiple datasets. Each dataset consists of two integers H and W separated by a single space.
The input ends with two 0 (when both H and W are zero)... | 3 | while 1:
a,b=map(int,input().split())
if a==b==0:break
for i in range(a):
print("#"*b)
print()
|
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | 3 | """
Oh, Grantors of Dark Disgrace,
Do Not Wake Me Again.
"""
# import stackprinter
# stackprinter.set_excepthook(style='color')
# import pysnooper
# @pysnooper.snoop()
def solve():
for _ in range(ii()):
n = ii()
w = li()
cnt = [0]*(n+1)
for i in range(n):
cnt[w[i]]... |
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes... | 1 | import sys
line = map(int, raw_input().split())
a = line[0]
b = line[1]
c = line[2]
d = line[3]
m = max(75 * a, 250 * a - a * c)
v = max(75 * b, 250 * b - b * d)
if (m > v): sys.stdout.write('Misha')
elif (m < v): sys.stdout.write('Vasya')
else: sys.stdout.write('Tie')
|
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 | from math import ceil
def f(n):
ne = n//2
no = ceil(n/2)
return (ne*(ne+1) - no*no)
n = int(input())
print(f(n))
|
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | 3 | n=int(input())
if(n%2!=0):
print(-1)
else:
for i in range(1,n+1,2):
print(i+1,i,end=" ") |
Chef loves research! Now he is looking for subarray of maximal length with non-zero product.
Chef has an array A with N elements: A1, A2, ..., AN.
Subarray Aij of array A is elements from index i to index j: Ai, Ai+1, ..., Aj.
Product of subarray Aij is product of all its elements (from ith to jth).
Input
First li... | 1 | __author__ = 'Deepak'
t=int(raw_input())
count=0
prod=1
c=[]
max=0
n=map(int,raw_input().split())
for i in range(len(n)):
if(n[i]!=0):
count+=1
else:
if(count>max):
max=count
count=0
if(max==0):
print count
else:
print max |
Polycarp analyzes the prices of the new berPhone. At his disposal are the prices for n last days: a_1, a_2, ..., a_n, where a_i is the price of berPhone on the day i.
Polycarp considers the price on the day i to be bad if later (that is, a day with a greater number) berPhone was sold at a lower price. For example, if ... | 3 | n = int(input())
for _ in range(n):
k = int(input())
c = list(map(int,input().split()))
minAtm = c[len(c)-1]
ctr = 0
for num in reversed(c):
if num > minAtm:
ctr += 1
else:
minAtm = num
print(ctr) |
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 | p=[0]
a=[]
for i in range(int(input())):
b,n=list(map(int,input().split()))
a.append([b,n])
for j in range(0,len(a)):
p.append(abs(p[len(p)-1]-a[j][0])+a[j][1])
print(max(p))
|
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 3 | x = input()
count = 1
for i in range(len(x)):
if x[i] == x[i-1]:
count += 1
else:
count = 1
if count == 7:
print('YES')
exit()
print('NO')
|
Polycarp has guessed three positive integers a, b and c. He keeps these numbers in secret, but he writes down four numbers on a board in arbitrary order — their pairwise sums (three numbers) and sum of all three numbers (one number). So, there are four numbers on a board in random order: a+b, a+c, b+c and a+b+c.
You h... | 3 | arr = list(map(int, input().split()))
arr.sort()
mx = arr[3]
arr.pop(3)
c = mx - arr[0]
arr.pop(0)
a = arr[0] - c
b = arr[1] - c
print(a,b,c)
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 1 | import sys
from Queue import Queue
from sets import Set
class pythonin:
_data = []
_ldata = []
_cur = 0
_lcur = 0
def __init__(self):
while True:
try: self._ldata.append(raw_input())
except EOFError : break
def _convert(self):
if self._lcur == len(s... |
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between dog... | 3 | n=int(input())
l=list(input())
if n==1:
print("YES")
exit()
if len(set(l))==n:
print("NO")
else:
print("YES") |
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example:
* 10010 and 01111 are similar (they have the same character in position 4);
* 10... | 3 | t = int(input())
for i in range(t):
n = int(input())
s = input()
l = s[n-1]
ans = l*n
print(ans) |
There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i.
You and Lunlun the dachshund alternately perform the following operation (starting from you):
* Choose one or more apples from the tree and eat them. Here, the apples chosen at ... | 3 | n = int(input())
for i in range(n):
a = int(input())
if a % 2 == 1:
print("first")
exit()
print("second") |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | from sys import stdin
t = int(stdin.readline())
for it in range(t):
n = int(stdin.readline())
nums = list(map(int, stdin.readline().split()))
if sum(nums) % 2 != 0:
print("YES")
else:
odds = len(list(filter(lambda x: x % 2 != 0, nums)))
even = len(nums) - odds
if odds... |
You've got an n × m matrix. The matrix consists of integers. In one move, you can apply a single transformation to the matrix: choose an arbitrary element of the matrix and increase it by 1. Each element can be increased an arbitrary number of times.
You are really curious about prime numbers. Let us remind you that a... | 1 | from bisect import bisect
l=lambda:map(int,raw_input().split())
# p=[2,3]
# [p.append(i) for i in range(5,10**5+10,2) if all([i%x for x in p])]
p=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,... |
Given are integers a,b,c and d. If x and y are integers and a \leq x \leq b and c\leq y \leq d hold, what is the maximum possible value of x \times y?
Constraints
* -10^9 \leq a \leq b \leq 10^9
* -10^9 \leq c \leq d \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the follo... | 3 | a, b, c, d = map(int, input().split())
m = [a*c, a*d, b*c, b*d]
print(max(m)) |
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.... | 1 | ans=0
for i in xrange(input()):
if map(int,raw_input().split()).count(1)>=2:
ans+=1
print ans
|
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains n different items numbered from 1 to n. The i-th item has base cost ai Egyptian pounds. If Sagheer buys k items with indices x1, x2, ..., xk, then the cost ... | 3 | import sys
import math
import copy
n, budget = [int(x) for x in sys.stdin.readline().strip().split(" ")]
items = [int(x) for x in sys.stdin.readline().strip().split(" ")]
#n, budget = 1, 7
#items = [7]
def money(k):
cursum = 0
computed = []
for i in range(0, len(items)):
cur = ((i + 1) * k) + items[i]
c... |
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n.
There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from... | 3 | t=int(input())
for _ in range(t):
n,x=tuple(map(int,input().split()))
if n<=2:
print(1)
else:
print((n-3)//x+2) |
Well, here is another math class task. In mathematics, GCD is the greatest common divisor, and it's an easy task to calculate the GCD between two positive integers.
A common divisor for two positive numbers is a number which both numbers are divisible by.
But your teacher wants to give you a harder task, in this task... | 1 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import fractions, bisect
a, b = map(int, raw_input().split())
g = fractions.gcd(a, b)
gl = []
for i in xrange(1, g+1):
if i*i > g: break
if g%i == 0: gl += [i, g/i]
gl = sorted(set(gl))
for _ in xrange(int(raw_input())):
l, h = map(int, raw_input().split())
... |
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 = list(input().split())
print(c+' '+a+' '+b) |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | # -*- coding: utf-8 -*-
"""poopoobutt.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1GpTf0WOSvif-hlDQkdi4cW7w72iExNtM
"""
x = int(input())
ret = []
for i in range(x):
t = input().split(" ")
ret.append(t[1] + " " + t[2] + " " + t[2])
for i i... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | '''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
#print("Hello World")
s=input()
l=list(s)
l.sort()
n=l.count('+')
for j in range(n):
l.remove('+')
s='+'.join(l)
pri... |
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 | def main():
# https://codeforces.com/problemset/problem/705/A
n = int(input())
hate_message = "I hate"
love_message = "I love"
sentence = []
for i in range(1, n+1):
if i % 2:
sentence.append(hate_message)
else:
sentence.append(love_message)
sentence = ... |
Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | 3 | t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
if max(a)==min(a):
print(n)
else:
print(1) |
You are given two sequences a_1, a_2, ..., a_n and b_1, b_2, ..., b_n. Each element of both sequences is either 0, 1 or 2. The number of elements 0, 1, 2 in the sequence a is x_1, y_1, z_1 respectively, and the number of elements 0, 1, 2 in the sequence b is x_2, y_2, z_2 respectively.
You can rearrange the elements i... | 3 | T = int(input())
results = []
for ttt in range(T):
res = 0
a = [int(item) for item in input().split()]
b = [int(item) for item in input().split()]
x = min(a[2], b[1])
res += x * 2
a[2] -= x
b[1] -= x
y = b[2] - a[2] - a[0]
if y > 0:
res -= y * 2
print(res)
|
Cat Noku has obtained a map of the night sky. On this map, he found a constellation with n stars numbered from 1 to n. For each i, the i-th star is located at coordinates (xi, yi). No two stars are located at the same position.
In the evening Noku is going to take a look at the night sky. He would like to find three d... | 3 | #By Tianyi Chen
from math import *
from functools import *
n=int(input())
l=[]
x,y=[int(x) for x in input().split()]
def cmp(a,b):
c=a[0]*b[1]-a[1]*b[0]
if c==0:return a[2]-b[2]
return a[4]-b[4]
for _ in range(1,n):
a,b=input().split()
a=int(a)-x
b=int(b)-y
l.append((a,b,a*a+b*b,_+1,atan2(b,a)))
cc=cmp_to_key(cm... |
You are a member of the space station engineering team, and are assigned a task in the construction process of the station. You are expected to write a computer program to complete the task.
The space station is made up with a number of units, called cells. All cells are sphere-shaped, but their sizes are not necessar... | 3 | class UnionFind():
def __init__(self, n):
self.n = n
self.parents = [-1] * n
def find(self, x):
if self.parents[x] < 0:
return x
else:
self.parents[x] = self.find(self.parents[x])
return self.parents[x]
def union(self, x, y):
x = ... |
Guy-Manuel and Thomas have an array a of n integers [a_1, a_2, ..., a_n]. In one step they can add 1 to any element of the array. Formally, in one step they can choose any integer index i (1 ≤ i ≤ n) and do a_i := a_i + 1.
If either the sum or the product of all elements in the array is equal to zero, Guy-Manuel and T... | 3 |
n = int(input())
for i in range(n):
a = input()
b = [int(b) for b in input().split()]
c = 0
for i in b:
if i == 0:
c = c + 1
if sum(b) + c == 0:
print(c + 1)
else:
print(c) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.