problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya recently learned to determine whether a string of lowercase Latin letters is lucky. For each i...
3
import string n=int(input()) i=1 st="" while i<(n+1): st+="a" i=i+1 while i<(n+1): st+="b" i=i+1 while i<(n+1): st+="c" i=i+1 while i<(n+1): st+="d" break break break i=i+1 print(st)
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
inp = input().split() n = int(inp[0]) m = int(inp[1]) print((n * m) // 2)
A game is played on a strip consisting of N cells consecutively numbered from 1 to N. Alice has her token on cell A. Borys has his token on a different cell B. Players take turns, Alice moves first. The moving player must shift his or her token from its current cell X to the neighboring cell on the left, cell X-1, or...
3
n,a,b = map(int, input().split()) if (b-a-1)%2!=0:print("Alice") else: print("Borys")
The Little Elephant likes permutations. This time he has a permutation A[1], A[2], ..., A[N] of numbers 1, 2, ..., N. He calls a permutation A good, if the number of its inversions is equal to the number of its local inversions. The number of inversions is equal to the number of pairs of integers (i; j) such that 1 ≀...
1
## CodeChef ## Little Elephant and Permutations ## 2016.03.26 def inversion(n,s): tot = 0 for i in xrange(n-1): for j in xrange(i+1,n): if s[i] > s[j]: tot += 1 return tot def localInv(n,s): tot = 0 for i in xrange(n-1): if s[i]>s[i+1]: tot +...
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
3
import math def solve(x, y, k): needed = k*y + k trades = (needed-1) // (x-1) if (needed-1) % (x-1): trades+=1 return trades + k for case1 in range(int(input())): x, y, k = map(int, input().split()) ans1 = solve(x, y, k) print(ans1)
Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected. The pasture is a rectangle consisting of R Γ— C cells. Each cell is either empty, contains a sheep, a wolf or a dog...
3
r, c = map(int, input().split()) pasture = [list(input()) for i in range(r)] impossible = False def fill(tu): global impossible x, y = tu if any((x<0, y<0, x>=r, y>=c)): return if pasture[x][y] == 'S': impossible = True if pasture[x][y] == '.': pasture[x][y] = 'D' for i i...
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
t=int(input()) for t in range(t): n=int(input()) sum1=0 sum2=0 for i in range(0,int(n/2)-1): sum1+=2**(i+1) for i in range(int(n/2)-1,n-1): sum2+=2**(i+1) print(abs(sum2-sum1-2**n))
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i...
3
from collections import Counter n = input() n = int(n) beauty = list(map(int,input().split())) beauty.sort() hello = beauty[-1] - beauty[0] ans = 0 hi = Counter(beauty) if hi[beauty[0]] == n: ans = n*(n-1) ans = int(ans/2) else: ans = (hi[beauty[0]]*hi[beauty[-1]]) print(hello,ans)
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly. In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ...
3
import sys input = sys.stdin.readline """ """ from math import floor, ceil q = int(input()) for _ in range(q): n, k = map(int, input().split()) arr = list(map(int, input().split())) mn = min(arr) mx = max(arr) if (mx - (mn+k)) <= k: print(mn+k) else: print(-1)
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem: There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}. Anton can perform the following sequence of operations any number of ti...
3
t = int(input()) al = [] for i in range(t): n = int(input()) a = list(map(int,input().split())) b = list(map(int,input().split())) s = 0 f = 0 z = 0 for j in range(n): if a[j] == 0: z += 1 elif a[j] == 1: s += 1 else: f += 1 ans...
There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid. When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1). In how many ways can the knight reach the square (X, Y)? Find the number of ways modulo 10^9 + 7. Constraints * 1 \leq X \leq 10^6 * 1 \l...
3
x,y = map(int,input().split()) n = 0 mod = 10**9+7 ans = 0 if not (x+y)%3: n = (x+y)//3 x-=n y-=n if not x<0 or y<0: ans = 1 for i in range(x): ans = ans*(n-i)*pow(i+1,mod-2,mod)%mod print(ans)
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
3
for t in range(int(input())): n = int(input()) if n == 1: print('-1') else: s = '4' + ('3' * (n - 1)) print(s)
Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i Γ— j. The rows and columns are numbered starting from 1. You are given a positive integer x. Your task is to count the number of cells in a table that contain number x. Input T...
3
n,x=map(int,input().split()) s=0 for i in range(1,n+1): if x%i==0 and x/i<n+1: s+=1 print(s)
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
from collections import defaultdict as dd import sys input=sys.stdin.readline t=int(input()) while t: #n=int(input()) n,m=map(int,input().split()) #l=list(map(int,input().split())) ans=(n//m)*m rem=n%m if(rem<=m//2): ans+=rem else: ans+=m//2 print(ans) t-=1
Soon a school Olympiad in Informatics will be held in Berland, n schoolchildren will participate there. At a meeting of the jury of the Olympiad it was decided that each of the n participants, depending on the results, will get a diploma of the first, second or third degree. Thus, each student will receive exactly one...
3
n = int(input()) a,b = map(int, input().split(' ')) c,d = map(int, input().split(' ')) e,f = map(int, input().split(' ')) while a + c + e < n and a < b: a += 1 while a + c + e < n and c < d: c += 1 m = n - a - c print (a, c, m)
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ...
3
x=int(input()) sm=[] for i in range(x): sm.append(input()) print("NO") for i in range(1,x): c=0 for l in range(i): if sm[i]==sm[l]: c+=1 if c>0: print("YES") else: print("NO")
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
3
n=int(input()) print(sorted([input() for _ in range(n)])[n//2])
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()) amount=k*((w*(w+1))//2) if amount>n: print(amount-n) else: print(0)
AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to sched...
3
import random D = int(input()) ans = [random.randint(1,26) for i in range(D)] print('\n'.join(map(str, ans)))
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
1
def mdc (a,b): if (b==0): resp=a else: resp= mdc(b,a%b) return resp a=raw_input().split() for i in range(0,2): a[i]=int(a[i]) a.sort() num=(6-a[1]+1) m=mdc(num,6) print str(num/m)+"/"+str(6/m)
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≀ m ≀ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
len = int(input()) s = input() n = 0 while (n*(n+1)//2)<len-1: print (s[n*(n+1)//2], end='') n+=1 print(s[0] if n==0 else "")
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task. Two matrices A and B are given, each of them has size n Γ— m. Nastya can perform the following operation to matrix A unlimited number of times: * take any square square submatrix of A and...
1
h, w = [int(x) for x in raw_input().split()] A = [[int(x) for x in raw_input().split()] for i in xrange(h)] B = [[int(x) for x in raw_input().split()] for i in xrange(h)] # A[h][w] for j in xrange(h): x = 0 y = j Ad, Bd = {}, {} while y >= 0 and x < w: if A[y][x] in Ad: Ad[A[y][x]]...
Devu is a renowned classical singer. He is invited to many big functions/festivals. Recently he was invited to "All World Classical Singing Festival". Other than Devu, comedian Churu was also invited. Devu has provided organizers a list of the songs and required time for singing them. He will sing n songs, ith song wi...
3
n,d=map(int,input().split()) d-=sum(map(int,input().split())) print([d//5,-1][d+10<10*n])
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
if(len(set(input()))%2==0): print("CHAT WITH HER!") else: print("IGNORE HIM!")
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
1
KN=int(input()) Alumnos = [int(x) for x in raw_input().split() ] N1=0 N2=0 N3=0 for k in range(KN): if(Alumnos[k]==1): N1=N1+1 if(Alumnos[k]==2): N2=N2+1 if(Alumnos[k]==3): N3=N3+1 A=[] B=[] C=[] Minimo = min(N1,N2,N3) print(Minimo) for i in range (KN): if(Alumnos[i]==1): ...
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams. The strength of a team is defined as the second largest strength among its members. For ...
3
n = int(input()) print(sum(sorted([int(i) for i in input().split()], reverse=True)[1:n*2:2]))
Chef Monocarp has just put n dishes into an oven. He knows that the i-th dish has its optimal cooking time equal to t_i minutes. At any positive integer minute T Monocarp can put no more than one dish out of the oven. If the i-th dish is put out at some minute T, then its unpleasant value is |T - t_i| β€” the absolute d...
3
from math import inf, log2 class SegmentTree: def __init__(self, array, func=max): self.n = len(array) self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1 self.func = func self.default = 0 if self.func != min else inf self.data = [self.default] * (2 * self.size) ...
Alice likes word "nineteen" very much. She has a string s and wants the string to contain as many such words as possible. For that reason she can rearrange the letters of the string. For example, if she has string "xiineteenppnnnewtnee", she can get string "xnineteenppnineteenw", containing (the occurrences marked) tw...
3
c = input().count print(max(0, min((c("n")-1)//2, c("i"), c("e")//3, c("t")))) #From SMMaster
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements? Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the to...
3
h,w = map(int,input().split()) print((int(h/2+0.5)*w-(h%2)*int(w/2))if(h-1)and(w-1)else 1)
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
a,b=map(int,input().split()) l=list(map(int,input().split())) count=0 q=l[b-1] for i in range(a): if(l[i]>=q and l[i]>0): count+=1 print(count)
You are given an array of integers a_1,a_2,…,a_n. Find the maximum possible value of a_ia_ja_ka_la_t among all five indices (i, j, k, l, t) (i<j<k<l<t). Input The input consists of multiple test cases. The first line contains an integer t (1≀ t≀ 2 β‹… 10^4) β€” the number of test cases. The description of the test cases ...
3
cases=int(input()) for _ in range(cases): n=int(input()) c=list(map(int,input().split())) c.sort() m1=c[0]*c[1]*c[2]*c[3]*c[4] m2=c[0]*c[1]*c[2]*c[3]*c[n-1] m3=c[0]*c[1]*c[2]*c[n-2]*c[n-1] m4=c[0]*c[1]*c[n-3]*c[n-2]*c[n-1] m5=c[0]*c[n-4]*c[n-3]*c[n-2]*c[n-1] m6=c[n-5]*c[n-4]*c[n-3]*c[n-2]*c[n-1] print(max(m...
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
a=input() x=str(a.count('4')+a.count('7')) f=0 num=['0','1','2','3','5','6','8','9'] for i in x: if i in num: print("NO") f=1 break if f==0: print("YES")
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
1
import sys def solve(): n = int(sys.stdin.readline()) values = map(int,sys.stdin.readline().split()) pos = [values.index(1),values.index(n)] pos.sort() if pos==[0,n-1]: best = n-1 else: best = max(pos[1], n-pos[0]-1) print best solve()
For given three points p1, p2, p, find the reflection point x of p onto p1p2. <image> Constraints * 1 ≀ q ≀ 1000 * -10000 ≀ xi, yi ≀ 10000 * p1 and p2 are not identical. Input xp1 yp1 xp2 yp2 q xp0 yp0 xp1 yp1 ... xpqβˆ’1 ypqβˆ’1 In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv...
3
import math class Point: def __init__(self,x,y): self.x = x self.y = y def __add__(self,p): return Point(self.x+p.x,self.y+p.y) def __sub__(self,p): return Point(self.x-p.x,self.y-p.y) def __mul__(self,p): return Point(self.x*p,self.y*p) def Dot(a,b): return a.x*b.x + a.y*b.y def Cross(a,b): return a.x...
One day, as Sherlock Holmes was tracking down one very important criminal, he found a wonderful painting on the wall. This wall could be represented as a plane. The painting had several concentric circles that divided the wall into several parts. Some parts were painted red and all the other were painted blue. Besides,...
3
# Description of the problem can be found at http://codeforces.com/problemset/problem/157/B import math n = int(input()) l_s = list(map(int, input().split())) l_s.sort(reverse = True) t = 0 for index in range(n): t += (-1 if index % 2 == 1 else 1) * l_s[index] ** 2 print(t * math.pi)
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
import sys string = input() string = string[:1].upper() + string[1:] print(string)
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0. On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2...
3
def main(): t = int(input()) for _ in range(t): n = int(input()) cands = set(); prev_cands = set(); good = True for i in range(n): row = input() if not good: continue for c in range(n - 1): if row[c] == "1": ...
You are given a system of pipes. It consists of two rows, each row consists of n pipes. The top left pipe has the coordinates (1, 1) and the bottom right β€” (2, n). There are six types of pipes: two types of straight pipes and four types of curved pipes. Here are the examples of all six types: <image> Types of pipes ...
3
tc = int(input()) def check(p,n): if 0<=p[0]<=1 and 0<=p[1]<=n: return True else: return False outs = [] for i in range(tc): n = int(input()) strs = [] strs.append(input()) strs.append(input()) p = [0,0] flag = 0 while True: if (strs[p[0]][p[1]] in ['1','2']...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
1
import sys for line in sys.stdin: N = int(line) if N % 2 == 0 and N/2 > 1: print "YES" else: print "NO"
Takahashi has K 500-yen coins. (Yen is the currency of Japan.) If these coins add up to X yen or more, print `Yes`; otherwise, print `No`. Constraints * 1 \leq K \leq 100 * 1 \leq X \leq 10^5 Input Input is given from Standard Input in the following format: K X Output If the coins add up to X yen or more, prin...
3
a,x = map(int,input().split()) print('Yes' if a * 500 >= x else 'No')
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that aβ‹… c=b. For n β‰₯ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
def f(a): for i in range(2, a // 2 + 2): if (a % i) == 0: return i return a def solution(): n, k = list(map(lambda x: int(x), input().split())) r = f(n) if r != 2: print(n + r + 2 * (k - 1)) else: print(n + r * k) if __name__ == "__main__": t = int(inp...
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
a = int(input()) mas = (input()) mas = mas.split() if (int(mas[0]) % 2 == 0 and int(mas[1]) % 2 == 0) or (int(mas[1]) % 2 == 0 and int(mas[2]) % 2 == 0) or (int(mas[0]) % 2 == 0 and int(mas[2]) % 2 == 0): for i in range(a): if(int(mas[i]) % 2 == 1): print(i+1) else: for i in range(a): ...
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
s = input().split('+') s.sort() res = '+'.join(s) print(res)
You are given a set of 2n+1 integer points on a Cartesian plane. Points are numbered from 0 to 2n inclusive. Let P_i be the i-th point. The x-coordinate of the point P_i equals i. The y-coordinate of the point P_i equals zero (initially). Thus, initially P_i=(i,0). The given points are vertices of a plot of a piecewis...
3
# cook your dish here import math n1,k1=(input().split(' ')) n=int(n1) k=int(k1) s=k//n m=k%n if m==0: print(s) else: print((s+1))
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
3
[a,b] = input().split(' ') a = int(a) b = int(b) cnt = 0 s = [int(k) for k in input().split(' ')] cnt = 2*sum([k>b for k in s]) + sum(k <= b for k in s) print(cnt)
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
3
import sys def read(): return sys.stdin.readline() n,k = map(int,read().split()) a = list(map(int,(read().split()))) sum=0 for i in range(n-1): if a[i]+a[i+1]<k: sum+=(k-a[i]-a[i+1]) a[i+1] = k-a[i] print(str(sum)+'\n'+' '.join(map(str,a)))
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
3
k=int(input()) n=input() counts=[None]*10 offset=ord('0') sum=0 for i in range(10): counts[i]=n.count(chr(i+offset)) sum+=i*counts[i] if sum<k: count=0 for i in range(9): for j in range(counts[i]): count+=1 sum+=10+~i if sum>=k: print(count) exit() else: print(0)
Vanya got an important task β€” he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels the bo...
3
n = int(input().strip()) l = len(str(n)) x = 10**(l-1) s = (n-x+1)*l for i in range(l-1): s += 9*(10**i)*(i+1) print(s)
In the evening, after the contest Ilya was bored, and he really felt like maximizing. He remembered that he had a set of n sticks and an instrument. Each stick is characterized by its length li. Ilya decided to make a rectangle from the sticks. And due to his whim, he decided to make rectangles in such a way that maxi...
3
_ = int(input()) as_ = list(sorted(map(int, input().split()))) def get_pair(): while len(as_) >= 2: s0 = as_.pop() s1 = as_.pop() if s0-1 == s1 or s0 == s1: return s1 as_.append(s1) return None ans = 0 tb = get_pair() lr = get_pair() while not (tb is None or lr is N...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) arr = [] for i in range(n): arr.append(str(input())) for i in arr: if len(i) <= 10: print(i) else: print(str(i[0]+str(len(i)-2)+i[-1]))
Little Artem got n stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem...
3
n=int(input()) if(n==1 or n==2): print(1) elif(n%3==0): print(2*(n//3)) elif(n%3==1): print(2*((n-1)//3)+1) else: print(2*(n+1)//3-1)
Write a program which reads a $ n \times m$ matrix $A$ and a $m \times 1$ vector $b$, and prints their product $Ab$. A column vector with m elements is represented by the following equation. \\[ b = \left( \begin{array}{c} b_1 \\\ b_2 \\\ : \\\ b_m \\\ \end{array} \right) \\] A $n \times m$ matrix with $m$ column ve...
3
n,m = map(int,input().split()) A = [list(map(int,input().split())) for _ in range(n)] b = [int(input()) for _ in range(m)] for i in range(n): ci = 0 for j in range(m): ci += A[i][j]*b[j] print(ci)
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
a,b,c,d = list(map(int,input().split())) ma = max(a,b,c,d) ans = [] for i in [a,b,c,d]: if i!=ma: ans.append(abs(i-ma)) print(*ans)
Sereja loves number sequences very much. That's why he decided to make himself a new one following a certain algorithm. Sereja takes a blank piece of paper. Then he starts writing out the sequence in m stages. Each time he either adds a new number to the end of the sequence or takes l first elements of the current seq...
3
n=int(input()) a=[] for i in range(n): a.append(list(map(int,input().split()))) m=int(input()) b=list(map(lambda x:int(x)-1,input().split())) c=[] now=0 k=0 ans=[] for i in range(n): t=a[i] last=now if t[0]==1: now+=1 if len(c)<100000: c.append(t[1]) if k<m and b[k]==now-1: ...
You are given two integers n and m (m < n). Consider a convex regular polygon of n vertices. Recall that a regular polygon is a polygon that is equiangular (all angles are equal in measure) and equilateral (all sides have the same length). <image> Examples of convex regular polygons Your task is to say if it is poss...
3
k = int(input()) for i in range(k): l, m = map(int,input().split()) if l%m==0: print('YES') else: print('NO')
Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so. Constraints * 1 ≀ length of the side ≀ 1,000 * N ≀ 1,000 Input Input consists of several data sets. In the first line, the number of data set, N is...
3
n = int(input()) for i in range(n): a,b,c=map(int,input().split()) l=[a,b,c] list.sort(l) if l[0]**2+l[1]**2==l[2]**2: print("YES") else: print("NO")
One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si β€” lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ...
3
n, k = map(int, input().split()) s = input() d = dict() for i in s: d[i] = d.get(i, 0) + 1 if d[i] > k: print('NO') exit(0) print('YES')
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n = int(input()) values = list(reversed(sorted([int(x) for x in input().split()]))) total = sum(values) coins = 1 for i in range(0, n): temp = 0 for j in range(0, coins): temp += values[j] if temp > (total - temp): break else: coins += 1 print(coins)
Berland crossword is a puzzle that is solved on a square grid with n rows and n columns. Initially all the cells are white. To solve the puzzle one has to color some cells on the border of the grid black in such a way that: * exactly U cells in the top row are black; * exactly R cells in the rightmost column ar...
1
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def main(): t = int(input()) for _ in range(t):...
Vasya has n days of vacations! So he decided to improve his IT skills and do sport. Vasya knows the following information about each of this n days: whether that gym opened and whether a contest was carried out in the Internet on that day. For the i-th day there are four options: 1. on this day the gym is closed and...
3
n = int(input()) k = list(map(int, input().split(" "))) ans = 0 last = "n" for i in k: if i == 0: now = "n" elif i == 1 and last != "p": now = "p" elif i == 1: now = "n" elif i == 2 and last != "s": now = "s" elif i == 2: now = "n" elif last == "s": ...
You are playing a new computer game in which you have to fight monsters. In a dungeon you are trying to clear, you met three monsters; the first of them has a health points, the second has b health points, and the third has c. To kill the monsters, you can use a cannon that, when fired, deals 1 damage to the selected ...
3
tests = int(input()) while(tests > 0): a, b, c = list(map(int, input().split())) m = min(a, b, c) # maximum can be m multiple of 7 ans = "NO" if (a + b + c) % 9 == 0: # mulitple of 9 d = (a + b + c)/9 if (m >= d): ans = "YES" print(ans) tests -=1...
Ohana Matsumae is trying to clean a room, which is divided up into an n by n grid of squares. Each square is initially either clean or dirty. Ohana can sweep her broom over columns of the grid. Her broom is very strange: if she sweeps over a clean square, it will become dirty, and if she sweeps over a dirty square, it ...
1
import collections n = input() a = [] for _ in xrange(n): a1 = '0' a2 = raw_input() for i in xrange(len(a2)): if a2[i]=='0': a1+='+'+str(i) a.append(a1) a = collections.Counter(a) print max(a.values())
A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}. How many times will the ball make a bounce where the coordinate is at most X? Constraints * 1 \leq N \leq 100 * 1 \leq L_i ...
3
n, x = map(int, input().split()) d = 0 b = 1 for l in map(int, input().split()): d += l if d <= x: b += 1 else: break print(b)
Write a program that reads the coordinates of the vertices of a convex n-sided polygon (a polygon whose internal angles are less than 180 degrees, that is, a polygon that is not dented) and outputs its area. The vertices are named Vertex 1, Vertex 2, Vertex 3, ... Vertex n according to the order of edge connections. H...
3
import math import cmath def cross_product(a,b): return (a.conjugate()*b).imag L = [] try: while True: x,y = map(float,input().split(',')) L.append(complex(x,y)) except EOFError: pass N = len(L) S = 0 for i in range(1,N-1): a,b,c = L[0],L[i],L[i+1] S += abs(cross_product(b-a,c-a))/2 ...
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold: 1. ai β‰₯ ai - 1 for all even i, 2. ai ≀ ai - 1 for all odd i > 1. For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted. Can you make the...
1
n = int(raw_input()) s = raw_input().split() l = [] for i in range(n): l.append(int(s[i])) #print l for i in range(n): for j in range(n - 1): if l[j] > l[j + 1]: k = l[j] l[j] = l[j + 1] l[j + 1] = k for i in range(n - 1): if i % 2 == 1: k = l[i] ...
A number is ternary if it contains only digits 0, 1 and 2. For example, the following numbers are ternary: 1022, 11, 21, 2002. You are given a long ternary number x. The first (leftmost) digit of x is guaranteed to be 2, the other digits of x can be 0, 1 or 2. Let's define the ternary XOR operation βŠ™ of two ternary n...
1
t = input() for i in range(t): n = input() a = raw_input() b="" c="" one = False for j in range(n): if one: b = b + a[j] c = c + '0' else: if(a[j]=='0'): b = b+'0' c = c+'0' elif(a[j]=='1'): ...
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) list0 = [0]*n x = 0 for i in range(n): list0[i] = input() if '+' in list(str(list0[i])): x += 1 if '-' in list(str(list0[i])): x -= 1 print(x)
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
3
N=int(input()) A=list(map(int,input().split())) B=[0]*N for i in range(N-1): B[A[i]-1]+=1 for j in B: print(j)
Amr loves Geometry. One day he came up with a very interesting problem. Amr has a circle of radius r and center in point (x, y). He wants the circle center to be in new position (x', y'). In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle ...
1
#!/usr/bin/env python import math r, x,y, x_linha, y_linha = [int(x) for x in raw_input().split()] # print dist(x,y, x_linha, y_linha),2*r print int(math.ceil(math.sqrt((x_linha-x)**2 + (y_linha - y)**2)/(2*r)))
There is a grid with H horizontal rows and W vertical columns. Let (i, j) denote the square at the i-th row from the top and the j-th column from the left. In the grid, N Squares (r_1, c_1), (r_2, c_2), \ldots, (r_N, c_N) are wall squares, and the others are all empty squares. It is guaranteed that Squares (1, 1) and ...
3
import sys input = lambda : sys.stdin.readline().strip() class PERM_COMB_MOD(): # http://drken1215.hatenablog.com/entry/2018/06/08/210000 def __init__(self, max_n=510000, mod=10**9+7): self.fac = [0]*max_n self.finv = [0]*max_n self.inv = [0]*max_n self.fac[0] = self.fac[1] = 1 ...
Boboniu likes bit operations. He wants to play a game with you. Boboniu gives you two sequences of non-negative integers a_1,a_2,…,a_n and b_1,b_2,…,b_m. For each i (1≀ i≀ n), you're asked to choose a j (1≀ j≀ m) and let c_i=a_i\& b_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise...
3
n,m = map(int,input().split()); a = list(map(int,input().split())); b = list(map(int,input().split()));c=0 for i in range(513): c = 1 for j in a: u = 0 for k in b: if(i|(j&k)==i):u = 1;break if(u==0):c=0;break if(c==1):print(i);break ...
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
3
n = input() l = [int(i) for i in input().split()] l.sort() for i in l: print(i, end = ' ')
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
from sys import stdin x = int(stdin.readline().rstrip()) if x%2==0 and x!=2: print("YES") else: print("NO")
The Little Elephant loves to play with color cards. He has n cards, each has exactly two colors (the color of the front side and the color of the back side). Initially, all the cards lay on the table with the front side up. In one move the Little Elephant can turn any card to the other side. The Little Elephant thinks...
3
from collections import defaultdict n = int(input()) l1 = defaultdict(int) l2 = defaultdict(int) for _ in range(n): a, b = [int(i) for i in input().split()] if a != b: l1[a] += 1 l2[b] += 1 else: l1[a] += 1 k1 = list(l1.keys()) k2 = list(l2.keys()) ans = k1 + k2 ans = set(ans) k = (n...
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
import sys import math counter = -1 # dont change i swear to god # # # count = 0 for lin in sys.stdin: line = lin.rstrip() counter += 1 # LEAVE THE ABOVE # # if counter == 0: pass else: s = line break print(("1 " * s.count("n") + "0 " * s.count("z"))[:-1...
Let's consider all integers in the range from 1 to n (inclusive). Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≀ a < b ≀ n. The greatest common divisor, gcd(a, b), of two positive integ...
3
from sys import stdin, setrecursionlimit, stdout #setrecursionlimit(1000000) from collections import deque from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin def ii(): return int(stdin.readline()) def fi(): return float(stdin.readline()) def mi(): return map(int, stdin.readline().split()) def...
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5Β·i minutes to solve the i-th...
3
n,k = map(int,input().split()) time_for_solve = 240-k if time_for_solve >= n*(n+1)/2*5: print (n) else: for i in range(n+1): if time_for_solve >= i*5: time_for_solve -= i*5 #print (time_for_solve) else: print (i-1) break
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
1
import sys def choose(n, k): return fact(n) / (fact(n-k) * fact(k)) def fact(n): return 1 if n == 0 else n * fact(n-1) if __name__ == '__main__': S1 = list(raw_input()) S2 = list(raw_input()) s1_plus = sum(1 for s1 in S1 if s1 == '+') s1_minus = sum(1 for s1 in S1 if s1 == '-') s2_plus ...
People do many crazy things to stand out in a crowd. Some of them dance, some learn by heart rules of Russian language, some try to become an outstanding competitive programmers, while others collect funny math objects. Alis is among these collectors. Right now she wants to get one of k-special tables. In case you for...
1
def main(): n, k = map(int,raw_input().split()) a = [[0 for i in xrange(n)] for j in xrange(n)] now = n*n ans = 0 for i in xrange(n): for j in xrange(n-1,k-2,-1): a[i][j] = now now -= 1 if j == k-1: ans += a[i][j] for i in xrange(n): ...
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 β‹… a_2 β‹… ... a_n of its elements seemed to him not large enough. He was ready t...
3
n=int(input()) ans=list(map(int,input().split())) mx=0 idx=-1 for i in range(n): if ans[i]>=0: ans[i]=-ans[i]-1; if(abs(ans[i])>mx): idx=i mx=abs(ans[i]) #print(i,ans[i]) if n%2==1: ans[idx]=-ans[idx]-1 for i in ans: print(i,end=' ')
According to rules of the Berland fashion, a jacket should be fastened by all the buttons except only one, but not necessarily it should be the last one. Also if the jacket has only one button, it should be fastened, so the jacket will not swinging open. You are given a jacket with n buttons. Determine if it is fasten...
1
n = int(raw_input()) a = map(int, raw_input().split()) m = 0 for i in xrange(n): if a[i] == 0: m += 1 if n == 1: if m == 0: print "YES" else: print "NO" elif m == 0 or m >1: print "NO" else: print "YES"
Let's consider some integer X. We will call the following sequence S a sequence generated by X: for i = 1: S[i] = X for i > 1: S[i] equals to the minimal positive integer such that S[i] is not a divisor of S[i - 1]. If there is no such integer than S[i - 1] is the last element of S. For example S = (10, 3, 2) is a se...
1
def gcd(a,b): if b==0:return a return gcd(b,a%b) def lcm(a,b):return a*(b/gcd(a,b)) f=[1,1,1] for i in range(3,100): for j in range(1,i+1): if i%j!=0: f.append(1+f[j]) break def solve(x): if x==0:return 0 global f m=1 ans=1 for v in range(2,min(x+1,50)): #v<m*...
We call two numbers x and y similar if they have the same parity (the same remainder when divided by 2), or if |x-y|=1. For example, in each of the pairs (2, 6), (4, 3), (11, 7), the numbers are similar to each other, and in the pairs (1, 4), (3, 12), they are not. You are given an array a of n (n is even) positive in...
3
for _ in range(int(input())): n = int(input()) l = sorted(map(int,input().split())) c = 0 leven = [] lodd = [] for i in l: if i%2==0: leven.append(i) else: lodd.append(i) if len(leven)%2==0 and len(lodd)%2==0: print("YES") else: flag = 0 for j in range(1,n): if abs(l[j]-l[j-1])==1: flag =...
A Hitachi string is a concatenation of one or more copies of the string `hi`. For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not. Given a string S, determine whether S is a Hitachi string. Constraints * The length of S is between 1 and 10 (inclusive). * S is a string consisting of lowerc...
3
s=input() ans="No" if len(s)%2==0: if s=="hi"*(len(s)//2): ans="Yes" print(ans)
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
3
n = int(input()) a = list(map(int,input().split())) scale = 30 btc = [10**6 for _ in range(scale)] for i in range(n): x = a[i] for d in range(scale): if x % 2 == 1: if btc[d] == 10**6: btc[d] = i else: btc[d] = 10**6+1 x //= 2 btc.reverse()...
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied: * For any two vertices p...
3
import sys sys.setrecursionlimit(10**5) def f(x): for tmp in links[x]: if c[tmp[0]]<0: if tmp[1]%2==0: c[tmp[0]]=c[x]+0 else: c[tmp[0]]=1-c[x] f(tmp[0]) N=int(input()) links=[[] for _ in range(N+1)] for _ in range(N-1): u, v, w=map(int, input().split()) links[u].append([v, ...
A Hitachi string is a concatenation of one or more copies of the string `hi`. For example, `hi` and `hihi` are Hitachi strings, while `ha` and `hii` are not. Given a string S, determine whether S is a Hitachi string. Constraints * The length of S is between 1 and 10 (inclusive). * S is a string consisting of lowerc...
3
s = input().strip() if s == 'hi' * (len(s) // 2): print("Yes") else: print("No")
Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i. Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to...
1
#!/usr/bin/env python2 """ This file is part of https://github.com/cheran-senthil/PyRival Copyright 2019 Cheran Senthilkumar <hello@cheran.io> """ from __future__ import division, print_function import itertools import os import sys from atexit import register from io import BytesIO class dict(dict): """dict() ...
Input The input contains a single integer a (1 ≀ a ≀ 40). Output Output a single string. Examples Input 2 Output Adams Input 8 Output Van Buren Input 29 Output Harding
1
pres = ['Washington', 'Adams', 'Jefferson', 'Madison', 'Monroe', 'Adams', 'Jackson', 'Van Buren', 'Harrison', 'Tyler', 'Polk', 'Taylor', 'Fillmore', 'Pierce', 'Buchanan', 'Lincoln', 'Johnson', 'Grant', 'Hayes', 'Garfield', 'Arthur', 'Cleveland', 'Harrison', 'Cleveland', 'McKinley', 'Roosevelt', 'Taft', 'Wilson', 'Hardi...
Memory is performing a walk on the two-dimensional plane, starting at the origin. He is given a string s with his directions for motion: * An 'L' indicates he should move one unit left. * An 'R' indicates he should move one unit right. * A 'U' indicates he should move one unit up. * A 'D' indicates he shoul...
3
a = input() u = 0 d = 0 l = 0 r = 0 for i in a: if i == "U": u += 1 elif i == "D": d += 1 elif i == "R": r += 1 else: l += 1 x = abs(r - l) y = abs(u - d) printar = 0 while x > 0 and y > 0: printar += 1 x -= 1 y -= 1 if x == 0 and y == 0: print(printar) elif x % 2 == 0 and y % 2 == 0: printa...
While Farmer John rebuilds his farm in an unfamiliar portion of Bovinia, Bessie is out trying some alternative jobs. In her new gig as a reporter, Bessie needs to know about programming competition results as quickly as possible. When she covers the 2016 Robot Rap Battle Tournament, she notices that all of the robots o...
1
from sys import stdin from collections import * class graph: # initialize graph def __init__(self, gdict=None): if gdict is None: gdict = defaultdict(list) self.gdict, self.edges, self.indeg = gdict, [], [0] * (n + 1) # add edge def addEdge(self, node1, node2, w=None): ...
You took a peek on Thanos wearing Infinity Gauntlet. In the Gauntlet there is a place for six Infinity Gems: * the Power Gem of purple color, * the Time Gem of green color, * the Space Gem of blue color, * the Soul Gem of orange color, * the Reality Gem of red color, * the Mind Gem of yellow color. ...
3
a=int(input()) c={ 'purple': 'Power', 'green':'Time', 'blue': 'Space', 'orange': 'Soul', 'red' :'Reality' , 'yellow':'Mind' , } for i in range(a): b=input() c[b]='+' k=[] for i in c: if c[i]!='+': k.append(c[i]) print(len(k)) for i in k: print(i)
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
1
import sys import math s1 = sys.stdin.readline().strip() s2 = sys.stdin.readline().strip() target = s1.count("+") - s1.count("-") user_start = s2.count("+") - s2.count("-") num_question = s2.count("?") delta = target - user_start def nCr(n,k): return math.factorial(n) / (math.factorial(k) * math.factorial(n-k)) de...
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
# def Divisible(a, b): # ans = 0 # if a%b == 0: # return ans # while(a%b != 0): # a += 1 # ans += 1 # if a%b == 0: # return ans def Divisible(a, b): return 0 if a%b==0 else (((a//b)+1)*b)-a n = int(input()) for _ in range(n): ab = list(map(int, input().s...
Consider a conveyor belt represented using a grid consisting of n rows and m columns. The cell in the i-th row from the top and the j-th column from the left is labelled (i,j). Every cell, except (n,m), has a direction R (Right) or D (Down) assigned to it. If the cell (i,j) is assigned direction R, any luggage kept o...
3
t=int(input()) while(t): m,n=map(int,input().split()) l=[] for i in range(m): a=list(map(str,input().split())) l.append(a) c=0 for i in range(m-1): z=l[i][0] p=z[len(z)-1] if p=="R": c+=1 p=0 pp=str(l[m-1]) print(pp.count("D")+c) ...
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
3
n=int(input()) z=[] for i in range(n): a,b=map(int,input().split()) p=[] p.append(a) p.append(b) z.append(p) z.sort() k=-1 for i in range(n): if k<=z[i][1]: k=z[i][1] else: k=z[i][0] print(k)
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
# Process input num_words = int(input()) words = [] for i in range(num_words): words.append(input()) abbr=[] for word in words: if len(word)>10: abbr.append(word[0]+ str((len(word)-2)) +word[-1]) else: abbr.append(word) for word in abbr: print(word)
There are N cats. We number them from 1 through N. Each of the cats wears a hat. Cat i says: "there are exactly a_i different colors among the N - 1 hats worn by the cats except me." Determine whether there exists a sequence of colors of the hats that is consistent with the remarks of the cats. Constraints * 2 ≀ N ...
3
N = int( input()) A = list( map( int, input().split())) K = max(A) L = min(A) if K == L: if K == N-1 or 2*K <= N: print('Yes') else: print('No') elif abs(K-L) == 1: x = K*N - sum(A) if 2*K - x <= N and x < K: print('Yes') else: print('No') else: print('No')
There are three airports A, B and C, and flights between each pair of airports in both directions. A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours. Consider a route where we start at one of th...
1
n = raw_input().split(' ') n1 = int(n[0]) + int(n[1]) n2 = int(n[1]) + int(n[2]) n3 = int(n[2]) + int(n[0]) if n1 <= n2: if n1 < n3: print(n1) else : print(n3) elif n2 <= n3: print(n2) else: print(n3)
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity. There are n columns of toy cubes in the box arranged in a line. The i-th column contains ai cubes. At first, the gravity in the box is pulling...
3
n=input(); a = list(map(int,input().split())); print(*sorted(a),sep = ' ')