problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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... | 1 | s = raw_input()
if len(s) == 1:
print s
else:
lst = []
t = ''
for i in range(len(s)):
if s[i].isdigit():
lst.append(s[i])
lst.sort()
for i in lst:
t += i + '+'
t = t[:-1]
print t
|
Pashmak has fallen in love with an attractive girl called Parmida since one year ago...
Today, Pashmak set up a meeting with his partner in a romantic garden. Unfortunately, Pashmak has forgotten where the garden is. But he remembers that the garden looks like a square with sides parallel to the coordinate axes. He al... | 3 | # Description of the problem can be found at http://codeforces.com/problemset/problem/459/A
x1, y1, x2, y2 = map(int, input().split())
d = max(abs(x1 - x2), abs(y1 - y2))
if d == 0:
print("-1")
elif x1 != x2 and y1 != y2 and abs(x1 - x2) != abs(y1 - y2):
print("-1")
else:
if x1 == x2:
print("%d %d ... |
Compute A \times B, truncate its fractional part, and print the result as an integer.
Constraints
* 0 \leq A \leq 10^{15}
* 0 \leq B < 10
* A is an integer.
* B is a number with two digits after the decimal point.
Input
Input is given from Standard Input in the following format:
A B
Output
Print the answer as ... | 3 | A,B = input().split()
A = int(A)
B = int(float(B)*1000)
print(A*B//1000) |
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... | 1 | n = int(raw_input())
l = raw_input()
if n == 1:
print 0
else:
res = 0
for i in range(n-1):
if l[i] == l[i+1]:
res += 1
print res
|
You are given an integer n and an integer k.
In one step you can do one of the following moves:
* decrease n by 1;
* divide n by k if n is divisible by k.
For example, if n = 27 and k = 3 you can do the following steps: 27 β 26 β 25 β 24 β 8 β 7 β 6 β 2 β 1 β 0.
You are asked to calculate the minimum numbe... | 3 | t=int(input())
for i in range(t):
n, k = map(int, input().split())
ct = 0
while n != 0:
t = n // k
ct += n - t * k
n = t * k
if n == 0: break
while n % k == 0:
n //= k
ct+=1
print(ct) |
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of... | 1 | n = input()
a = 0
b = []
b1 = 0
c = []
c1 = 0
e = 0
f = 0
for i in xrange(n):
d = input()
a+=d
if d>0:
if e==0:
b.append(d)
b1+=1
f=1
else:
if e==0:
c.append(abs(d))
c1+=1
f=2
if b1>0 and c1>0 and e==0:
d1 = min(b1,c1)
if b[d1-1]>c[d1-1]:
e=1
elif b[d1-1]<c[d1-1]:
e=2
if a>0:
print... |
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 | i,j=0,0
for x in range(5):
s=input().split()
if(s.count("1")):
i=x
j=s.index("1")
print(abs(i-2)+abs(j-2)) |
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | # Final bot test.
T = int(input())
for _ in range(T):
n = int(input())
s = input()
if list(s) == sorted(list(s)):
print(s)
else:
left, right = 1, 1
for i in range(n):
if s[i] == '1':
left = i
break
for i in range(n-1, -1, -1):
... |
Little Alyona is celebrating Happy Birthday! Her mother has an array of n flowers. Each flower has some mood, the mood of i-th flower is ai. The mood can be positive, zero or negative.
Let's define a subarray as a segment of consecutive flowers. The mother suggested some set of subarrays. Alyona wants to choose severa... | 3 | flowers, subarrays = map(int, input().split(" "))
moods = list(map(int, input().split(" ")))
added = 0
for i in range(subarrays):
f, t = map(int, input().split(" "))
val = sum(moods[f-1:t])
if val > 0:
added += val
print(added)
|
Today, as a friendship gift, Bakry gave Badawy n integers a_1, a_2, ..., a_n and challenged him to choose an integer X such that the value \underset{1 β€ i β€ n}{max} (a_i β X) is minimum possible, where β denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
As always, Badawy is too ... | 3 | def recur(arr, val, pos):
if(pos == -1):
return val
on = []
off = []
for i in arr:
if(i & (1<<pos)):
on.append(i)
else:
off.append(i)
if(on and off):
return min(recur(on, val + (1<<pos), pos-1), recur(off, val + (1<<pos), pos - 1))
elif(on)... |
There are two rival donut shops.
The first shop sells donuts at retail: each donut costs a dollars.
The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ... | 1 | # template by 3xC and starkizard.
# contributors:
#####################################################################################
from __future__ import division, print_function
import sys
import os
from collections import Counter, deque, defaultdict
import itertools
import math
import io
"""Uncomment modul... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | y = str(int(input()) + 1)
while True:
if len(set(y)) == 4:
print(y)
break
else:
y = str(int(y) + 1) |
You are given positive integers A and B.
If A is a divisor of B, print A + B; otherwise, print B - A.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \leq 20
Input
Input is given from Standard Input in the following format:
A B
Output
If A is a divisor of B, print A + B; otherwise, print B -... | 3 | a,b=map(int,input().split())
print([a+b,b-a][b%a!=0]) |
There is a frequency operation in the conversion operation of a finite number sequence. The conversion result of the sequence $ S = \\ {s_1, s_2, ... s_n \\} $ is a sequence of the same length. If the result is $ C = \\ {c_1, c_2, ..., c_n \\} $, then $ c_i $ represents the number of $ s_i $ in the sequence $ S $.
For... | 1 | def f(x):
a=x; c=0
while 1:
b=[a.count(e) for e in a]
if a==b: return c," ".join(map(str,a))
else: a=b; c+=1
while 1:
if input()==0: break
c,s=f(map(int,raw_input().split()))
print c; print s |
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i β€ x β€ r_i, and ((x mod a) mod b) β ((x mod b) mod a). Calculate the answer for each query.
Recall that y mod z is the remainder of the division of y by z... | 3 | import math
t = int(input())
def get(A,B,N):
if(N==-1):
return 0;
if(max(A,B) > N):
return N + 1
GCD = int(math.gcd(A,B))
X = GCD * (A//GCD) * (B//GCD)
Delta = min(max(A,B), N - N//X*X + 1)
return max(A,B) + max(N//X-1,0)*max(A,B) + (Delta * int(N>=X))
for _ in range(t):
a,... |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j β i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | t=int(input())
for i in range(t):
n = int(input())
arr= list(map(int,input().split()))
arr.sort(reverse=True)
for i in range(n):
if i==n-1:
print (arr[i])
continue
print (arr[i]," ",end=" " )
|
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,t = list(map(int, input().split()))
s = input()
result = [char for char in s]
for i in range(t):
j = 0
while(j < len(result)-1):
if(result[j] == 'B' and result[j+1]=='G'):
result[j], result[j+1] = result[j+1], result[j]
j += 2
else:
j+=1
print("".join(result))
|
Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
* f(599) = 6: 599 + 1 = 600 β 60 β 6;
* f(7) = 8: 7 + 1 = 8;
* f(9) = 1: 9 + 1 = 10 β 1;
* f(10099) = 101: 10099 + 1 = 10100 β 1010 β 101.
... | 3 | def Next(num):
num = int(num)
result = str(num + 1)
#print(result, result[len(result)-1])
while result[len(result)-1] == '0':
result = result[:-1]
#print(result, result[len(result)-1])
return result
num = input ()
count = 1
while True:
if len(num) == 1:
if num == '0':
... |
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... | 3 | import math
def is_angle(k):
s = 360/(180-k)
return ['NO','YES'][(s - math.floor(s) < 10**(-5))];
n = int(input())
for i in range(n):
print(is_angle(int(input())))
|
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())
ans = 0
for i in range(n):
solve = list(map(int, input().split()))
if solve.count(1) > 1:
ans += 1
print(ans) |
An English booklet has been created for publicizing Aizu to the world. When you read it carefully, you found a misnomer (an error in writing) on the last name of Masayuki Hoshina, the lord of the Aizu domain. The booklet says "Hoshino" not "Hoshina".
Your task is to write a program which replace all the words "Hoshino... | 1 | n=input()
for i in range(n):
print raw_input().replace("Hoshino","Hoshina") |
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())
dic={"Tetrahedron" :4,"Cube" :6,"Octahedron" :8,"Dodecahedron":12,"Icosahedron" :20}
som=0
for i in range(n):
s=input()
som+=dic[s]
print(som) |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | import math
def solve():
n = int(input().strip())
eigths = int(math.ceil(n/4))
nines = n - eigths
print("9"*nines + "8"*eigths)
t = int(input().strip())
for _ in range(t):
solve()
|
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())
result = 0
for i in range(n):
line =input()
arr = line.split()
count_1 = 0
for item in arr:
if int(item) == 1:
count_1 +=1
if count_1 >=2:
result +=1
print(result)
|
You are given a range of positive integers from l to r.
Find such a pair of integers (x, y) that l β€ x, y β€ r, x β y and x divides y.
If there are multiple answers, print any of them.
You are also asked to answer T independent queries.
Input
The first line contains a single integer T (1 β€ T β€ 1000) β the number of... | 3 | # -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import itertools
import sys
"""
created by shhuan at 2018/12/28 22:38
"""
T = int(input())
ans = []
for ti in range(T):
l, r = map(int, input().split())
ans.append((l, 2*l))
print('\n'.join(['{} {}'.format(x, y... |
Now you get Baby Ehab's first words: "Given an integer n, find the longest subsequence of [1,2, β¦, n-1] whose product is 1 modulo n." Please solve the problem.
A sequence b is a subsequence of an array a if b can be obtained from a by deleting some (possibly all) elements. The product of an empty subsequence is equal ... | 3 | from math import gcd
def coprime(a, b):
return gcd(a, b) == 1
N = int(input())
ans = [1]
count = 1
mod = 1
for x in range(2, N):
if coprime(x, N):
ans += x,
count += 1
mod = (mod*x)%N
if mod != 1:
del ans[-1]
count -= 1
print(count)
print(' '.join(map(str, ans))) |
Vlad likes to eat in cafes very much. During his life, he has visited cafes n times. Unfortunately, Vlad started to feel that his last visits are not any different from each other. To fix that Vlad had a small research.
First of all, Vlad assigned individual indices to all cafes. Then, he wrote down indices of cafes h... | 3 | n = int(input())
a = list(map(int, input().split()))
b = dict()
for i in range(len(a)):
b[a[i]] = i
print(a[min(list(b.values()))])
|
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 | host = list(input()) + list(input())
test = list(input())
host.sort()
test.sort()
print("YES" if host == test else "NO") |
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane.
You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem... | 3 | n=int(input())
stroka=input()
SF=0
FS=0
plusiki=0
while plusiki<n-1:
if stroka[plusiki]=='S' and stroka[plusiki+1]=='F':
SF=SF+1
if stroka[plusiki]=='F' and stroka[plusiki+1]=='S':
FS=FS+1
plusiki=plusiki+1
if SF>FS:
print('YES')
else:
print('NO') |
The bear decided to store some raspberry for the winter. He cunningly found out the price for a barrel of honey in kilos of raspberry for each of the following n days. According to the bear's data, on the i-th (1 β€ i β€ n) day, the price for one barrel of honey is going to is xi kilos of raspberry.
Unfortunately, the b... | 3 | n, c = map(int, input().split())
numbers = list(map(int, input().split()))
max = 0
for i in range(n - 1):
if numbers[i] - numbers[i + 1] > max:
max = numbers[i] - numbers[i + 1]
if max - c > 0:
print(max - c)
else:
print(0) |
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 3 | l=input()
l=l.split()
n=int(l[0])
m=int(l[1])
s=0
if(n==1 and m==1):
print(0)
else:
while min(n,m)>0:
if(n>=m):
n-=2
m+=1
else:
n+=1
m-=2
s+=1
print(s) |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 3 | first = input().split()
s = int(first[0])
n = int(first[1])
arr = []
for i in range(n):
app = input().split()
arr.append(app)
while(1):
counter = 0
i = 0
while i < len(arr):
k = int(arr[i][0])
l = int(arr[i][1])
if s > k:
s = s + l
del arr[i]
... |
Snuke has N sticks. The length of the i-th stick is l_i.
Snuke is making a snake toy by joining K of the sticks together.
The length of the toy is represented by the sum of the individual sticks that compose it. Find the maximum possible length of the toy.
Constraints
* 1 \leq K \leq N \leq 50
* 1 \leq l_i \leq 50
... | 3 | n,k = map(int,input().split())
x = sorted(list(map(int,input().split())))
print(sum(x[:-k-1:-1])) |
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that:
* Alice will get a (a > 0) candies;
* Betty will get b (b > 0) candies;
* each sister will get some integer number of candies;
* Alice will get a greater amount of candie... | 3 | #1335A
a = []
for i in range(int(input())):
a.append(int(input()))
for i in a:
print((i-1)//2) |
In Berland each high school student is characterized by academic performance β integer value between 1 and 5.
In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly n students. An academic performance of each student is known β integer value between 1 and 5.
Th... | 3 | input()
a=[0]*6
for i in[1,-1]:
for x in map(int,input().split()):a[x]+=i
s=sum(abs(x)for x in a)
print([s//4,-1][any(x%2 for x in a)])
|
Alice and Bob play ping-pong with simplified rules.
During the game, the player serving the ball commences a play. The server strikes the ball then the receiver makes a return by hitting the ball back. Thereafter, the server and receiver must alternately make a return until one of them doesn't make a return.
The one ... | 3 | #akash mandal: jalpaiguri government engineering college
import sys,math
def ii(): return int(input())
def mii(): return map(int,input().split())
def lmii(): return list(mii())
def dtob(n):
return bin(n).replace("0b", "")
def main():
for _ in range(ii()):
x,y=mii()
print(x-1,y)
i... |
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β to check his answers, he needs a program that among the given n numbers finds one that is di... | 3 | n = int(input())
lists = list(map(int, input().rstrip().split()))
for i in range(len(lists)):
for j in range(len(lists)):
if i != j:
if abs(lists[i]-lists[j])%2 == 1:
c = 0
else:
c = 1
break
if c == 0:
index = i + 1
... |
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 β€ si β€ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu... | 3 | n=int(input())
l=sorted(list(map(int,input().split())))
res1=l.count(4)
if res1>0:
l=l[0:l.index(4)]
res2=min(l.count(1),l.count(3))
if res2>0:
l=l[res2:len(l)-res2]
res3=l.count(3)
if res3>0:
l=l[0:l.index(3)]
res4=min(l.count(1)//2,l.count(2))
if res4>0:
l=l[res4*2:len(l)-res4]
#######
res5=l.count(2)... |
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets.
The store does not sell single clothing items β instead, it sells suits of two types:
* a suit of the first type consists of one tie and one jacket;
* a suit of the second type ... | 3 | a,b,c,d,e,f=[int(input()) for i in range(6)]
x,y=min(a,d),min(b,c,d)
print(max(e*x+f*min(b,c,d-x),f*y+e*min(a,d-y))) |
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city.
The city of Tomsk can be represented as point on the plane with ... | 3 | import math
n, s = input().split()
n, s = int(n), int(s)
m = {}
r1 = -1
for i in range(n):
x, y, k = input().split()
x, y, k = int(x), int(y), int(k)
m[i] = math.sqrt(x*x+y*y),x, y, k
lm = list(m.items())
lm.sort (key=lambda i: i[1])
for i in range(n):
try:
s += lm[i][1][3]
if s ... |
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessar... | 3 | b=input().split()
n=int(b[0])
k=int(b[1])
a=input().split()
ai=[]
for i in range(n):
ai.append(int(a[i]))
ai.sort()
print(ai[n-k])
|
You have array a1, a2, ..., an. Segment [l, r] (1 β€ l β€ r β€ n) is good if ai = ai - 1 + ai - 2, for all i (l + 2 β€ i β€ r).
Let's define len([l, r]) = r - l + 1, len([l, r]) is the length of the segment [l, r]. Segment [l1, r1], is longer than segment [l2, r2], if len([l1, r1]) > len([l2, r2]).
Your task is to find a ... | 3 | t = int(input())
s = 1
sp = [int(s) for s in input().split()]
max_sum = 2
sum = 2
if t == 1:
print(1)
else:
for i in range(2, len(sp)):
if(sp[i] == sp[i-1] + sp[i-2]):
sum += 1
else:
max_sum = max(sum, max_sum)
sum = 2
max_sum = max(sum, max_sum)
pri... |
Addition of Big Integers
Given two integers $A$ and $B$, compute the sum, $A + B$.
Input
Two integers $A$ and $B$ separated by a space character are given in a line.
Output
Print the sum in a line.
Constraints
* $-1 \times 10^{100000} \leq A, B \leq 10^{100000}$
Sample Input 1
5 8
Sample Output 1
13
S... | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# FileName: addition_of_big_integers
# CreatedDate: 2020-07-26 14:23:13 +0900
# LastModified: 2020-07-26 14:23:35 +0900
#
import os
import sys
# import numpy as np
# import pandas as pd
def main():
a, b = map(int, input().split())
print(a+b)
if __name__ ==... |
There are n districts in the town, the i-th district belongs to the a_i-th bandit gang. Initially, no districts are connected to each other.
You are the mayor of the city and want to build n-1 two-way roads to connect all districts (two districts can be connected directly or through other connected districts).
If two... | 3 | def solve():
n = int(input())
districts = [int(x) for x in input().split()]
dict = {}
for idx, district in enumerate(districts):
if district in dict.keys():
dict[district].append(idx+1)
else:
dict[district] = [idx+1]
# print(dict)
if len(dict) == 1:
... |
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ... | 3 | n=int(input())
if(n%5==0):
print(int(n/5))
else:
print(n//5+1) |
In Summer Informatics School, if a student doesn't behave well, teachers make a hole in his badge. And today one of the teachers caught a group of n students doing yet another trick.
Let's assume that all these students are numbered from 1 to n. The teacher came to student a and put a hole in his badge. The student, ... | 3 | from math import sqrt, floor
from collections import defaultdict
n = int(input())
p = list(map(int, input().split()))
dic = defaultdict(int)
for i in range(n):
dic[i + 1] = p[i]
ans = [0]
for i in range(1, n + 1):
dic_ = defaultdict(int)
dic_[i] += 1
tmp = dic_[i]
cur = i
while tmp != 2:
... |
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1.
You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0... | 3 | def main():
n, x, y = map(int, input().split())
num = input()[::-1]
ans = 0
for i in range(x):
if (i != y and num[i] == '1') or (i == y and num[i] == '0'):
ans += 1
print(ans)
if __name__ == "__main__":
main() |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | for _ in range(int(input())):
n = int(input())
arr = list(map(int, input().split()))
goodlen = 1
isgrowing = True
isdecr = False
it = n-1
while it > 0:
if isgrowing:
if arr[it] <= arr[it-1]:
it -= 1
goodlen += 1
else:
... |
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 | def password(arr,n):
if n==1:
return 1
elif len(set(arr))==1:
return n
else:
return 1
return password(arr,n-1)
for _ in range(int(input())):
n = int(input())
arr = [int(num) for num in input().split(' ')]
print(password(arr,n)) |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | def getAns(s):
return ''.join(map(lambda i: s[2 * i], range(len(s) // 2))) + s[-1]
def main():
t = int(input())
anss = [''] * t
for i in range(t):
s = input()
anss[i] = getAns(s)
for ans in anss:
print(ans)
main()
|
These days Arkady works as an air traffic controller at a large airport. He controls a runway which is usually used for landings only. Thus, he has a schedule of planes that are landing in the nearest future, each landing lasts 1 minute.
He was asked to insert one takeoff in the schedule. The takeoff takes 1 minute it... | 3 | n,s = map(int, input().split())
a,b = map(int, input().split())
if a*60+b>=s+1:
print(0,0)
else:
X = 0
for i in range(n-1):
c,d = map(int, input().split())
if c*60+d - (a*60+b) >= 2*s+2:
M = a*60+b+1+s
print(M//60,M%60)
X = 1
break
else... |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k β [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | t=int(input())
while t>0:
a,b=map(int,input().split())
ans=a-b
if ans==0:
print('0')
elif ans>0:
if ans%2!=0:
print('2')
else:
print('1')
else:
ans=abs(ans)
if ans%2!=0:
print('1')
else:
print('2')
t-... |
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 | T = int(input())
while(T>0):
a,b,c,r = map(int,input().split())
if a>b:
a,b = b,a
x = c-r
y = c+r
sum = 0
if b>=x and a<=x and b>=y:
sum += x-a
sum += b-y
elif b>=x and a<=x and y>=b:
sum += x-a
elif x<=a and y>=a and y<=b:
sum += b-y
e... |
You are given a string S of length N consisting of `A`, `C`, `G` and `T`. Answer the following Q queries:
* Query i (1 \leq i \leq Q): You will be given integers l_i and r_i (1 \leq l_i < r_i \leq N). Consider the substring of S starting at index l_i and ending at index r_i (both inclusive). In this string, how many t... | 3 | n,q=map(int,input().split())
s=input()
T=[0]*(n+1)
for i in range(n-1):
T[i+2]=T[i+1]+[0,1][s[i:i+2]=="AC"]
for _ in range(q):
l,r=map(int,input().split())
print(T[r]-T[l-1]-[0,1][s[l-2:l]=="AC"]) |
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted β the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one lo... | 3 | n, p = map(int, input().split())
A = list(map(int, input().split()))
highScore = 0
lSum = A[0]
rSum = sum(A[1::])
for i in range(len(A)-1):
score = (lSum % p) + (rSum % p)
if score > highScore:
highScore = score
lSum += A[i+1]
rSum -= A[i+1]
print(highScore) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | def th(f):
d = "abcdefghijklmnopqrstuvwxyz"
for i in d:
if i not in f.lower():
return("NO")
return("YES")
n = int(input())
f = input()
if n < 26:
print("NO")
else:
print(th(f))
|
Barney lives in NYC. NYC has infinite number of intersections numbered with positive integers starting from 1. There exists a bidirectional road between intersections i and 2i and another road between i and 2i + 1 for every positive integer i. You can clearly see that there exists a unique shortest path between any two... | 1 | def INC(v,u,w,fees):
path_to_root = {}
c = v
path_to_root[v] = None
while c > 1:
path_to_root[c/2] = c
c = c/2
c = u
while c > 1:
if c in path_to_root: break
e = (c/2,c)
if not e in fees:
fees[e] = 0
fees[e] += w
re = (c,c/2)
... |
Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out... | 3 | s='AHIMTUVWXYO'
s1=input()
for j,i in enumerate(s1):
if not i in s:
print('NO')
exit(0)
if s1[j]!=s1[len(s1)-j-1]:
print('NO')
exit(0)
print("YES") |
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho... | 3 | b = []
s = input()
b += s
ans = set()
for i in range(len(s) + 1):
for j in range(26):
b.insert(i, chr(ord('a') + j))
now = 0
y = 37
for h in range(len(b)):
now += (ord(b[h]) - ord('a') + 1) * y
y *= 37
del b[i]
ans.add(now)
print(len(ans)) |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay iΒ·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | k, n, w = map(int, input().split(' '))
toBorrow = (((2*k+(w-1)*k)/2)*w)-n
if toBorrow > 0:
print(int(toBorrow))
else:
print(0) |
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ... | 3 | for t in range(int(input())):
n = int(input())
a = []
ans = ""
for i in range (n):
a.append(list(map(int,input().split())))
a = sorted(a)
cur = [0,0]
boo = False
for j in range(n-1):
if(a[j][0] < a[j+1][0] and a[j][1] > a[j+1][1]):
boo = True
break... |
Valera loves his garden, where n fruit trees grow.
This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days,... | 3 | import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,0,1,0,-1,1... |
You have an array a of length n. For every positive integer x you are going to perform the following operation during the x-th second:
* Select some distinct indices i_{1}, i_{2}, β¦, i_{k} which are between 1 and n inclusive, and add 2^{x-1} to each corresponding position of a. Formally, a_{i_{j}} := a_{i_{j}} + 2^{... | 3 | import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
n = int(input())
A = list(map(int, input().split()))
if n == 1:
print(0)
continue
B = [0]*n
for i in range(n):
if i == 0:
B[i] = 0
max_ = A[i]
else:
i... |
<image>
Input
The first line of the input is a string (between 1 and 50 characters long, inclusive). Each character will be a letter of English alphabet, lowercase or uppercase.
The second line of the input is an integer between 0 and 26, inclusive.
Output
Output the required string.
Examples
Input
AprilFool
14... | 1 | d = raw_input()
b = int(raw_input())
r = ''
d = d.lower()
for i in xrange(len(d)):
a = d[i]
if ord(a) < b + 97:
r += a.upper()
else:
r += a.lower()
print r |
You are given two integers a and b, and q queries. The i-th query consists of two numbers l_i and r_i, and the answer to it is the number of integers x such that l_i β€ x β€ r_i, and ((x mod a) mod b) β ((x mod b) mod a). Calculate the answer for each query.
Recall that y mod z is the remainder of the division of y by z... | 3 | import math
for _ in range(int(input())):
a,b,q=map(int,input().split());lcm=a*b//math.gcd(a,b);t=max(a,b)
for i in range(q):
l,r=map(int,input().split());Ans=0
Ans+=(r-l+1);n=(l-1)//lcm;m=r//lcm;tem=min(r-m*lcm+1,t);Ans-=(m-n-1)*t;Ans-=tem;Ans-=max(t-(l-lcm*n),0);print(Ans,end=' ')
print()
... |
M-kun is a competitor in AtCoder, whose highest rating is X.
In this site, a competitor is given a kyu (class) according to his/her highest rating. For ratings from 400 through 1999, the following kyus are given:
* From 400 through 599: 8-kyu
* From 600 through 799: 7-kyu
* From 800 through 999: 6-kyu
* From 1000 thro... | 3 | X = int(input())
t = X // 200
print(10 - t) |
There are n piranhas with sizes a_1, a_2, β¦, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium.
Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the... | 3 | t = int(input())
for i in range(t):
n = int(input())
A = list(map(int,input().split()))
m = 0
k = 0
d = 0
for j in range(n):
if A[j] > m:
k = 1
m = A[j]
if j > 0 and A[j - 1] != m or j < n - 1 and A[j + 1] != m:
d = j + 1
elif A... |
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'.
In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov... | 3 | for _ in range(int(input())):
n = int(input())
s = input()
while '()' in s:
s = s.replace('()',"")
print(s.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 | n=int(input())
for i in range(n):
t=1
s=input()
for j in range(len(s)):
if s[j].isdigit()==True:
break
for k in range(j,len(s)):
if s[k].isdigit()==False:
t=0
break
if t==0:
f=s.index('C')
row=int(s[j:f])
col=int(s[f+1:])
val=""
while col!=0:
r=col%26
col=col//26
if r==0:
r=26
... |
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'... | 1 | str=raw_input()
s,n=[int(i) for i in str.split()]
list=[]
for i in range(n):
m=[]
a=raw_input()
m=[int(i) for i in a.split()]
list.append(m)
list.sort()
for i in range(n):
if list[i][0]>=s:
print 'NO'
break
else:
s=s+list[i][1]
if i<n-1:
continue
... |
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to... | 3 | # METO Bot 0.9.9
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as ... | 1 | class team:
def __init__ (self,a,b):
self.home = a
self.away = b
def main():
n = input()
T = []
for i in range (0,n):
a = raw_input()
a = a.split()
T.append(team(int(a[0]),int(a[1])))
ans = 0
for i in range (0,n-1):
for j in range... |
A string b is a subsequence of a string a if b can be obtained from a by deletion of several (possibly, zero or all) characters. For example, "xy" is a subsequence of "xzyw" and "xy", but not "yx".
You are given a string a. Your task is to reorder the characters of a so that "trygub" is not a subsequence of the result... | 3 | for _ in range(int(input())):
n=int(input())
str=input()
s=""
p=""
for i in str:
if i=="r":
s=s+i
else:
p=p+i
print(s+p)
|
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor).
What is the minimum number of ope... | 3 | import math
import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
size = inp()
arr = inlt()
i = 0
count = size - arr.count(1)
arr1 = ... |
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | 3 | main_word = input()
chek_word = input()
rev_main_word = main_word[::-1]
if rev_main_word == chek_word:
print('YES')
else:
print('NO') |
Luba needs your help again! Luba has n TV sets. She knows that i-th TV set will be working from moment of time li till moment ri, inclusive.
Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at leas... | 3 | n = int(input())
lis = []
for i in range(n):
a, b = map(int, input().split())
lis.append([a, b, i+1])
lis.sort()
i = 1
ans = -1
while i<n:
if lis[i][1]<=lis[i-1][1]:
ans = lis[i][2]
print(ans)
exit(0)
elif( lis[i][0] <= lis[i-1][0] and lis[i][1] >= lis[i-1][1]):
ans = lis[i-1][2]
print(ans)
exit(0)
lis... |
In this problem you will meet the simplified model of game King of Thieves.
In a new ZeptoLab game called "King of Thieves" your aim is to reach a chest with gold by controlling your character, avoiding traps and obstacles on your way.
<image>
An interesting feature of the game is that you can design your own levels... | 1 | import sys
n = int(raw_input())
s = raw_input()
def can(i, k):
def has(i):
return i < n and s[i] == '*'
return has(i) and has(i + k) and has(i + 2 * k) and has(i + 3 * k) and has(i + 4 * k)
for i in range(n):
for k in range(1, n):
if can(i, k):
print "yes"
sy... |
Little Elephant loves magic squares very much.
A magic square is a 3 Γ 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15... | 3 | a = []
for i in range(3):
a.append([int(i) for i in input().split()])
sum_1 = sum(a[0])
sum_2 = sum(a[1])
sum_3 = sum(a[2])
z = (sum_1 + sum_2 - sum_3) // 2
y = sum_1 - z
x = sum_2 - z
a[0][0] = x
a[1][1] = y
a[2][2] = z
for i in range(3):
for j in range(3):
print(a[i][j],end=" ")
print() |
Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l β€ x β€ r, and <image> is maximum possible. If there are multiple such numbers find the sma... | 3 | import sys
input=sys.stdin.readline
n=int(input())
for _ in range(n):
l,r=map(int,input().split())
while (l|(l+1))<=r:
l|=l+1
print(l) |
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100.
The shop sells N kinds of cakes.
Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i.
Th... | 3 | n,m = map(int,input().split())
xyz = [list(map(int,input().split())) for _ in range(n)]
res = 0
for a in (1,-1):
for b in (1,-1):
for c in (1,-1):
l = []
for (x,y,z) in xyz:
l.append(x*a+y*b+z*c)
l = sorted(l,reverse=True)
res = max(res, sum(l[... |
Alice and Bob are decorating a Christmas Tree.
Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments.
In Bob's opinion, a Christmas Tree will be beautiful if:
* the number of blue ornaments used is greater b... | 3 | y, b, r = map(int,input().split())
d = y
e = b - 1
f = r - 2
t = [d,e,f]
print(3*min(t)+3) |
Koto Municipal Subway
Koto Municipal Subway
Koto City is a famous city whose roads are in a grid pattern, as shown in the figure below. The roads extending from north to south and the roads extending from east to west are lined up at intervals of 1 km each. Let Koto station at the southwestern intersection of Koto ci... | 3 | from math import sqrt
while True:
d, e = map(int, input().split())
if d == e == 0:
break
mn = 10000
for i in range(d // 2 + 1):
mn = min(mn, abs(sqrt(i ** 2 + (d - i) ** 2) - e))
print(mn) |
Vasya lives in a strange world. The year has n months and the i-th month has ai days. Vasya got a New Year present β the clock that shows not only the time, but also the date.
The clock's face can display any number from 1 to d. It is guaranteed that ai β€ d for all i from 1 to n. The clock does not keep information ab... | 3 | D = int(input())
N = int(input())
M = list(map(int, input().split()))
ans = 0
for m in M[:-1]:
ans += D - m
print(ans) |
Sometimes one has to spell email addresses over the phone. Then one usually pronounces a dot as dot, an at sign as at. As a result, we get something like vasyaatgmaildotcom. Your task is to transform it into a proper email address (vasya@gmail.com).
It is known that a proper email address contains only such symbols a... | 1 | s = raw_input()
if(s.find("at")<>0):
s = s.replace("at","@",1)
else:
s = s.replace("at","@",2)
s = s.replace("@","at",1)
dotpos=-1
if(s.find("dot")==0):
dotpos=4
elif(s.find("dot")==-1):
dotpos=0
while(dotpos<>0):
if(s.find("dot",dotpos)<>0 and s.find("dot",dotpos)<>len(s)-3):
s = s.re... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | u=input()
l=list(map(int,u.split(' ')))
r=0
n=l[0]
k=l[1]
if n//10==0:
print(n-k)
elif n//10>0:
while r<k:
if n%10==0:
n=n/10
elif n%10!=0:
n=n-1
r=r+1
print(int(n)) |
Little Vasya has received a young builderβs kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ... | 1 | n = int(raw_input())
s = raw_input().split()
a = [0]
a = a * 10000
mh = 0
kol = 0
for i in range(0,n):
if a[int(s[i])] == 0:
kol += 1
a[int(s[i])] += 1
if mh < a[int(s[i])]:
mh = a[int(s[i])]
print mh, kol |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 1 | a=input()
if(a<=2):
print "NO"
elif(a%2==0):
print "YES"
else:
print "NO" |
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ... | 3 | def gcd(x,y):
if x>y:
ma=x
mi=y
else:
ma=y
mi=x
if mi!=0:
return gcd(mi,ma%mi)
else:
return ma
a,b,n=map(int,input().split())
i=0
x=a
while n>=gcd(x,n):
if i%2==0:
x=a
n=n-gcd(x,n)
i+=1
else:
x=b
n=n-gcd(x,n)... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | n=int(input())
s=[]
group=0
for x in range(n):
s+=[input()]
#print(s)
for x in range(n-1):
if(s[x][1]==s[x+1][0]):
group+=1
print(group+1)
|
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 | n = input()
m = n.split("+")
s = sorted(m)
print("+".join(map(str,s))) |
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ... | 3 | n,k=map(int,input().split())
md=10**9+7
n1=n-k+1
n2=k-1
com1=[]
com2=[]
c1=1
c2=1
for i in range(k+1):
com1+=[c1]
com2+=[c2]
c1=c1*(n1-i)//(i+1)
c2 = c2 * (n2 - i) // (i + 1)
for i in range(1,k+1):
ans=com1[i]*com2[i-1]%md
print(ans) |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a=int(input())
if(a%2!=0):
print("NO")
elif(a==2):
print("NO")
else:
if((a/2)%2!=0):
c=a/2
d=c
c=c-1
d=d+1
if(c+d==a):
print("YES")
else:
c=a/2
d=c
c=c-2
d=d+2
if(c+d==a):
print("YES") |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 β€ i β€ n and do one of the following operations:
* eat exactly... | 3 | def fixequalgift(n,a,b):
mina , minb = min(a) , min(b) ; move = 0
for i in range(n):
if a[i]>mina:
if b[i]>minb:
if a[i]-mina > b[i]-minb :
move += a[i]-mina
elif a[i]-mina < b[i]-minb:
move += b[i]-minb
... |
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 | input()
s=input()
a,d=0,0
for i in range(len(s)):
if s[i]=='A':
a+=1
else:
d+=1
if a>d:
print("Anton")
elif d>a:
print("Danik")
else:
print("Friendship") |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | n = int(input())
s = input()
dict = {}
for i in range(n-1):
temp = s[i]+s[i+1]
if temp not in dict:
dict[temp] = 1
else:
dict[temp] += 1
maximum = max(dict, key=dict.get)
print(maximum) |
You are given positive integers A and B.
If A is a divisor of B, print A + B; otherwise, print B - A.
Constraints
* All values in input are integers.
* 1 \leq A \leq B \leq 20
Input
Input is given from Standard Input in the following format:
A B
Output
If A is a divisor of B, print A + B; otherwise, print B -... | 3 | a,b=map(int,input().split());print(b + a*(b%a==0) - a*(b%a>0)) |
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there.
The content special agent has got an important task: to get th... | 1 | def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
s = raw_input().strip()
cnt = dict()
for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ?0123456789':
cnt[c] = 0
for c in s:
cnt[c] += 1
t = 0
for c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if cnt[c] > 0:
t += 1
c = s[0]
res = 1
if c in 'ABCDEFGHIJKLMNOPQR... |
Little Petya likes numbers a lot. He found that number 123 in base 16 consists of two digits: the first is 7 and the second is 11. So the sum of digits of 123 in base 16 is equal to 18.
Now he wonders what is an average value of sum of digits of the number A written in all bases from 2 to A - 1.
Note that all computa... | 1 | # To change this template, choose Tools | Templates
# and open the template in the editor.
__author__="yaroslav"
__date__ ="$02.08.2011 18:00:13$"
def isch(n,k):
res = 0
while n/k!=0:
res += n%k
n /= k
res += n%k
return res
def nod(a,b):
while a!=0 and b!=0:
if a>=b:
... |
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars.
There are... | 3 | from bisect import bisect
from collections import defaultdict
# l = list(map(int,input().split()))
# map(int,input().split()))
from math import gcd,sqrt,ceil,inf
from collections import Counter
import sys
sys.setrecursionlimit(1000000)
from bisect import bisect
from collections import defaultdict
# l = list(map(int,inp... |
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace an... | 1 | n=input();print len(raw_input().replace("RU","D").replace("UDR","DD").replace("UR","D"))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.