problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Recently, Norge found a string s = s_1 s_2 … s_n consisting of n lowercase Latin letters. As an exercise to improve his typing speed, he decided to type all substrings of the string s. Yes, all (n (n + 1))/(2) of them! A substring of s is a non-empty string x = s[a … b] = s_{a} s_{a + 1} … s_{b} (1 ≤ a ≤ b ≤ n). For e...
3
line1 = input() n, k = line1.split() n, k = int(n), int(k) string = input() cs = input().split() subs = [[]] for c in string: if c in cs: subs[-1].append(c) else: if len(subs[-1]) != 0: subs.append([]) ret = 0 for sub in subs: a = len(sub) if a != 0: ret += (a * (...
You are given two integers a and b. In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves. Your task is to find the minimum number of mo...
3
for i in range(int(input())):a,b=map(int,input().split());print((abs(a-b)+9)//10)
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n). <image> An example of a cornfield with n = 7 and d = 2. Vasya also knows that there are m grasshoppers near the fie...
3
n, d = map(int, input().split()) count = int(input()) for i in range(count): x, y = map(int, input().split()) if (y>=x-d) and (y>=-x+d) and (y<=x+d) and (y<=-x+n*2-d): print('YES') else: print('NO')
For an array b of length m we define the function f as f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases} where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6...
3
import sys n = int(input()) matriz = [[0] * n for i in range(n)] maiores = matriz entrada = list(map(int, sys.stdin.readline().split())) for i in range(n): matriz[i][i] = entrada[i] for i in range(n - 1, -1, -1): for j in range(i + 1, n): a = matriz[i][j - 1] b = matriz[i + 1][j] xo...
Snuke lives on an infinite two-dimensional plane. He is going on an N-day trip. At the beginning of Day 1, he is at home. His plan is described in a string S of length N. On Day i(1 ≦ i ≦ N), he will travel a positive distance in the following direction: * North if the i-th letter of S is `N` * West if the i-th letter...
1
# coding: UTF-8 s = raw_input() if 'N' in s and 'W' in s and 'S' in s and 'E' in s: print "Yes" elif 'N' in s and not 'W' in s and 'S' in s and not 'E' in s: print "Yes" elif not 'N' in s and 'W' in s and not 'S' in s and 'E' in s: print "Yes" else : print "No"
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that. For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ...
3
def check(num): for i in [2,3,5,7,11,13,17,19,23,29,31]: if num % i == 0 and (num // i) > 1: return 1 return 0 n = int(input()) j = 4 num = n - 4 while not check(num): j = j + 1 if check(j): num = n - j print(num,j)
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,...
3
n=int(input()) arr=list(map(int,input().split())) number=arr.count(1) indices=[] for i in range(len(arr)): if arr[i]==1: indices+=[i] ans=[] for i in range(1,len(indices)): ans+=[indices[i]-indices[i-1]] ans+=[arr[-1]] print(number) print(' '.join(list(map(str,ans))))
Problem description You will be given a zero-indexed array A. You need to rearrange its elements in such a way that the following conditions are satisfied: A[i] ≤ A[i+1] if i is even. A[i] ≥ A[i+1] if i is odd. In other words the following inequality should hold: A[0] ≤ A[1] ≥ A[2] ≤ A[3] ≥ A[4], and so on. Operation...
1
for _ in xrange(int(raw_input())): n=int(raw_input()) a=map(int,raw_input().split()) a=sorted(a) if len(a)%2!=0: for i in range(1,len(a)-1,2): val=a[i] a[i]=a[i+1] a[i+1]=val print ' '.join(str(a[k]) for k in xrange(len(a))) else: for i in ...
Takahashi wants to gain muscle, and decides to work out at AtCoder Gym. The exercise machine at the gym has N buttons, and exactly one of the buttons is lighten up. These buttons are numbered 1 through N. When Button i is lighten up and you press it, the light is turned off, and then Button a_i will be lighten up. It ...
1
from sys import stdin a = [0] n = int(stdin.readline()) for _ in xrange(n): a.append(int(stdin.readline())) ans = -1 cur = 0 x = 1 s = set() while True: if x in s: break if x==2: ans = cur break s.add(x) cur+=1 x = a[x] print ans
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
## f(n) = -1 + 2 - 3 + 4 - 5 + ... + n * (-1)^n def f(n): if n % 2 == 0: return n // 2 else: return - (n + 1) // 2 n = int(input()) print(f(n))
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
## first line consists no.of friends and height of fence ## second line consists of height of friends w=1 wExtended=2 n,h = list(map(int,input().split())) heights = list(map(int,input().split())) hl=h totalWidth=0 for i in heights: if i > hl: totalWidth += 2 else: totalWidth += 1 ...
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep...
3
t = int(input()) for i in range(t): a,b,c,d = map(int,input().split()) m = 0 if b>=a: m = b else: m += b if(d>=c): m = -1 else: x = (a-b)/(c-d) if(int(x) == x): x = int(x) m += x*c else: ...
Notes Template in C Constraints 2 ≤ the number of operands in the expression ≤ 100 1 ≤ the number of operators in the expression ≤ 99 -1 × 109 ≤ values in the stack ≤ 109 Input An expression is given in a line. Two consequtive symbols (operand or operator) are separated by a space character. You can assume that +...
3
s=[] p=s.pop for e in input().split(): s+=[e if e.isdigit() else str(eval(p(-2)+e+p()))] print(*s)
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo) Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho...
3
import sys input = sys.stdin.readline loop,num = int(input().strip()), 0 for i in range(1, loop + 1): num += 1/i print(num)
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 109) of the equation: x = b·s(x)a + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in...
1
def sum_digits(n): s = 0 while n: n, remainder = divmod(n, 10) s += remainder return s '''def solve1(a, b, c): solves = [] for i in xrange(100): x = b * pow(sum_digits(i), a) + c print x if x == i: solves.append(x) print len(solves) print solves''' def solve2(a, b, c, length):...
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
a = [[0]] * 5 row = 0 colon = 0 for i in range(5): a[i] = list(map(int, input().split())) tik_mini = 0 for i in range(5): for j in a[i]: if j == 1: row = i colon = tik_mini tik_mini += 1 tik_mini = 0 tik = 0 while row != 2: if row > 2: row -= 1 tik...
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times. Greg now only does three types of exercises: "chest" exercises,...
3
t=int(input()) n=list(map(int,input().split())) a=0 b=0 c=0 i=0 while i<t: a=a+n[i] if i+1<t: b=b+n[i+1] if i+2<t: c=c+n[i+2] i=i+3 dic={"chest":a,"biceps":b,"back":c} print(max(dic, key=dic.get))
This contest, AtCoder Beginner Contest, is abbreviated as ABC. When we refer to a specific round of ABC, a three-digit number is appended after ABC. For example, ABC680 is the 680th round of ABC. What is the abbreviation for the N-th round of ABC? Write a program to output the answer. Constraints * 100 ≤ N ≤ 999 I...
3
s = 'ABC' n = str(input()) print(s+n)
This is the easy version of the problem. The difference between the versions is that the easy version has no swap operations. You can make hacks only if all versions of the problem are solved. Pikachu is a cute and friendly pokémon living in the wild pikachu herd. But it has become known recently that infamous team R...
3
from sys import stdin from math import ceil, gcd # Input data #stdin = open("input", "r") def func(): return for _ in range(int(stdin.readline())): n, q = map(int, stdin.readline().split()) arr = list(map(int, stdin.readline().split())) # dp[i][0] -> till index i we have even no. of elements in ou...
Vanya smashes potato in a vertical food processor. At each moment of time the height of the potato in the processor doesn't exceed h and the processor smashes k centimeters of potato each second. If there are less than k centimeters remaining, than during this second processor smashes all the remaining potato. Vanya h...
1
def f(): n, h, k = map(int,raw_input().split()) a = map(int,raw_input().split()) rem = 0 it = 0 for x in a: d = h - rem s = (x - d) / k if s > 0: it += s rem -= s*k d = h - rem while d < x: rem = max(rem-k, 0) i...
You are given integers A and B, each between 1 and 3 (inclusive). Determine if there is an integer C between 1 and 3 (inclusive) such that A \times B \times C is an odd number. Constraints * All values in input are integers. * 1 \leq A, B \leq 3 Input Input is given from Standard Input in the following format: A...
3
a,b=map(int,input().split()) print("Yes" if (a%2==1 and b%2==1) else "No")
Let a be a matrix of size r × c containing positive integers, not necessarily distinct. Rows of the matrix are numbered from 1 to r, columns are numbered from 1 to c. We can construct an array b consisting of r + c integers as follows: for each i ∈ [1, r], let b_i be the greatest common divisor of integers in the i-th ...
3
a, b = map(int, input().split()) if a == 1 and b == 1: print(0) else: o1 = 0 o2 = 0 i1 = [] i2 = [] if a < b: i1.append(1) o1 = 1 else: i2.append(1) o2 = 1 for i in range(2, a + b + 1): if (o1 < a): o1 += 1 i1.append...
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. Input The f...
3
n = int(input()) array = list(map(int, input().split())) def construct_primes(): n = 10**6 + 1 primes = [True] * n p = 2 while p ** 2 <= n: if primes[p]: for i in range(p * p, n, p): primes[i] = False p += 1 return primes def check(n): sqrt = n ...
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters. In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? In...
3
for _ in range(int(input())): n=int(input()) s='' for _ in range(n): s=s+input() result=[s.count(i)%n for i in set(s)] if set(result)=={0}: print('YES') else: print('NO')
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory. George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living...
3
n=int(input()) m=0 for i in range(n): k,l=[int(x) for x in input().split(" ")] if (l-k)>1: m+=1 print(m)
We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list. Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n...
3
import math SIZE = 10 ** 6 + 5 flag = [True] * (SIZE + 5) primes = [] def seive(): flag[0] = flag[1] = False val = int(math.sqrt(SIZE) + 1) for i in range(2, val): if flag[i]: for j in range(i, SIZE): if i * j > SIZE: break flag[i ...
In order to celebrate Twice's 5th anniversary, Tzuyu and Sana decided to play a game. Tzuyu gave Sana two integers a and b and a really important quest. In order to complete the quest, Sana has to output the smallest possible value of (a ⊕ x) + (b ⊕ x) for any given x, where ⊕ denotes the [bitwise XOR operation](http...
3
t = int(input()) for turn in range(t): a, b = list(map(int, input().rstrip().split())) c = min(a,b) d = max(a,b) c1,d1 = '', '' while c>1: cmod = c%2 dmod = d%2 if cmod==1 and dmod==1: c1 = '0' + c1 d1 = '0' + d1 else: c1 = str(cmo...
Alice guesses the strings that Bob made for her. At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a. Bob builds b from a...
3
import sys import bisect as b import math from collections import defaultdict as dd input=sys.stdin.readline mo=10**9+7 def cin(): return map(int,sin().split()) def ain(): return list(map(int,sin().split())) def sin(): return input() def inin(): return int(input()) for _ in range(int(input()...
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
t = int(input()) for _ in range(t): s = input() n = min(s.count("1"), s.count("0")) print("DA" if n%2==1 else "NET")
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()) a = sorted([int(q) for q in input().split()]) s2 = 0 s = sum(a) for i in range(n): s2 += a[i] if s - s2 <= s2: print(n - i) break
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
w = input() lw = w.lower() uw = w.upper() ln = 0 un = 0 for i in range(len(w)): if w[i] != uw[i]: un += 1 if w[i] != lw[i]: ln += 1 if ln <= un: print(lw) else: print(uw)
Kris works in a large company "Blake Technologies". As a best engineer of the company he was assigned a task to develop a printer that will be able to print horizontal and vertical strips. First prototype is already built and Kris wants to tests it. He wants you to implement the program that checks the result of the pr...
3
n, m, k = map(int, input().split(' ')) row = [(0, -1)] * 5010 col = [(0, -1)] * 5010 for i in range(1, k+1): a, b, c = map(int, input().split(' ')) if a == 1: row[b] = (c, i) else: col[b] = (c, i) for i in range(1, n+1): for j in range(1, m+1): if row[i][1] > col[j][1]: ...
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
# -*- coding: utf-8 -*- """ Created on Fri Oct 23 18:15:08 2020 @author: 17831 """ n = int(input()) color = input() num = 0 for i in range(0,n-1): if color[i] == color[i+1]: num+=1 else: continue print(num)
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
a1,a2,a3=map(int,input().split()) a=int(pow(a1*a3/a2,0.5)) b=int(pow(a1*a2/a3,0.5)) c=int(pow(a2*a3/a1,0.5)) print(4*(a+b+c))
Today in the scientific lyceum of the Kingdom of Kremland, there was a biology lesson. The topic of the lesson was the genomes. Let's call the genome the string "ACTG". Maxim was very boring to sit in class, so the teacher came up with a task for him: on a given string s consisting of uppercase letters and length of a...
3
n = int(input()) s = input() t = 'ACTG' ans = 10**6 for i in range(n-3): x = s[i:i+4] cur = 0 for j in range(4): dis = abs(ord(x[j]) - ord(t[j])) cur += min(dis, 26-dis) ans = min(ans, cur) print(ans)
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
1
t=raw_input() flag=0 for i in t: if(i=='H' or i=='Q' or i=='9'): print "YES" flag=1 break if(flag==0): print "NO"
You have a blackboard and initially only an odd number x is written on it. Your goal is to write the number 1 on the blackboard. You may write new numbers on the blackboard with the following two operations. * You may take two numbers (not necessarily distinct) already on the blackboard and write their sum on the ...
3
n = int(input()) out = [] if n>>1 & 1: out.append(str(n) + " + " + str(n)) #2*n out.append(str(2*n) + " ^ " + str(n)) # n>>1 & 1 = 0 n = ((2*n)^n) m = n.bit_length() - 1 a = n b = n for i in range(m): out.append(str(b) + " + " + (str(b))) b *= 2 out.append(str(a) + " + " + str(b)) c = a + b out....
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
3
n=int(input()) s='' i=1 while True: if len(s)>=1000: break s+=str(i) i+=1 print(s[n-1])
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
n,l=map(int,input().split(" ")) a=list(map(int,input().split(" "))) a=sorted(a) mx=0 for i in range(n-1): if((a[i+1]-a[i])>mx): mx=a[i+1]-a[i] mx=(mx)/2 x=a[0] y=l-a[n-1] ans=max(mx,x,y) print("%.10f" %ans)
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations: * eat exactly...
3
from sys import stdin for _ in range(int(stdin.readline().rstrip())): n =int(stdin.readline().rstrip()) a = list(map(int, stdin.readline().rstrip().split(" "))) b = list(map(int, stdin.readline().rstrip().split(" "))) min_a = min(a) min_b = min(b) t = 0 for i in range(n): t += max(a[...
Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example). You are given a string...
3
t = input() t1 = t.replace('a', '') if t1[:len(t1)//2:] == t1[len(t1)//2::]: if t[len(t) - 1] == 'a' and t.count('a') != len(t): print(':(') else: if t[len(t) - len(t1) // 2::].count('a') == 0: print(t[:len(t) - len(t1) // 2:]) else: print(':(') else: print(':...
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi...
1
from itertools import combinations from string import ascii_lowercase n = int(raw_input()) l = [] for i in range(n): l.append(raw_input()) res = map(lambda x: (set(x),len(x)), l) l = [(tuple(k),v) for (k,v) in filter(lambda (x,y): len(x) <= 2, res)] resd = {k:sum([i[1] for i in l if not set(i[0]) - set(k)]) for ...
Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns. The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`. From a road square, you can move to a horizontally or vertically adjacent ro...
3
from collections import deque import copy def BFS(sy,sx,xy_list): dist=[[-1]*w for i in range(h)] dist[sy][sx]=0 xy_list[sy][sx]='#' dq=deque() dq.append((sy,sx)) while dq: y,x=dq.popleft() for dy,dx in [[1,0],[-1,0],[0,1],[0,-1]]: ny=y+dy nx=x+dx if 0<=ny<h and 0<=nx<w and xy_list[ny][nx]!='#': ...
After the lessons n groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the i-th group consists of si friends (1 ≤ si ≤ 4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum nu...
3
n = int(input()) list_groupe = [int(s) for s in input().split(" ")] list_groupe.sort() #1 2 3 3 4 #1 1 2 2 3 3 4 4 n4 = list_groupe.count(4) n3 = list_groupe.count(3) n2 = list_groupe.count(2) n1 = list_groupe.count(1) g4 = n4 if n1 <= n3: g4 += n1 n3 -= n1 n1 = 0 g4 += n3 if n2 % 2 == 0: g4 += int(n2/2)...
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
qtd = int(input()) total = 0 maior = 0 for i in range(qtd): entrada = input().split() s = int(entrada[0]) e = int(entrada[1]) total -= s total += e if(total > maior): maior = total print(maior)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
t = int(input()) for _ in range(t): line = input() if line[-2:] == 'po': print('FILIPINO') if line[-4:] == 'desu' or line[-4:] == 'masu': print('JAPANESE') if line[-5:] == 'mnida': print('KOREAN')
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
3
def main(): import sys input = sys.stdin.readline from collections import defaultdict # any 2 points must have different position. # 時計回りに出力するようにしちゃったけど反時計のほうが数学的にいい?? def ConvexHull(point_list): pos2idx = {point_list[i]: i for i in range(len(point_list))} y_val = defaultdict(li...
There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct. There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for whi...
3
n = int(input()) a = [] d = {} for b in range(n): s = input() g = set() for i in range(len(s)): for k in range(i, len(s)): w = s[i:k + 1] if w in g: continue else: g.add(w) if w in d: d[w] += 1 ...
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: * it is up to a passenger to choose a plane to fly on; * if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs ...
3
# cook your dish here from sys import stdin, stdout import math from itertools import permutations, combinations from collections import defaultdict from bisect import bisect_left from bisect import bisect_right from collections import deque def L(): return list(map(int, stdin.readline().split())) def In(): ...
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...
3
n,m,k = map(int,input().split()) t = list(map(int,input().split())) tmp_sum = 0 wyn = 0 z = 0 for x in range(len(t)-1,-1,-1): if m == 0: break tmp_sum+=t[x] if x!=0: wyn+=1 if tmp_sum+t[x-1]>k: m-=1 tmp_sum = 0 else: if tmp_sum<=k: wyn+...
There is a building consisting of 10~000 apartments numbered from 1 to 10~000, inclusive. Call an apartment boring, if its number consists of the same digit. Examples of boring apartments are 11, 2, 777, 9999 and so on. Our character is a troublemaker, and he calls the intercoms of all boring apartments, till someone...
3
for i in range(int(input())): n=int(input()) if n==1: print(1) if n==11: print(3) if n==111: print(6) if n==1111: print(10) if n==2: print(11) if n==22: print(13) if n==222: print(16) if n==2222: print(20) if n==3: ...
Rudolf is on his way to the castle. Before getting into the castle, the security staff asked him a question: Given two binary numbers a and b of length n. How many different ways of swapping two digits in a (only in a, not b) so that bitwise OR of these two numbers will be changed? In other words, let c be the bitwise...
3
n = int(input()) a = input() b = input() x = [0]*4 for i, j in zip(a, b): x[2*int(i) + int(j)] += 1 print(x[0]*x[2] + x[0]*x[3] + x[1]*x[2])
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
n=int(input()) s=input() k=0 z=str() for i in range(1, n+1): k=k+i if k<=len(s): z=z+s[k-1] print(z)
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()) number_in_length = 0 number_in_width = 0 if n%a==0: number_in_length = int(n/a) else: number_in_length = int(n//a)+1 if m%a==0: number_in_width =int(m/a) else: number_in_width = int(m//a) +1 need = int(number_in_length * number_in_width) print(need)
Write a program which reads two integers a, b and an operator op, and then prints the value of a op b. The operator op is '+', '-', '*' or '/' (sum, difference, product or quotient). The division should truncate any fractional part. Constraints * 0 ≤ a, b ≤ 20000 * No divisions by zero are given. Input The input c...
1
while True: a,op,b = raw_input().split() a = int(a) b = int(b) if op == "+": print a+b elif op == "-": print a-b elif op == "*": print a*b elif op == "/": print a/b else : break
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 = input().split(' ') n = int(n) m = int(m) a = int(a) print(((m-1)//a+1)*((n-1)//a+1))
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob...
3
n=int(input()) cc,ca,cb=0,0,0 ans=1 a=list(map(int,input().split())) b=list(map(int,input().split())) for i,j in zip(a,b): if i==j and i==1: cc+=1 for i in a: if i==1: ca+=1 for j in b: if j==1: cb+=1 ca-=cc cb-=cc if ca ==0: print(-1) else: x=1 # ca-=1 # print(ca,cb) while x*ca<=cb: x+=1 if (ca*x)>...
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
n=int(input()) if n<=2 or n%2!=0: print("no") else: print("yes")
There is a robot in a warehouse and n packages he wants to collect. The warehouse can be represented as a coordinate grid. Initially, the robot stays at the point (0, 0). The i-th package is at the point (x_i, y_i). It is guaranteed that there are no two packages at the same point. It is also guaranteed that the point ...
3
import sys def getN(): return int(input()) def getNM(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getArray(intn): return [int(input()) for i in range(intn)] def input(): return sys.stdin.readline().rstrip() for _ in range(int(input())): ...
Recently a new building with a new layout was constructed in Monocarp's hometown. According to this new layout, the building consists of three types of apartments: three-room, five-room, and seven-room apartments. It's also known that each room of each apartment has exactly one window. In other words, a three-room apar...
3
# 01 - Number of apartments # # For given N, solve 3a + 5b + 7c = N for a,b,c non-negative integers. # # Brute force? After all, 1 <= N <= 1000. # # Iterate through multiples of 7 until too large. Then iterate through multiples of 5, # then test whether there is a solution for 3. # # Test for trivial solutions along th...
Vanya wants to pass n exams and get the academic scholarship. He will get the scholarship if the average grade mark for all the exams is at least avg. The exam grade cannot exceed r. Vanya has passed the exams and got grade ai for the i-th exam. To increase the grade for the i-th exam by 1 point, Vanya must write bi es...
3
# link: https://codeforces.com/problemset/problem/492/C import os, sys, heapq 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...
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
# -*- coding: utf-8 -*- import bisect import heapq import math import random import sys from collections import Counter, defaultdict, deque from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal from functools import lru_cache, reduce from itertools import combinations, combinations_with_replacement, product, permut...
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
s=[list(map(int, input().split())) for i in range(int(input()))] s.sort() d=0 for a,b in s: d=a if b<d else b print(d) # Made By Mostafa_Khaled
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
if __name__ == "__main__": a, b = tuple(map(int, input().split())) m, x = min(a, b), max(a, b) print(f'{m} {(x - m) // 2}')
You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1. Constraints * 1 ≤ X,Y ≤ 10^9 * X and Y are integers. Input Input is given from Standard Input in...
3
a, b = map(int, input().split()) print('-1' if a % b == 0 else a )
Anton likes to play chess, and so does his friend Danik. Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie. Now Anton wonders, who won more games, he or Danik? Help him determine this. Input The first line of the input contains a...
3
n=input() s=input() a,d=0,0 for i in s: if i =="A": a+=1 else: d+=1 if a>d: print("Anton") elif d>a: print("Danik") else: print("Friendship")
[3R2 - Standby for Action](https://www.youtube.com/watch?v=P2ZVC9aoiKo) Our dear Cafe's owner, JOE Miller, will soon take part in a new game TV-show "1 vs. n"! The game goes in rounds, where in each round the host asks JOE and his opponents a common question. All participants failing to answer are eliminated. The sho...
3
n = int(input()) s = 0 while n != 0: s += 1/n n -= 1 print(round(s, 8))
There are N cards placed face down in a row. On each card, an integer 1 or 2 is written. Let A_i be the integer written on the i-th card. Your objective is to guess A_1, A_2, ..., A_N correctly. You know the following facts: * For each i = 1, 2, ..., M, the value A_{X_i} + A_{Y_i} + Z_i is an even number. You ar...
3
from collections import deque N,M = map(int,input().split()) E = [[] for _ in range(N+1)] for i in range(M): x,y,z = map(int,input().split()) E[x].append(y) E[y].append(x) d = [-1]*(N+1) def dfs(start,num): q = deque([start]) d[start] = num while(q): v = q.pop() for s in E[v]: ...
You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion. All strings that can be obtained in this way can be evaluated as formulas. ...
3
S=input() ans=0 for i in range(2**(len(S)-1)): tmp=S[0] for j in range(len(S)-1): if (i>>j)&1:tmp+="+" tmp+=S[j+1] ans+=eval(tmp) print(ans)
Ashishgup and FastestFinger play a game. They start with a number n and play in turns. In each turn, a player can make any one of the following moves: * Divide n by any of its odd divisors greater than 1. * Subtract 1 from n if n is greater than 1. Divisors of a number include the number itself. The player...
3
import math def prime(n): for i in range(2,int(math.sqrt(n))+1): if(n%i==0): return False return True # cook your dish here T=int(input()) for _ in range(T): n=int(input()) count=0 if(n==1): print('FastestFinger') elif n%2!=0 or n==2: pri...
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
3
def pklk(n): s=n if (n==1): return(n) if (n==2): return(3) for i in range (2,n): s+=1+i*(n-i) return (s+1) n=int(input()) print(pklk(n))
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
if __name__ == "__main__": result_str = "" end = "it" conjunction = "that" n = int(input()) for i in range(1, n + 1): if i % 2 != 0: result_str += "I hate" else: result_str += "I love" if i + 1 != n + 1: result_str += " " + conjunction ...
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P. While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe...
3
from collections import Counter,defaultdict,deque #from heapq import * #from itertools import * #from operator import itemgetter #from itertools import count, islice #from functools import reduce #alph = 'abcdefghijklmnopqrstuvwxyz' #dirs = [[1,0],[0,1],[-1,0],[0,-1]] #from math import factorial as fact #a,b = [int(x)...
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
for _ in range(int(input())): n=int(input()) inp=sorted(list(map(int, input().split()))) while inp: print(inp.pop(len(inp)//2), end=" ") print()
Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). A...
1
import sys def ni(): return int(sys.stdin.readline()) def nia(n): data = sys.stdin.readline().split(' ') return [int(g) for g in data] def solve(): nums = ni() ra = nia(nums) sum = 0 xr = 0 for x in ra: xr = xr ^ x sum = sum + x ext = sum * 2 + xr nx = ext ^...
Try guessing the statement from this picture <http://tiny.cc/ogyoiz>. You are given two integers A and B, calculate the number of pairs (a, b) such that 1 ≤ a ≤ A, 1 ≤ b ≤ B, and the equation a ⋅ b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11)...
3
_ = int(input()) for ________________________ in range(_): a,b = map(int,input().split()) c = 0 i = 1 while((10**i)-1 <= b): c+=1 i+=1 print(a*c)
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them. Input The first line contains integ...
3
n = input() s = input() counter = 0 for i in range(len(s) - 1): if s[i + 1] == s[i]: counter += 1 print(counter)
In a coordinate system,There are 3 chocolate which will be placed at three random position (x1,y1),(x2,y2) and (x3,y3).Ramesh loves Chocolates. Ramesh always moves along a straight line. your task is to find out whether he can have all the chocolates. Input Format :- The first line of the input contains an integer T d...
1
def isHori(p1, p2): if p1.x == p2.x: return True def isVert(p1,p2): if p1.y == p2.y: return True def isDia(p1, p2): if abs(p1.x-p2.x) == abs(p1.y-p2.y): return True class Point: def __init__(self, x, y): self.x = x self.y = y tc = int(raw_input()) for i in range(tc): data = map(int, raw_input().stri...
PolandBall is playing a game with EnemyBall. The rules are simple. Players have to say words in turns. You cannot say a word which was already said. PolandBall starts. The Ball which can't say a new word loses. You're given two lists of words familiar to PolandBall and EnemyBall. Can you determine who wins the game, i...
3
n,m=map(int,input().split()) listm = [] listn = [] for i in range(0,n): listn.append(input()) for i in range(0,m): listm.append(input()) if n > m: print ("YES") elif n < m: print ("NO") else: cou = 0 for tmp in listn: if tmp in listm : cou = cou + 1; if cou%2 == 0: ...
A new delivery of clothing has arrived today to the clothing store. This delivery consists of a ties, b scarves, c vests and d jackets. The store does not sell single clothing items — instead, it sells suits of two types: * a suit of the first type consists of one tie and one jacket; * a suit of the second type ...
3
ties, scarves, vests, jackets, suit_1_cost, suti_2_cost = [int(input()) for _ in range(6)] result = 0 if suti_2_cost > suit_1_cost: n = min(scarves, vests, jackets) m = min(jackets - n, ties) else: m = min(ties, jackets) n = min(jackets - m, scarves, vests) print(m * suit_1_cost + n * suti_2_cost)
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: * Remove any two elements from a and append their sum to...
3
from math import sqrt,floor for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) o=[] e=[] for i in range(2*n): if l[i]&1: o.append(i) else: e.append(i) if len(o)&1: o.pop() e.pop() elif len(e)>=2: e.pop...
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n=int(input()) l=set([int(i) for i in input().split() if int(i)>0 ][1:]) m=set([int(i) for i in input().split() if int(i)>0 ][1:]) t=l|m if len(t)<n: print("Oh, my keyboard!") else: print("I become the guy.")
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
3
for i in range(int(input())): a,b,c,n = map(int,input().split(' ')) maxine = max(a,b,c) count = (n-(maxine-a)-(maxine-b)-(maxine-c)) if count >= 0 and count%3 == 0: print('YES') else: print('NO')
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi. As Petya is older, he wants to take the chores with complexity larger...
3
n,a,b=map(int,input().split()) l=list(map(int,input().split())) l.sort() c=0 l1=[] x,y,z,t=l[n-a-1],l[n-a]-1,l[b-1],l[b]-1 if(x>y or z>t): print('0') else: if(x==z): m=min(y,t) print(m-x+1) elif(x>z): if(x<=t): m=min(y,t) print(m-x+1) else: ...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
l=[] for i in range(int(input())): l.append(int(input())) c=1 for i in range(1,len(l)): if(l[i]*l[i-1]==10): c=c+1 print(c)
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
M, N = map(int, input().split()) area = M * N answer = area // 2 print(answer)
This year in Equestria was a year of plenty, so Applejack has decided to build some new apple storages. According to the advice of the farm designers, she chose to build two storages with non-zero area: one in the shape of a square and another one in the shape of a rectangle (which possibly can be a square as well). A...
3
n=int(input()) x=input(); a=[] a=x.split(" ") c={} for i in range(n): a[i]=int(a[i]) if(a[i] not in c): c[a[i]]=1 else: c[a[i]]+=1 c4,c2,c8,c6=0,0,0,0 for k in c.keys(): if c[k]>=8: c8+=1 elif c[k]>=6: c6+=1 elif c[k]>=4: c4+=1 elif c[k]>=2: c2+=1 # print(c); print(c2, c4, c6, c8) q=int(input()) for ...
Each month Blake gets the report containing main economic indicators of the company "Blake Technologies". There are n commodities produced by the company. For each of them there is exactly one integer in the final report, that denotes corresponding revenue. Before the report gets to Blake, it passes through the hands o...
1
class Span: def __init__(self, index, direction): self.index, self.direction = index, direction n, m = map(int, raw_input().split()) values = list(map(int, raw_input().split())) spans = n * [ None ] for index in range(m): direction, span = map(int, raw_input().split()) spans[span - 1] = Span(index, direction...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
n = int(input()) l = [] for i in range(n): l.append(input()) s = 1 for i in range(n-1): if l[i] != l[i + 1]: s += 1 else: continue print(s)
It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch. Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number...
3
from bisect import bisect_left,bisect n = int(input()) b = list(map(int,input().split())) s =0 t=[] for i in b: s+=i t.append(s) input() for j in map(int,input().split()): print(bisect_left(t,j)+1)
You are given two integers n and m. Calculate the number of pairs of arrays (a, b) such that: * the length of both arrays is equal to m; * each element of each array is an integer between 1 and n (inclusive); * a_i ≤ b_i for any index i from 1 to m; * array a is sorted in non-descending order; * array b ...
3
#only choosing def chs(n,i,md): deno = 1 for j in range(n,n-i,-1): deno*=j deno%=md nume = 1 for j in range(1,i+1): nume*=pow(j,md-2,md) nume%=md return (deno*nume%md) n,m = map(int, input().split()) mod = 10**9+7 print(chs(n+2*m-1,m*2,mod))
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o...
3
a=input() b=input() print( [max(len(a),len(b)) , -1, 0] [a==b])
Every year, hundreds of people come to summer camps, they learn new algorithms and solve hard problems. This is your first year at summer camp, and you are asked to solve the following problem. All integers starting with 1 are written in one line. The prefix of these line is "123456789101112131415...". Your task is to...
3
a = "".join([str(i) for i in range(1000)]) print(a[int(input())])
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
number = int(input()) passenger, hp = 0, 0 for m in range(number): a, b = map(int, input().split()) passenger -= a passenger += b if passenger > hp: hp = passenger print(hp)
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d...
3
n = int(input()) for _ in range(n): k, x = list(map(int, input().split())) print(x + (k - 1) * 9)
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m. Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f...
3
for _ in range(int(input())): n,m = list(map(int,input().split())) arr1 = list(map(int,input().split())) arr2 = list(map(int,input().split())) k = list(set(arr1) & set(arr2) ) if k: print("YES") print("1",k[0]) else: print("NO")
Andrewid the Android is a galaxy-famous detective. In his free time he likes to think about strings containing zeros and ones. Once he thought about a string of length n consisting of zeroes and ones. Consider the following operation: we choose any two adjacent positions in the string, and if one them contains 0, and ...
3
n=int(input()) s=input() c0,c1=0,0 for i in s: if(i=='1'): c1+=1 elif(i=='0'): c0+=1 k=(c1-c0)if(c1>c0)else(c0-c1) print(k)
Chef is going to participate in a new quiz show: "Who dares to be a millionaire?" According to the rules of the game, contestants must answer N questions. The quiz being famous for its difficulty, each question has 26 candidate answers, but only one of which is correct. Answers are denoted by capital Latin letters from...
1
n_test_cases = int(raw_input()) for i in range(0, n_test_cases): n_questions = int(raw_input()) answers = list(raw_input()) chef_answers = list(raw_input()) scores = [int(i) for i in raw_input().split()] # print n_questions # print answers # print chef_answers # print scores score = 0 for c_i, chef_answer...
You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum. Subsequence is a sequence that can be derived from another sequence by deletin...
1
n = input() m = map(int, raw_input().split()) p = [] n = [] soma = 0 for i in m: if(i>0): soma += i p.append(i) else: n.append(i) impar = 0 if(soma%2 == 0): p.sort() n.sort() i = 0 t=0 y=0 while(True): if(len(n)>0): t = (-1)*n.pop() if(i<len(p)): y = p[i] i += 1 if(y%2 != 0 an...
Dolphin is planning to generate a small amount of a certain chemical substance C. In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b. He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmac...
3
N, Ma, Mb = map(int, input().split()) INF = 10 ** 8 lst = [[INF] * 401 for i in range(401)] lst[0][0] = 0 for _ in range(N): a, b, c = map(int, input().split()) for i in range(400, a - 1, -1): for j in range(400, b - 1, -1): if lst[i- a][j - b] == INF: pass els...