problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
# cook your dish here n = (input()) u = [] for char in n[::]: if char not in u: u.append(char); if(len(u)%2): print("IGNORE HIM!") else: print("CHAT WITH HER!");
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≀ k ≀ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≀ i ≀ n) she calculated a_i β€” the length of ...
3
for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) z='a' l='' if a[0]==0: print(z) z='b' s='b' else: print(z*a[0]) s=z*a[0] for i in range(1,n): if a[i]==0: print(s) if z=='a': ...
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()) while n > 0: n -=1 stroka = str(input()) if len(stroka) <= 10: print(stroka) else: a = stroka[0] b = stroka[-1] k = len(stroka) - 2 k = str(k) print(a+k+b)
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel. Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex...
1
#!/usr/bin/env python from sys import stdin def main(): n = int(stdin.readline().strip()) print (n-2)**2 return 0 if __name__ == '__main__': main()
Princess'Gamble Princess gambling English text is not available in this practice contest. One day, a brave princess in a poor country's tomboy broke the walls of her room, escaped from the castle, and entered the gambling hall where horse racing and other gambling were held. However, the princess who had never gambl...
3
import math TICKET_PRICE = 100 def get_data_list(): data_list = input().split() for i in range(len(data_list)): data_list[i] = int(data_list[i]) return data_list def get_input(): input_data = int(input()) return input_data def make_ticket_dict(player): ticket_sum = 0 ticket_list ...
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the eve...
3
n,m=list(map(int,input().split())) k=m if m>n: print(n) elif m==n: print(n+1) elif m<n: while n//m!=0: m=m+k n=n+1 print(n)
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin...
1
inputline = raw_input() n,k=inputline.split() n = int(n) k = int(k) if n&1==1: m=(n>>1) + 1 else: m= n>>1 if k<=m: print (k<<1) - 1 else: print (k - m)<<1
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
t=int(input()) for _ in range(t): n,k=map(int, input().strip().split()) print( (n//k)*k + min( n-((n//k)*k), k//2 ) )
Petya has an array a consisting of n integers. He wants to remove duplicate (equal) elements. Petya wants to leave only the rightmost entry (occurrence) for each element of the array. The relative order of the remaining unique elements should not be changed. Input The first line contains a single integer n (1 ≀ n ≀ ...
3
n=int(input()) a=list(map(int,input().split())) a.reverse() s=[] for i in range(n): if a[i] not in s: s.append(a[i]) s.reverse() print(len(s)) st="" for i in range(len(s)): st+=str(s[i])+" " print(st)
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m...
3
def move(a, i, j): f = a[i] for g in range(i, j, -1): a[g] = a[g - 1] a[j] = f n = int(input()) a = list(map(int, input().split())) c = 0 for i in range(0, 2 * n, 2): if a[i] != a[i + 1]: f = a[i + 1:].index(a[i]) + i + 1 move(a, f, i + 1) c += f - i - 1 print(c)
The math faculty of Berland State University has suffered the sudden drop in the math skills of enrolling students. This year the highest grade on the entrance math test was 8. Out of 100! Thus, the decision was made to make the test easier. Future students will be asked just a single question. They are given a sequen...
3
n = int(input()) s = input() l = [*map(int, s.split())] res = 0 d = {(1, 2): 3, (1, 3): 4, (2, 3): float('inf')} for i in range(n - 1, 0, -1): res += d[(min(l[i], l[i - 1]), max(l[i], l[i - 1]))] if res == float('inf'): print("Infinite") exit() print("Finite") print(res - s.count('3 1 2'))
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix M of size n Γ— n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≀ i, j ≀ n. We define a cross appearing in the i-th row and the j-th column (1 < i...
3
import sys def main(): n, *s = sys.stdin.read().strip().split('\n') c, t = 0, [(-1, 1), (-1, -1), (1, 1), (1, -1), (0, 0)] for i in range(1, int(n)-1): for j in range(1, int(n)-1): c += all(s[i+m][j+n] == 'X' for m,n in t) return c print(main())
Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`. Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7: * For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, a...
3
N = int(input()) s = input() mod = 10**9+7 dp = [[0] * N for _ in range(N)] dp[0][0] = 1 for i in range(N-1): prev_cs = [0] * (N+1) for j in range(N): prev_cs[j+1] = (prev_cs[j] + dp[i][j]) % mod if s[i] == '>': for j in range(i+2): dp[i+1][j] = (prev_cs[-1] - prev_cs[j]) % mod ...
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
d = sorted([x for x in map(int, input().split('+'))]) n = len(d) for i in range(n): if i != n-1: print('{0}+'.format(d[i]),end='') if i == n-1: print('{0}'.format(d[i]))
Write a program which reads a list of student test scores and evaluates the performance for each student. The test scores for a student include scores of the midterm examination m (out of 50), the final examination f (out of 50) and the makeup examination r (out of 100). If the student does not take the examination, t...
3
while 1: m,f,r=map(int,input().split());s=m+f if m==f==r<0:break if m*f<0 or s<30:print('F') elif(s<50)*(r<50):print('D') elif s<65:print('C') elif s<80:print('B') else:print('A')
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
3
n = int(input()) i = 2 resposta = 1 while i * i <= n: if n % i == 0: resposta *= i while n % i == 0: n //= i i += 1 if n > 1: resposta *= n print(resposta)
Even if the world is full of counterfeits, I still regard it as wonderful. Pile up herbs and incense, and arise again from the flames and ashes of its predecessor β€” as is known to many, the phoenix does it like this. The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ...
3
a,b = map(int,input().split()) d = 1 if b-a>=10: print(0) else: for i in range(a+1,b+1): d*=i print(str(d)[-1])
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
a = list(map(int, input().split())) M, N = a[0], a[1] print(M*N//2)
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode s...
Takahashi and Aoki are training for long-distance races in an infinitely long straight course running from west to east. They start simultaneously at the same point and moves as follows towards the east: * Takahashi runs A_1 meters per minute for the first T_1 minutes, then runs at A_2 meters per minute for the subse...
3
t1, t2 = map(int, input().split()) a1, a2 = map(int, input().split()) b1, b2 = map(int, input().split()) ng = "infinity" first = t1 * a1 - t1 * b1 second = t1 * a1 + t2 * a2 - t1 * b1 - t2 * b2 if second == 0: print(ng) exit() if first * second > 0: print(0) exit() if first < 0: first *= -1 ...
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area. To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r...
1
from fractions import gcd from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin, floor, atan from itertools import * from fractions import Fraction import string import copy import random import bisect from decimal import * from collections import deque from sys import * digs = string.digits + ...
There are n students standing in a circle in some order. The index of the i-th student is p_i. It is guaranteed that all indices of students are distinct integers from 1 to n (i. e. they form a permutation). Students want to start a round dance. A clockwise round dance can be started if the student 2 comes right after...
3
def process(A): n = len(A) one_kind = True n_index = None for i in range(n): if A[0]+i <= n: if A[i]!=i+A[0]: one_kind = False if A[0]+i==n: n_index = i elif A[0]+i > n: if n_index is None or (A[i] != i-n_index): ...
The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations: * d1 is the distance between the 1-st and the 2-nd station; * d2 is the distance between the 2-nd and the 3-rd station; ... * dn - 1 is the distance between the n - 1-th and the n-th station; ...
3
num = int(input()) arr = list(map(int, input().split())) st = list(map(int, input().split())) s, t = sorted(st) arr += arr s-=1 t-=1 print(min(sum(arr[s:t]), sum(arr[t:(num+s)]))) # print(arr) # print(s) # print(t)
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
a,b = zip(*[map(int, raw_input().split()) for _ in [0]*input()]) print sum([b.count(i) for i in a])
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). Consider a permutation p of length ...
3
import sys,math input=sys.stdin.readline n = int(input()) total = 1 mod = (10**9) + 7 for i in range(1,n+1): total = ((i % mod) * (total % mod)) % mod invert = 1 for i in range(1,n): invert = ((2 % mod) * (invert % mod)) % mod ans = (total - invert + mod) % mod print(ans)
Alyona has recently bought a miniature fridge that can be represented as a matrix with h rows and 2 columns. Initially there is only one shelf at the bottom of the fridge, but Alyona can install arbitrary number of shelves inside the fridge between any two rows. A shelf is two cells wide, does not occupy any space but ...
3
n, h = map(int, input().split()) a = list(map(int, input().split())) v = [] ans = 0 for i in range(n): v.append(a[i]) v.sort(reverse = True) cnt = 0 for j in range(0, len(v), 2): cnt += v[j] if (cnt <= h): ans = i + 1 print(ans)
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
1
n, m = map(int, raw_input().split()) D = [0] * (m+1) for _ in range(n): B = map(int, raw_input().split())[1:] for b in B: D[b] = 1 print 'NO' if 0 in D[1:] else 'YES'
"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
n=list(map(int,input().split())) l=list(map(int,input().split())) a=l[n[1]-1] c=0 for i in range(len(l)): if(l[i]>=a and l[i]>0): c=c+1 print(c)
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,...
1
a = int(raw_input()) x = map(int,raw_input().split(" ")) y = [] ctr = 1 ln = 0 for i in x: if i<=ln: ctr+=1 y.append(ln) ln = i y.append(i) print ctr for i in y: print i,
This is the easy version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
import math t = 1 for tc in range(t): n = int(input()) arr = list(map(int, input().split())) arr.sort() j = n // 2 k = 0 l = j new_arr = [0] * n for i in range(0,n,2) : new_arr[i] = arr[l] l += 1 if i != n-1: new_arr[i+1] = arr[k] k += 1 ...
You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers. For instance, if we are given an array [10, 20, 30, 40], we can pe...
1
from sys import stdin, stdout ti = lambda : stdin.readline().strip() ma = lambda fxn, ti : map(fxn, ti.split()) ol = lambda arr : stdout.write(' '.join(str(i) for i in arr) + '\n') os = lambda i : stdout.write(str(i) + '\n') olws = lambda arr : stdout.write(''.join(str(i) for i in arr) + '\n') n = int(ti()) a = ma(in...
Given are N positive integers A_1,...,A_N. Consider positive integers B_1, ..., B_N that satisfy the following condition. Condition: For any i, j such that 1 \leq i < j \leq N, A_i B_i = A_j B_j holds. Find the minimum possible value of B_1 + ... + B_N for such B_1,...,B_N. Since the answer can be enormous, print t...
3
from fractions import gcd n=int(input()) a=list(map(int,input().split())) mod=10**9+7 x = a[0] for i in range(1, len(a)): x = (x * a[i]) // gcd(x, a[i]) gcd=x res = 0 for i in a: res += gcd//i #res%=mod print(res%mod)
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
from math import sqrt x = [] y = [] while(1): try: a = [float(i) for i in input().split(",")] x.append(a[0]) y.append(a[1]) except EOFError: break n = len(x) S = 0 for i in range(n-2): if i == 0: a = sqrt((x[1]- x[0])**2 + (y[1]-y[0])**2) b = sqrt((x[i+2]- x[i+1]...
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest. In total, n students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to n. Let's denote the...
1
n = input() a = map(int, raw_input().split()) def place(x): return len([i for i in a if i > x]) + 1 b = map(place, a) print ' '.join(map(str, b))
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
from math import ceil for T in range(int(input())): n,x=map(int,input().split()) if(n<=2): print(1) else: n-=2 floor=ceil(n/x) print(floor+1)
Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no mo...
3
# -*- coding: utf-8 -*- """ @Project : CodeForces @File : 2.py @Time : 2018/6/17 0:27 @Author : Koushiro """ if __name__ == "__main__": n, k = map(int, input().split()) knight = [[i,0,0,0]for i in range(n)] power = list(map(int, input().split())) money = list(map(int, input().split())) fo...
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...
1
# map(int, raw_input().split())... # " ".join([])... # [0] * n... # isupper... d = int(raw_input()) n = int(raw_input()) ans = 0 for x in map(int, raw_input().split())[:-1]: ans += d - x print ans
This problem uses a simplified network topology model, please read the problem statement carefully and use it as a formal document as you develop the solution. Polycarpus continues working as a system administrator in a large corporation. The computer network of this corporation consists of n computers, some of them a...
3
R = lambda: map(int, input().split()) n, m = R() c = [0] * n for i in range(m): x, y = R() c[x - 1] += 1 c[y - 1] += 1 c1 = c2 = 0 for i in range(n): if c[i] == 1: c1 += 1 elif c[i] == 2: c2 += 1 if c2 == n: print("ring topology") elif c1 == 2 and c2 == n - 2: print("bus topology") elif c1 == n - ...
You are at a water bowling training. There are l people who play with their left hand, r people, who play with their right hand, and a ambidexters, who can play with left or right hand. The coach decided to form a team of even number of players, exactly half of the players should play with their right hand, and exactl...
3
# bsdk idhar kya dekhne ko aaya hai, khud kr!!! # from math import * # from itertools import * # import random l, r, a = map(int, input().split()) if a == 0: min_ = min(l, r) print(2 * min_) elif a != 0: # a is not equal to zero then we have to check if its diff is less than or equal or a or not and then we...
Today, Wet Shark is given n integers. Using any of these integers no more than once, Wet Shark wants to get maximum possible even (divisible by 2) sum. Please, calculate this value for Wet Shark. Note, that if Wet Shark uses no integers from the n integers, the sum is an even integer 0. Input The first line of the ...
3
n = int(input()) odd = 0 lowest_odd = None s = 0 for num in map(int, input().split()): s += num if num % 2 == 1: odd += 1 if lowest_odd is None or num < lowest_odd: lowest_odd = num if odd % 2 == 1: print(s-lowest_odd) else: print(s)
Olesya loves numbers consisting of n digits, and Rodion only likes numbers that are divisible by t. Find some number that satisfies both of them. Your task is: given the n and t print an integer strictly larger than zero consisting of n digits that is divisible by t. If such number doesn't exist, print - 1. Input T...
3
a,b=map(int,input().split()) hmm=False for i in range(10**(a-1), 10**a+10): if i%b==0: hmm=True break if hmm==True and 10**(a)>b: print(i) else: print(-1)
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()) m=0 for i in range(n): yes=0 list=input().split(' ') for x in range(3): if int(list[x])==1: yes=yes+1 if yes>=2: m=m+1 print(m)
<image> The International Clown and Pierrot Competition (ICPC), is one of the most distinguished and also the most popular events on earth in the show business. One of the unique features of this contest is the great number of judges that sometimes counts up to one hundred. The number of judges may differ from one co...
1
# -*- coding: utf-8 -*- n = int(raw_input()) while n != 0: list = [] for i in range(n): list.append(int(raw_input())) print (sum(list)-max(list)-min(list))/(n-2) n = int(raw_input())
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
t=input().split() #print(t) d=set(t) #print(d) ans=4-len(d) print(ans)
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 ...
3
import math r,x,y,x1,y1=map(int,input().split()) dis=math.sqrt((x-x1)**2 +(y-y1)**2) fd=dis ans1=int(fd/(2*r)) ans2=fd%(2*r) if ans2>0: print(ans1+1) else: print(ans1)
Kolya is very absent-minded. Today his math teacher asked him to solve a simple problem with the equation a + 1 = b with positive integers a and b, but Kolya forgot the numbers a and b. He does, however, remember that the first (leftmost) digit of a was d_a, and the first (leftmost) digit of b was d_b. Can you reconst...
3
i = input() a = int(i[0]) b = int(i[2]) c, d = 0,0 if b - a == 1: c = a*10+9 d = b*10 e = str(c) + ' ' + str(d) elif b == a: c = a*10 d = a*10+1 e = str(c) + ' ' + str(d) elif a == 9 and b == 1: c = 99 d = 100 e = str(c) + ' ' + str(d) else: e = -1 print(e)
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()) counter = 0 for i in range(n): x = input().split(' ') sum = 0 for i in x: sum += int(i) if sum >= 2: counter += 1 break print(counter)
You are given two arrays A and B, each of size n. The error, E, between these two arrays is defined <image>. You have to perform exactly k1 operations on array A and exactly k2 operations on array B. In one operation, you have to choose one element of the array and increase or decrease it by 1. Output the minimum poss...
1
from heapq import heappush as hpush, heappop as hpop n, k1, k2 = map(int, raw_input().strip().split()) a = map(int, raw_input().strip().split()) b = map(int, raw_input().strip().split()) k = k1 + k2 heap = [] for i in xrange(n): hpush(heap, -abs(a[i] - b[i])) x = -1 while 1: if k == 0: break x = hp...
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
name = input() a = len(set(name)) if a % 2 == 0: print('CHAT WITH HER!') else: print('IGNORE HIM!')
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≀ i ≀ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i an...
3
n,m =map(int,input().split()) l1=list(map(int,input().split())) l2=list(map(int,input().split())) l1.sort() l2.sort() m1=max(l1) m2=min(l2) s1=sum(l1) s2=sum(l2) if m2<m1: print(-1) else: if l2[0]>l1[n-1]: print(m*(s1)-l1[n-2]-(m-1)*l1[n-1]+s2) else: print(m*(s1)-(m)*l1[n-1]+s2)
Polycarp wants to cook a soup. To do it, he needs to buy exactly n liters of water. There are only two types of water bottles in the nearby shop β€” 1-liter bottles and 2-liter bottles. There are infinitely many bottles of these two types in the shop. The bottle of the first type costs a burles and the bottle of the se...
3
for _ in[0]*int(input()): n,a,b=map(int,input().split()) print(min(n*a,n//2*b+n%2*a))
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
n, m, a = map(int, input().split()) ans = ((n+a-1)//a)*((m+a-1)//a) print(ans)
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears. These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite β€” cookies. Ichihime decides to attend the contest. Now sh...
3
# import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') # import re gg="abcdefghijklmnopqrstuvwxyz" # def negmod(a, m): # return (a%m + m) % m # for C in range(int(input())): # rawstr = ''.join([int(x) * '(' + x + ')' * int(x) for x in str(input())]) # for _ in range(9): # raws...
This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem. Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ...
3
n = int(input()) arr = list(map(int, input().split())) res = [0] * n arr.sort() res[1::2] = arr[:n//2] res[::2] = arr[n//2:] x = 0 for i in range(1, n-1): x += res[i-1] > res[i] < res[i+1] print(x) print(*res)
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two pa...
3
from sys import stdin all_in = stdin.read().splitlines() n = int(all_in[0]) if n == 2: print('Yes') print(1) print(1, 2) exit() graph = {i: list() for i in range(1, n + 1)} for el in all_in[1: n + 1]: a, b = map(int, el.split()) graph[a].append(b) graph[b].append(a) sor = sorted(graph...
The only difference between easy and hard versions is constraints. You are given a sequence a consisting of n positive integers. Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ...
3
import math N=int(input()) for i in range(0,N): n=int(input()) S=input().split() P=[] for i in range(0,n): P.append(int(S[i])) ans=0 for i in range(1,27): for j in range(1,27): templist=[] if i==j: continue inumber=0 ...
In the 2022 year, Mike found two binary integers a and b of length n (both of them are written only by digits 0 and 1) that can have leading zeroes. In order not to forget them, he wanted to construct integer d in the following way: * he creates an integer c as a result of bitwise summing of a and b without transfe...
1
for _ in range(input()): n=input() b=raw_input() a="1" o=str(1+int(b[0])) for i in range(1,n): if b[i]=='0' and o[len(o)-1]!='1': a+='1' o+='1' elif b[i]=='0': a+='0' o+='0' elif b[i]=='1' and o[len(o)-1]!='2': a+='1...
At many competitions that have a word Β«cupΒ» in its official name the winner is presented with an actual cup. This time the organizers of one unusual programming competition have decided to please the winner even more and to add a nameplate to the cup with the handle of the winner. The nameplate is to be rectangular an...
3
a = input() str1 = (len(a)-1)//20+1 sto1 = (len(a)+str1-1)//str1 f = str1-1-(len(a)+str1-1) % str1 print(str1, sto1) for q in range(str1): if q < f: print(*a[(sto1-1)*q:(sto1-1)*(q+1)], '*', sep='') else: print(*a[(sto1-1)*f+sto1*(q-f):(sto1-1)*f+sto1*(q-f+1)], sep='')
There are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equa...
3
n=int(input()) s=[int(x) for x in input().split()] G=sorted(s) c=0 for i in range(0,len(G),2): c=c+abs(G[i+1]-G[i]) print(c) """L=[0]*105 G=[] for i in range(0,len(s)): if(L[s[i]]%2==0): L[s[i]]=1 else: L[s[i]]=L[s[i]]+1 for i in range(0,len(L)): if(L[i]%2==0): L[i]=0 for i in ra...
Three people, A, B and C, are trying to communicate using transceivers. They are standing along a number line, and the coordinates of A, B and C are a, b and c (in meters), respectively. Two people can directly communicate when the distance between them is at most d meters. Determine if A and C can communicate, either ...
3
a,b,c,d=map(int,input().split()) print("Yes" if abs(c-a)<=d or (abs(a-b)<=d and abs(b-c)<=d) else "No")
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
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,...
1
n=input() radii=map(int,raw_input().split(" ")) radii.sort() sum=0 if n%2!=0: sum=radii[0]**2 if n>1: for x in range(2,n,2): sum+=radii[x]**2-radii[x-1]**2 else: for x in range(1,n,2): sum+=radii[x]**2-radii[x-1]**2 print sum*3.1415926536
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
T = int( input() ) for t in range(T): n = int( input() ) st = input().split() A = [] s = 0 for i in range(n): A.append( int( st[i] ) ) s += A[i] if s == 0: print("NO") continue else: print("YES") if s > 0: A = sorted(A, reverse=True) else: A = sorted(A) if A[0] ...
You came to the exhibition and one exhibit has drawn your attention. It consists of n stacks of blocks, where the i-th stack consists of a_i blocks resting on the surface. The height of the exhibit is equal to m. Consequently, the number of blocks in each stack is less than or equal to m. There is a camera on the cei...
3
# Main def run(): n, mmm = map(int, input().split()) arr = list(map(int, input().split())) arr.sort() ans = 0 for i in range(n): if arr[i] > ans: ans += 1 left = arr[n-1] - ans sol = sum(arr) - n - left print(sol) # end main # Program Start if __name__ == "__m...
For god's sake, you're boxes with legs! It is literally your only purpose! Walking onto buttons! How can you not do the one thing you were designed for? Oh, that's funny, is it? Oh it's funny? Because we've been at this for twelve hours and you haven't solved it either, so I don't know why you're laughing. You've got ...
3
# ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode...
Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other wi...
3
d,l,v1,v2 = map(int, input().split()) l-=d totv = v1+v2 print(l/totv)
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) arr.sort() present,cnt,cur = 1,0,0 for i in range(n): if arr[i]<=present:present += 1 elif arr[i]<=(present+cur): present += cur+1 cur = 0 else:cur += 1 print(prese...
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible ...
3
x = int(input()) #x, y = map(int, input().split()) y = x//210*48 for i in range(1, x%210 + 1): if i%2 and i%3 and i%5 and i%7: y+=1 print(y)
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
s=input() t=input() if(s[::-1]==t or s==t[::-1]): print("YES") else: print("NO")
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≀ k ≀ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
t = int(input()) while t: x,y,n = map(int,input().split()) if n-n%x+y<=n: print(n-n%x+y) else: print(n-n%x-(x-y)) t-=1
Skier rides on a snowy field. Its movements can be described by a string of characters 'S', 'N', 'W', 'E' (which correspond to 1 meter movement in the south, north, west or east direction respectively). It is known that if he moves along a previously unvisited segment of a path (i.e. this segment of the path is visite...
3
from collections import defaultdict as dd t=int(input()) while t: d=dd(int) s=input() x=0 y=0 d[(x,y)]=1 ans=0 px=0 py=0 for i in range(len(s)): a=s[i] if(a=='N'): y+=1 l=[(px,py),(x,y)] l.sort() l=tuple(l) i...
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, m = [int(x) for x in input().split(' ')] numbers = [int(x) for x in input().split(' ')] max_res = 0 total_sum = sum(numbers) sum_thus_far = 0 for i in range(n-1): tmp_a = sum_thus_far + numbers[i] tmp_b = total_sum - tmp_a tmp_sum = (tmp_a % m) + (tmp_b % m) if tmp_sum > max_res: max_res = tmp_sum print(max_...
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as Β«.Β», 1 as Β«-.Β» and 2 as Β«--Β». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet. Input The first line contains a nu...
3
x = input() i = 0 l = [] for _ in range(len(x)): if i < len(x): if x[i] == '.': l.append('0') i += 1 elif x[i] == '-': if x[i + 1] == '.': l.append('1') else: l.append('2') i += 2 else: break x = ...
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepi...
3
a,b,c = [int(i) for i in input().split(" ")] fact1 = set() for i in range(1,a//2+1): if a%i==0: fact1.add((i,a//i)) if a//i!=i: fact1.add((a//i, i)) fact2 = set() for i in range(1,b//2+1): if b%i==0: fact2.add((i,b//i)) if b//i!=i: fact2.add((b//i, i)) fact3 = set() for i in range(1,c//2+1): if c%i=...
There are N gems. The value of the i-th gem is V_i. You will choose some of these gems, possibly all or none, and get them. However, you need to pay a cost of C_i to get the i-th gem. Let X be the sum of the values of the gems obtained, and Y be the sum of the costs paid. Find the maximum possible value of X-Y. Co...
3
N = int(input()) V = list(map(int,input().split())) C = list(map(int,input().split())) print(sum([a-b if a-b>0 else 0 for a,b in zip(V,C)]))
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
3
t=int(input()) a=list(map(int,input().strip().split(" "))) a.sort() c=1;d=1 if t==1: print(0) else: for i in range(t-1): if a[i]==a[i+1]: c+=1 else: break for i in range(t-1,0,-1): if a[i]==a[i-1]: d+=1 else: break if ...
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string s. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" <image>...
3
from collections import Counter n = int(input()) c = Counter(input()) print(('1' if c['1'] else '')+('0'*c['0']))
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 ...
3
# 507B import math __author__ = 'artyom' r, x, y, x0, y0 = map(int, input().split()) print(math.ceil(math.sqrt((x - x0) ** 2 + (y - y0) ** 2) / (2 * r)))
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i β‰  a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
3
n = int(input()) l = [0]*(n+1) great = 0 for i in range(2, n+1): if l[i] == 0: great += 1 for j in range(i, n+1, i): l[j] = great print(*l[2:]) # import math # for i in range(2, n+1): # for j in range(i, n+1): # if math.gcd(i, j) == 1: # print(i, j) # print(l[i] != l[j])
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-...
3
n=input() x=len(n) f=0 if '8' in n: f=1 s='8' elif '0' in n: f=1 s='0' else: for i in range(x): for j in range(i+1,x): s=n[i]+n[j] if int(s)%8==0: f=1 break if f: break if f==0 and x>=3: for i in range(x)...
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
3
# You lost the game. s = str(input()) n = len(s) L = [s] def ok(L,s): for x in L: if x == s: return 0 return 1 for i in range(n): s = s[1:]+s[0] if ok(L,s): L += [s] print(len(L))
You are given an array a_{1}, a_{2}, …, a_{n}. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct. In other words, at most one time you can choose two integers l and r (1 ≀ l ≀ r ≀ n) and delete integers a_l, a_{l+1}, …, a_r from the array. Remaining elements should be pa...
3
""" NTC here """ from sys import setcheckinterval, stdin setcheckinterval(1000) # print("Case #{}: {} {}".format(i, n + m, n * m)) def iin(): return int(stdin.readline()) def lin(): return list(map(int, stdin.readline().split())) n=iin() a=lin() sol=n dc={} ans=n check=0 for i in a: try: dc[i]+=...
Given 2 integers u and v, find the shortest array such that [bitwise-xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of its elements is u, and the sum of its elements is v. Input The only line contains 2 integers u and v (0 ≀ u,v ≀ 10^{18}). Output If there's no array that satisfies the condition, print "...
3
u, v = map(int, input().split()) if u & 1 != v & 1 or u > v: print(-1) elif u == v == 0: print(0) elif u == v: print(1, u) elif (v + u >> 1) ^ (v - u >> 1) == u: print(2, v + u >> 1, v - u >> 1) else: print(3, u, v - u >> 1, v - u >> 1)
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns: * Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1. A tree...
3
t = int(input()) for i in range(t): s = input().split(' ') n = int(s[0]) x = int(s[1]) c = 0 for j in range(n-1): s = input().split(' ') u = int(s[0]) v = int(s[1]) if x == u or x == v: c += 1 if c > 1: if n % 2 == 0: print('Ayush'...
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 ...
1
from sys import stdin n = int(stdin.readline()) a = map(int, stdin.readline().split()) a.sort() a.reverse() print sum(a[1:1+2*n:2])
"You must lift the dam. With a lever. I will give it to you. You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give Danik the lever. But to get a stone...
3
result = [] for a in range(int(input())): input() checkList = [bin(int(val)) for val in input().split()] list_count = [0] * 32 correctCases = 0 for a in checkList: list_count[len(a) - 3] += 1 for c in list_count: correctCases += (c - 1)/2*c result.append(int(correctCases)) ...
Monocarp has got two strings s and t having equal length. Both strings consist of lowercase Latin letters "a" and "b". Monocarp wants to make these two strings s and t equal to each other. He can do the following operation any number of times: choose an index pos_1 in the string s, choose an index pos_2 in the string...
3
n = int(input()) a = input() b = input() c,d,l = [],[],0 for i in range(n): if a[i]==b[i]: continue else: k = a[i]+b[i] if k=="ab": c.append(i+1) else: d.append(i+1) p,q = len(c),len(d) if p>0 or q>0: if p%2==q%2: if p%2==0: print(p...
There are n integers b1, b2, ..., bn written in a row. For all i from 1 to n, values ai are defined by the crows performing the following procedure: * The crow sets ai initially 0. * The crow then adds bi to ai, subtracts bi + 1, adds the bi + 2 number, and so on until the n'th number. Thus, ai = bi - bi + 1 + bi...
3
n = int(input()) a_values = [int(i) for i in input().split()] b = [] for i in range(1, len(a_values)): b_value = a_values[i] + a_values[i - 1] b.append(b_value) b.append(a_values[n - 1]) print(*b)
n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the locat...
3
''' Author: csc Date: 2021-04-28 12:22:16 LastEditTime: 2021-04-29 12:31:32 LastEditors: Please set LastEditors Description: In User Settings Edit FilePath: \code_py\ex.py ''' def solve(): n = int(input()) mix, mxx = -100000, 100000 miy, mxy = -100000, 100000 for _i in range(n): x, y, f1, f2, ...
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed som...
3
#import base64 def get(s): hao = set() c = 0 last = '@' for e in s: if last == '@': last = e c = 1 continue elif e == last: c += 1 else: if c % 2 == 1: hao.add(last) c = 1 last = e ...
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price β€” their owners are ready to pay Bob if he buys their useless apparatus. Bob can Β«buyΒ» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ...
3
if __name__ == '__main__': n, m = map(int, input().split()) a = sorted(list(map(int, input().split()))) ans = 0 for i in range(min(m, len(a))): if a[i] < 0: ans -= a[i] else: break print(ans)
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and n water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that...
3
from sys import stdin, stdout n, s = map(int,stdin.readline().split()) arr = list(map(int,stdin.readline().split())) arr.sort() arr = arr[:len(arr)-1] if(sum(arr)<=s): stdout.write('YES\n') else: stdout.write('NO\n')
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
n=int(input()) string=[] for _ in range(n): string.append(input()) string.sort(key=len) flag=True #print(string) for i in range(n-1): s=string[i] s_n=string[i+1] if s_n.find(s)==-1: flag=False break if flag==False: print("NO") if flag==True: print("YES") for s in string...
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
3
def solve(): n, m, k = map(int, input().split()) if n // k >= m: print(m) else: rp = k-1 #remaining players rj = m - n // k #remaining jokers if rj % rp == 0: print(n//k - rj // rp) else: j = rj // rp + 1 print(n//k - j) def ma...
Emuskald needs a fence around his farm, but he is too lazy to build it himself. So he purchased a fence-building robot. He wants the fence to be a regular polygon. The robot builds the fence along a single path, but it can only make fence corners at a single angle a. Will the robot be able to build the fence Emuskald...
1
for i in range(int(raw_input())): print ["YES","NO"][360%(180-input())>0] #print "fuck yourself if cannot do this simple"
Danny, the local Math Maniac, is fascinated by circles, Omkar's most recent creation. Help him solve this circle problem! You are given n nonnegative integers a_1, a_2, ..., a_n arranged in a circle, where n must be odd (ie. n-1 is divisible by 2). Formally, for all i such that 2 ≀ i ≀ n, the elements a_{i - 1} and a_...
3
from sys import stdin import math from collections import deque from bisect import * g = lambda : stdin.readline().strip() gl = lambda : g().split() gil = lambda : [int(var) for var in gl()] gfl = lambda : [float(var) for var in gl()] gcl = lambda : list(g()) gbs = lambda : [int(var) for var in g()] mod = int(1e9)+7...
We have a 3 \times 3 grid. A number c_{i, j} is written in the square (i, j), where (i, j) denotes the square at the i-th row from the top and the j-th column from the left. According to Takahashi, there are six integers a_1, a_2, a_3, b_1, b_2, b_3 whose values are fixed, and the number written in the square (i, j) is...
3
c=[list(map(int,input().split()))for i in range(3)] a=[c[0][i]-0 for i in range(3)] b=[c[i][0]-a[0]for i in range(3)] d=[[a[i]+b[j] for i in range(3)]for j in range(3)] print('Yes' if c==d else 'No')
You are given two integers K and S. Three variable X, Y and Z takes integer values satisfying 0≀X,Y,Z≀K. How many different assignments of values to X, Y and Z are there such that X + Y + Z = S? Constraints * 2≀K≀2500 * 0≀S≀3K * K and S are integers. Input The input is given from Standard Input in the following for...
3
k,s = map(int,input().split()) print(sum(0<=s-i-j<=k for i in range(k+1) for j in range(k+1)))
After the mysterious disappearance of Ashish, his two favourite disciples Ishika and Hriday, were each left with one half of a secret message. These messages can each be represented by a permutation of size n. Let's call them a and b. Note that a permutation of n elements is a sequence of numbers a_1, a_2, …, a_n, in ...
3
n = int(input()) a = [int(i)-1 for i in input().split()] b = [int(i)-1 for i in input().split()] aindex = [0]*n for i in range (n): aindex[a[i]]=i bindex = [0]*n for i in range (n): bindex[b[i]]=i shifts=[0]*n for i in range (n): if a[i]==b[i]: shifts[0]+=1 elif i<bindex[a[i]]: shifts[bi...
Yaroslav has an array, consisting of (2Β·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1. Yaroslav is now wondering: what maximum sum of array elements c...
1
R=lambda:map(int,raw_input().split()) n=input() a=R() b=sorted([abs(i) for i in a]) if min(a)>=0 or n&1 or sum([1 for i in a if i<0])%2 == 0:print sum(b) else:print sum(b)-2*b[0]