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
import sys name = sys.stdin.readline().rstrip() freq = {} for c in name: if c in freq: freq[c] += 1 else: freq[c] = 1 if len(freq.keys()) % 2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators (<https://en.wikipedia.org/wiki/Seven-segment_display>). <image> Max starts to type all the values from a to b. After typing each number Max resets the calculator. Find t...
3
d = { '0':6 , '1':2 , '2':5 , '3':5 , '4':4 , "5":5 , '6':6 , '7':3 , '8':7 , '9':6 } a , b = map(int , input().split()) total = 0 for i in range(a , b+1): i = str(i) for j in i: total = total + d[j] print(total)
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
3
s,v1,v2,t1,t2 = list(map(int,input().split())) a = 2*t1+s*v1 b = 2*t2+s*v2 if a < b: print("First") elif a > b: print("Second") elif a == b: print("Friendship")
Little Elephant loves magic squares very much. A magic square is a 3 × 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15...
3
arr=[] s=0 for i in range(3): a=list(map(int,input().split())) arr.append(a) s+=sum(a) s=s//2 for i in range(3): arr[i][i]=s-sum(arr[i]) print(*arr[i])
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 itertools import accumulate n = int(input()) a = list(accumulate(int(i) for i in input().split())) indices = [None] j = 0 for i in range(1, a[n - 1] + 1): if i > a[j]: j += 1 indices.append(j + 1) input() for bi in (int(i) for i in input().split()): print(indices[bi])
Given is an integer S. Find a combination of six integers X_1,Y_1,X_2,Y_2,X_3, and Y_3 that satisfies all of the following conditions: * 0 \leq X_1,Y_1,X_2,Y_2,X_3,Y_3 \leq 10^9 * The area of the triangle in a two-dimensional plane whose vertices are (X_1,Y_1),(X_2,Y_2), and (X_3,Y_3) is S/2. We can prove that ther...
3
S = int(input()) v = 10**9 y = S//v + (S < 10**18) x = v*y - S print(0, 0, 10**9, 1, x, y)
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
s = input() A = ["A", "O", "Y", "E", "U", "I", "a", "o", "y", "e", "u", "i"] for i in s: if i in A: continue if i >= 'A' and i <= 'Z': print('.', chr(ord(i) + 32), sep = '', end = '') if i >= 'a' and i <= 'z': print('.', i, sep = '', end = '')
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
n = int(input()) a = list(map(int,input().split())) c = 0 k = 0 for i in a: if i > 0: c += i elif i == -1: c += i if c < 0: k += 1 c = 0 print(k)
You are given two integers n and k. Your task is to find if n can be represented as a sum of k distinct positive odd (not divisible by 2) integers or not. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 10^5) — the number of test cases. The next t lines...
3
for _ in range(int(input())): n,k=map(int,input().split()) if (k%2==1 and n%2==1) or (k%2==0 and n%2==0): if n>=k**2-1: print("YES") else: print("NO") else: print("NO")
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum. For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively. Calculate the answer for t values of n. Input The first line of...
3
'''input 2 4 1000000000 ''' from math import log for _ in range(int(input())): n = int(input()) print(n*(n+1)//2 - 2*(2**(int(log(n,2))+1)-1))
There are n shovels in Polycarp's shop. The i-th shovel costs i burles, that is, the first shovel costs 1 burle, the second shovel costs 2 burles, the third shovel costs 3 burles, and so on. Polycarps wants to sell shovels in pairs. Visitors are more likely to buy a pair of shovels if their total cost ends with severa...
3
import sys input = sys.stdin.buffer.readline n = input().strip() n2 = int(n) mx = str(n2 + n2 - 1) if mx.count('9') == len(mx): print(1) elif int(mx) < 9: print(n2*(n2-1)//2) else: ans = 0 mx = int(mx) nines = '9'*(len(str(mx)) - 1) for i in range(0,9): curr = int(str(i) + nines) ...
"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
import string n, k = map(int, input().split()) a = [] a = input().split() a = [int(s) for s in a] passed = 0 min_score = a[k-1] a.sort() for score in a: if score >= min_score and score > 0: passed += 1 print(passed)
Now it's time of Olympiads. Vanya and Egor decided to make his own team to take part in a programming Olympiad. They've been best friends ever since primary school and hopefully, that can somehow help them in teamwork. For each team Olympiad, Vanya takes his play cards with numbers. He takes only the cards containing ...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin....
For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 ...
3
count=0 def merge(A,left,mid,right): global count L=A[left:mid]+[10**9+1] R=A[mid:right]+[10**9+1] i=0 j=0 for k in range(left,right): if L[i]<R[j]: A[k]=L[i] i+=1 else: A[k]=R[j] j+=1 count+=(mid-left-i) def me...
You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m. For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb...
3
I=input t=int(I()) for i in range(t): n=int(I()) ar=[int(x) for x in I().split()] m=[0]*(n+1) ans="" for j in range(n): m[ar[j]]=j mx,mn=0,n for j in range(1,n+1): mx=max(m[j],mx) mn=min(m[j],mn) l=mx-mn+1 if l==j: ans+='1' else : ...
A group of people played a game. All players had distinct scores, which are positive integers. Takahashi knows N facts on the players' scores. The i-th fact is as follows: the A_i-th highest score among the players is B_i. Find the maximum possible number of players in the game. Constraints * 1 \leq N \leq 10^5 * 1...
3
N=int(input()) A=[0]*N B=[0]*N for i in range(N): A[i],B[i] = map(int,input().split()) A_max=max(A) B_min=min(B) print(A_max + B_min)
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
1
#!/usr/bin/python # -*- coding: UTF-8 -*- import math n=int(input()) arr=map(int, raw_input().split()); for i in range(0,n): if arr[i]==1: l=i; if arr[i]==n: r=i; if (r<l): l,r=r,l; ans=max(r-0,n-1-l); print(ans);
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
3
N = int(input()) a = [] for i in range(2): a.append(list(map(int, input().split()))) dp = [[0] * 2 for _ in range(N)] for i in range(2): dp[0][i] = a[i][0] #1番目から始めたものと2番目から始めたものの最大値を比べる for i in range(N): for j in range(2): if i % 2 == 0: if i >= 1: dp[i][j] = max...
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ...
3
n = int(input()) s = input() a = 0 for i in range(1,n): a = max(a,len(set(s[:i+1]) & set(s[i+1:]))) print(a)
Alice and Bob have received three big piles of candies as a gift. Now they want to divide these candies as fair as possible. To do this, Alice takes one pile of candies, then Bob takes one of the other two piles. The last pile is split between Alice and Bob as they want: for example, it is possible that Alice takes the...
1
n = int(raw_input()) for i in range(n): l = map(int,raw_input().split()) x = 0 for j in l: x+=j print x/2
You are given an array a_1, a_2, ... , a_n, which is sorted in non-decreasing order (a_i ≤ a_{i + 1}). Find three indices i, j, k such that 1 ≤ i < j < k ≤ n and it is impossible to construct a non-degenerate triangle (a triangle with nonzero area) having sides equal to a_i, a_j and a_k (for example it is possible to...
3
t=int(input()) for _ in range(t): n=int(input()) a=list(map(int,input().split())) if a[0]+a[1]<=a[-1]: print(1,2,n) else: print(-1) """ 3 7 4 6 11 11 15 18 20 4 10 10 10 11 3 1 1 1000000000 --------------- 2 3 6 -1 1 2 3 """
Vus the Cossack has n real numbers a_i. It is known that the sum of all numbers is equal to 0. He wants to choose a sequence b the size of which is n such that the sum of all numbers is 0 and each b_i is either ⌊ a_i ⌋ or ⌈ a_i ⌉. In other words, b_i equals a_i rounded up or down. It is not necessary to round to the ne...
1
n = input() a = [] s = 0 for i in range(n): t = raw_input() f = 0 if t[0] == '-': f = 1 t = map(int,t.strip().split('.')) if f and t[1] != -0: t[0] -= 1 t[1] = 100000 - t[1] # print t a.append(t) s += t[1] c = s/100000 i = 0 while c>0: if a[i][1] != 0: a[i][0] += 1 c -= 1 i += 1 for i in a: print i...
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
from math import ceil [a,b,c]=map(float,input().split()) print(ceil(a/c)*ceil(b/c))
You are given string s. Your task is to determine if the given string s contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order). Input The only line of input contains a string s of length between 1 and 105 consisting of uppercase Latin letters. Output Print "YES" (without the quot...
3
# -*- coding: utf-8 -*- s = input() if not('AB' in s): print('NO') else: if not ('BA' in s.replace('AB', ' ', 1)): if 'BA' in s: if not ('AB' in s.replace('BA', ' ', 1)): print('NO') else: print('YES') else: print('NO') el...
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
3
from collections import deque n,k=map(int,input().split()) a=[int(i) for i in input().split()] b=deque([0]*k) c=set() nul=k for i in a: if i not in c: if b[-1]!=0: c.remove(b[-1]) else: nul-=1 b.appendleft(i) b.pop() c.add(i) print(k-nul) for i in...
Today Patrick waits for a visit from his friend Spongebob. To prepare for the visit, Patrick needs to buy some goodies in two stores located near his house. There is a d1 meter long road between his house and the first shop and a d2 meter long road between his house and the second shop. Also, there is a road of length ...
3
a,b,c=map(int,input().split()) print(min((2*a+2*b),a+b+c,(2*a+2*c),(2*b+2*c)))
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
1
''' Created on Nov 23, 2014 @author: nikolaoskyrtatas ''' if __name__ == '__main__': n = int(raw_input()) skills = [int(x) for x in raw_input().split()] a = [[], [], []] for i, skill in enumerate(skills): a[skill-1].append(i+1) res = list(zip(a[0], a[1], a[2])) print len(res) if re...
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
#!/usr/bin/env python3 from sys import stdin, stdout, setrecursionlimit import math def get_int(): return int(stdin.readline().strip()) def get_ints(): return map(int, stdin.readline().strip().split()) def get_string(): return stdin.readline().strip() def get_list(): return list(map(int, stdin....
Let's define a number ebne (even but not even) if and only if its sum of digits is divisible by 2 but the number itself is not divisible by 2. For example, 13, 1227, 185217 are ebne numbers, while 12, 2, 177013, 265918 are not. If you're still unsure what ebne numbers are, you can look at the sample notes for more clar...
3
import os import sys debug = True if debug and os.path.exists("input.in"): input = open("input.in", "r").readline else: debug = False input = sys.stdin.readline def inp(): return (int(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return s[:len...
Given is a positive integer N. Consider repeatedly applying the operation below on N: * First, choose a positive integer z satisfying all of the conditions below: * z can be represented as z=p^e, where p is a prime number and e is a positive integer; * z divides N; * z is different from all integers chosen in previous...
3
from math import floor from math import sqrt N = int(input()) def f(x): return (floor((-1+sqrt(1+8*x))/2.0)) ans = 0 i = 2 while N > 1: x = 0 while N % i == 0: N = N // i x = x + 1 if x != 0: ans = ans + f(x) i = i + 1 if i > 10 ** 6: ans = ans + 1 break print(ans)
There are two rival donut shops. The first shop sells donuts at retail: each donut costs a dollars. The second shop sells donuts only in bulk: box of b donuts costs c dollars. So if you want to buy x donuts from this shop, then you have to buy the smallest number of boxes such that the total number of donuts in them ...
3
t = int(input()) for _ in range(t): a, b, c = map(int, input().split()) if(a < c): d = 1 else: d = -1 if(a*b <= c): e = -1 else: e = b print("{} {}".format(d, e))
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
s1=input() s2=input() for i in range(len(s1)): if s1[i]==s2[i]: print('0',end='') else: print('1',end='')
AtCoDeer the deer is going on a trip in a two-dimensional plane. In his plan, he will depart from point (0, 0) at time 0, then for each i between 1 and N (inclusive), he will visit point (x_i,y_i) at time t_i. If AtCoDeer is at point (x, y) at time t, he can be at one of the following points at time t+1: (x+1,y), (x-1...
3
N=int(input()) t,x,y=0,0,0 for i in range(N): T,X,Y=map(int,input().split()) r=abs(X-x)+abs(Y-y) t=T-t if r%2!=t%2 or t<r: print('No') exit() t=T;x=X;y=Y print('Yes')
Some natural number was written on the board. Its sum of digits was not less than k. But you were distracted a bit, and someone changed this number to n, replacing some digits with others. It's known that the length of the number didn't change. You have to find the minimum number of digits in which these two numbers c...
3
k=int(input()) n=list(map(int,input().rstrip())) tot=sum(n) n.sort() count=0 if tot<k: for i in n: tot+=9-i count+=1 if tot>=k: break print(count)
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a system of equations: <image> You should count, how many there are pai...
3
n,m=map(int,input().split()) count=0 x=min(n,m) for b in range(x*x+1): a=x-b*b if a*a+b==max(n,m) and a>=0 : count+=1 print(count)
There are two sisters Alice and Betty. You have n candies. You want to distribute these n candies between two sisters in such a way that: * Alice will get a (a > 0) candies; * Betty will get b (b > 0) candies; * each sister will get some integer number of candies; * Alice will get a greater amount of candie...
3
t=int(input()) while t: t-=1 n=int(input()) if(n&1): print(n//2) else: print(n//2-1)
You have n coins, each of the same value of 1. Distribute them into packets such that any amount x (1 ≤ x ≤ n) can be formed using some (possibly one or all) number of these packets. Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve...
3
n=int(input()) i,c=1,0 while i<=n: i*=2 c+=1 print(c)
There is an N-car train. You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back." Constraints * 1 \leq N \leq 100 * 1 \leq i \leq N Input Input is given from Standard Input in the following format: N i O...
3
N,i=input().split() a=int(N) b=int(i) print(a+1-b)
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices. You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi...
3
rng = int(input()) instr = list(input().lower()) chars = [] for i in range(26): chars.append(0) for char in range(rng): chars[ord(instr[char])-97] += 1 isyes = True for i in range(26): if chars[i] == 0: print('NO') isyes = False break if isyes: print('YES')
You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can par...
1
from __future__ import division import sys from collections import namedtuple #x=namedtuple('point','x y') from math import * from collections import deque, OrderedDict #append #popleft from fractions import gcd from copy import copy ,deepcopy from collections import Counter #Counter(list) import re #re.split("[^a-zA-Z...
We will call a string that can be obtained by concatenating two equal strings an even string. For example, `xyzxyz` and `aaaaaa` are even, while `ababab` and `xyzxy` are not. You are given an even string S consisting of lowercase English letters. Find the length of the longest even string that can be obtained by delet...
3
s = list(input()) while s: s.pop() l = len(s) if s[:l//2]*2 == s: break print(l)
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
3
n,m = map(int,input().split()) a = list(map(int,input().split())) seen = [0]*100001 ans = [0] a = a[::-1] for i in range(n): ans.append(ans[-1]) if not seen[a[i]]: seen[a[i]] = 1 ans[-1] += 1 answer = '' for i in range(m): answer += str(ans[-int(input())])+'\n' print(answer)
In Absurdistan, there are n towns (numbered 1 through n) and m bidirectional railways. There is also an absurdly simple road network — for each pair of different towns x and y, there is a bidirectional road between towns x and y if and only if there is no railway between them. Travelling to a different town using one r...
3
n,m = map(int, input().split()) railway = [[] for i in range(n+1)] roads = [[] for i in range(n+1)] railway_direct = False for i in range(m): u,v = map(int,input().split()) if((u == 1 and v == n) or (u == n and v == 1)): railway_direct = True railway[u].append(v) railway[v].append(u) for i i...
Constraints * All values in input are integers. * 1\leq N, M\leq 12 * 1\leq X\leq 10^5 * 1\leq C_i \leq 10^5 * 0\leq A_{i, j} \leq 10^5 Input Input is given from Standard Input in the following format: N M X C_1 A_{1,1} A_{1,2} \cdots A_{1,M} C_2 A_{2,1} A_{2,2} \cdots A_{2,M} \vdots C_N A_{N,1} A_{N,2} \cdots A_{...
3
N,M,X=map(int,input().split()) B=[list(map(int,input().split())) for _ in range(N)] inf=(10**5)*12+1 ans=inf for i in range(1,2**N): tmp=[0]*M c=0 for j in range(N): if i>>j&1: for k in range(M): tmp[k]+=B[j][k+1] c+=B[j][0] if len([i for i in tmp if i>=X])==M: ans=min(c,ans) print(a...
Hooray! Polycarp turned n years old! The Technocup Team sincerely congratulates Polycarp! Polycarp celebrated all of his n birthdays: from the 1-th to the n-th. At the moment, he is wondering: how many times he turned beautiful number of years? According to Polycarp, a positive integer is beautiful if it consists of ...
3
n = int(input()) for _ in range(n): i = str(int(input())) s = 0 s += (len(i) - 1) * 9 for u in range(1, 10): if i >= str(u)*len(i): s += 1 else: break print(s)
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
s = input() k=0 b = 0 for i in range(len(s)): if s[i].islower(): k+=1 else: b+=1 if k>=b: s=s.lower() else: s = s.upper() print(s)
Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once. You are given the sequence A and q questions where each question contains Mi. Notes You can solve this problem by a Burte Force appro...
1
#!/usr/bin/env python from __future__ import division, print_function from sys import stdin from itertools import combinations def enum_sum_numbers(sets, s_range, r): for cmb in combinations(sets, r): yield sum(cmb) if r <= s_range: for s in enum_sum_numbers(sets, s_range, r+1): yi...
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()) a = [] for i in range(n): a.append([int(j) for j in input().split()]) count = 0 for row in a: if row.count(1) > 1: count += 1 print(count)
You are given a grid with 2 rows and 3 columns of squares. The color of the square at the i-th row and j-th column is represented by the character C_{ij}. Write a program that prints `YES` if this grid remains the same when rotated 180 degrees, and prints `NO` otherwise. Constraints * C_{i,j}(1 \leq i \leq 2, 1 \leq...
3
C=input()+input() print("YNEOS"[1 in[1 for i in range(3)if C[i]!=C[-i-1]]::2])
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
line = input() n, k = [int(x) for x in line.strip().split(" ")] for i in range(k): if n % 10: n -=1 else: n /= 10 print(int(n))
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i. We will write a positive integer on each vertex in T and calculate our score as follows: * On each edge, write the smaller of the integers writ...
3
N = int(input()) AB = [list(map(int,input().split())) for _ in [0]*(N-1)] *C, = sorted(map(int,input().split())) print(sum(C[:-1])) E = [[] for _ in [0]*N] d = [0]*N for a,b in AB: E[a-1].append(b-1) E[b-1].append(a-1) for i in range(N): if len(E[i])>1:break q = [i] while q: i = q.pop() d[i] = C.po...
Takahashi and Aoki will play a game on a tree. The tree has N vertices numbered 1 to N, and the i-th of the N-1 edges connects Vertex a_i and Vertex b_i. At the beginning of the game, each vertex contains a coin. Starting from Takahashi, he and Aoki will alternately perform the following operation: * Choose a vertex ...
3
import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline n = int(input()) graph = [[] for _ in range(n)] for i in range(n-1): a, b = map(int, input().split()) a -= 1 b -= 1 graph[a].append(b) graph[b].append(a) def dfs(v, dist, memo): memo[v] = dist for nv in graph[v]: i...
You have a given integer n. Find the number of ways to fill all 3 × n tiles with the shape described in the picture below. Upon filling, no empty spaces are allowed. Shapes cannot overlap. <image> This picture describes when n = 4. The left one is the shape and the right one is 3 × n tiles. Input The only line cont...
3
R = lambda: map(int, input().split()) n = int(input()) dp = [1] + [0] * 100 for i in range(1, 61): dp[i] = dp[i - 2] * 2 print(dp[n])
You and your friend are playing the game Mortal Kombat XI. You are trying to pass a challenge tower. There are n bosses in this tower, numbered from 1 to n. The type of the i-th boss is a_i. If the i-th boss is easy then its type is a_i = 0, otherwise this boss is hard and its type is a_i = 1. During one session, eith...
3
from sys import stdin, stdout import math,sys,heapq from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict from os import path import random import bisect as bi def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #------------------Sublime-----...
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
# cook your dish here for _ in range(int(input())): print(int(input()))
Snuke built an online judge to hold a programming contest. When a program is submitted to the judge, the judge returns a verdict, which is a two-character string that appears in the string S as a contiguous substring. (The judge can return any two-character substring of S.) Determine whether the judge can return the ...
3
S = input() for s, ns in zip(S, S[1:]): if s + ns == "AC": print("Yes") exit() print("No")
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
from heapq import heappush, heappop, heapify from collections import deque, defaultdict, Counter import itertools from itertools import permutations, combinations, accumulate import sys import bisect import string import math import time def I(): return int(input()) def MI(): return map(int, input().split()) def ...
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
""" n = int(input()) total = 0 for i in range(n): a,b,c = [int(c) for c in input().split()] if (a+b+c > 1): total += 1 print(total) import math input() s = [int(c) for c in input().split()] n = [0,0,0,0] for g in s: n[g-1] += 1 total = n[3] #all 4 are there n[0] = max(0, n[0] - n[2]) #put 1 to...
A bracket sequence is a string that is one of the following: 1. An empty string; 2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ; 3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B / Given are N strings S_i. Can a bracket sequence be forme...
3
def f(): N = int(input()) UP = [] DOWN = [] for _ in range(N): S = input() c = 0 minC = 0 for s in S: if s == '(': c += 1 else: c -= 1 minC = min(minC, c) if c >= 0: UP.append(...
Input The only line of the input contains a 7-digit hexadecimal number. The first "digit" of the number is letter A, the rest of the "digits" are decimal digits 0-9. Output Output a single integer. Examples Input A278832 Output 0 Input A089956 Output 0 Input A089957 Output 1 Input A1440...
3
s=input() k=int(s,16) print(k%2)
For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a...
3
for _ in[0]*int(input()): X,z=input(),[] for y in input(): s=i=0 for k in z: t=X.find(y,s)+1 if t<1:break z[i]=min(t,k) s=k;i+=1 else: t=X.find(y,s)+1 if t:z+=[t] print(len(z))
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array. Input The first line contains t...
3
n1, n2 = map(int, input().split()) k, m = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) print("YES" if max(a[0:k]) < min(b[-m:n2]) else "NO")
A wise man told Kerem "Different is good" once, so Kerem wants all things in his life to be different. Kerem recently got a string s consisting of lowercase English letters. Since Kerem likes it when things are different, he wants all substrings of his string s to be distinct. Substring is a string formed by some num...
3
n = int(input()) s = input() if n > 26: print (-1) else: dic = {} nr = 0 for c in s: if (dic.get(c) != None): nr += 1 else: dic[c] = 1 print(nr)
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
#!/usr/bin/env python3 # Headers import os # Input Get_In = str(input()) # Finding the lower characters as well as upper characters Count_Upper = [char for char in Get_In if char.isupper()] Count_Small = [char for char in Get_In if char.islower()] if len(Count_Upper) > len(Count_Small): print(Get_In.upper()) elif ...
There is a rectangle in a coordinate plane. The coordinates of the four vertices are (0,0), (W,0), (W,H), and (0,H). You are given a point (x,y) which is within the rectangle or on its border. We will draw a straight line passing through (x,y) to cut the rectangle into two parts. Find the maximum possible area of the p...
3
W, H, x, y = map(int, input().split()) print(W*H/2, 1 if (x == W/2) & (y == H/2) else 0)
The only difference between easy and hard versions is constraints. You are given n segments on the coordinate axis OX. Segments can intersect, lie inside each other and even coincide. The i-th segment is [l_i; r_i] (l_i ≤ r_i) and it covers all integer points j such that l_i ≤ j ≤ r_i. The integer point is called bad...
3
import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify, nlargest from copy import deepcopy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin....
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
3
n = int(input()) s=list(map(int,input().split())) d=max(s) k=[] for i in s: if s.count(i)==2: k.append(i) if d%i!=0 : k.append(i) print(d,max(k))
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia...
1
import re input() print len(re.findall("(?=(xxx))",raw_input()))
You are given 4n sticks, the length of the i-th stick is a_i. You have to create n rectangles, each rectangle will consist of exactly 4 sticks from the given set. The rectangle consists of four sides, opposite sides should have equal length and all angles in it should be right. Note that each stick can be used in only...
3
from collections import Counter q = int(input()) for _ in range(q): n = int(input()) ds = sorted(map(int, input().split())) s = ds[0]*ds[-1] for i in range(n): if ds[2*i] == ds[2*i+1] and ds[-1-2*i] == ds[-2-2*i] and ds[2*i]*ds[-1-2*i] == s: continue else: print(...
Creatnx has n mirrors, numbered from 1 to n. Every day, Creatnx asks exactly one mirror "Am I beautiful?". The i-th mirror will tell Creatnx that he is beautiful with probability (p_i)/(100) for all 1 ≤ i ≤ n. Some mirrors are called checkpoints. Initially, only the 1st mirror is a checkpoint. It remains a checkpoint ...
3
n = int(input()) a = list(map(int,input().split())) mod = 998244353 rng = 1100 inv = [0,1] for i in range(2,rng): inv.append(pow(i,mod-2,mod)) acc = [0]*n acc[-1] = 100*inv[a[-1]] for i in range(n-1)[::-1]: acc[i] = acc[i+1]*100*inv[a[i]]%mod print(sum(acc)%mod)
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
n=int(input()) a=list(map(int,input().split())) m=int(input()) b=list(map(int,input().split())) l=[] l.append(a[0]) for i in range(1,n): l.append(l[i-1]+a[i]) #print(l) s=0 ans=0 r=n-1 for i in b: s=0 ans=0 r=n-1 while s <= r: mid = (s+r) // 2 if l[...
Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network. Constraints * $2 \leq n \leq 100,000$ * $0 \leq m \leq 100,000$ * $1 \leq q \leq 10,000$ Input In the first line, two integer $n$ and $m$ are given. $n$ is the ...
3
import sys input = sys.stdin.readline from operator import itemgetter sys.setrecursionlimit(10000000) from collections import deque def main(): n, m = map(int, input().strip().split()) nei = [[] for _ in range(n)] for _ in range(m): s, t = map(int, input().strip().split()) nei[s].append(t) ...
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
x=input() if input()==x[::-1]: print("YES") else: print("NO")
Given this sequence….. 1^(1!)+2^(2!)+3^(3!)+4^(4!)+……………………..N^(N!). Your job is to write a program such that given N any time, you have to find out the unit place digit of the sum of the above sequence. Input Enter the number N to calculate the unit place digit of the sum of the above sequence 1 < N < 1000. ...
1
def factorial(k): if k > 4: k = 4 # specific code P = 1 for i in xrange(1,k+1): P *= i return P def process(N): S = 0 for i in xrange(1, N + 1): S += ((i % 10) ** factorial(i)) % 10 return S def main(): while True: N = raw_input() if N == '#': break ...
You are given a positive integer n. Let S(x) be sum of digits in base 10 representation of x, for example, S(123) = 1 + 2 + 3 = 6, S(0) = 0. Your task is to find two integers a, b, such that 0 ≤ a, b ≤ n, a + b = n and S(a) + S(b) is the largest possible among all such pairs. Input The only line of input contains a...
3
n = input() l = len(n) s= 0 if int(n) > 10: temp = int(n[0]) - 1 #print(len(n)) new_n = str(temp) chin = '9'*(int(l)-1) new_n = new_n + chin for i in new_n: s = s + int(i) conlai = int(n) - int(new_n) for i in str(conlai): s = s+ int(i) print(s) else: print(int(...
We have N boxes, numbered 1 through N. At first, box 1 contains one red ball, and each of the other boxes contains one white ball. Snuke will perform the following M operations, one by one. In the i-th operation, he randomly picks one ball from box x_i, then he puts it into box y_i. Find the number of boxes that may ...
3
n, m = map(int, input().split()) cnt = [1] * n red = [0] * n red[0] = 1 for _ in range(m): x, y = map(lambda x: int(x) - 1, input().split()) cnt[x] -= 1 cnt[y] += 1 if red[x]: red[y] = 1 if cnt[x] == 0: red[x] = 0 print(sum(red))
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...
3
#!/usr/bin/env python3 # -*- coding: utf-8 *-* n, k = map(int,input().split()) if n%2 == 0: if k <= n//2: print(2*k-1) else: print(2*(k-n//2)) else: if k <= (n+1)//2: print(2*k-1) else: print(2*(k-(n+1)//2))
Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in n different shops in the city. It's known that the price of one bottle in the shop i is equal to xi coins. Vasiliy plans to buy his favorite drink fo...
3
import time time0 = time.time() clock0 = time.clock() def find(m, lst, start, end): length = end-start+1 if length == 1: if m >= lst[start]: return start+1 return start z = start + length//2 if lst[z-1] <= m < lst[z]: return z elif m >= lst[z]: retur...
Given is a string S of length N. Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following: ...
3
n=int(input()) s=input() mx=0 for i in range(1,n): c=0 for j in range(n-i): if s[j]==s[j+i]: c+=1 mx=max(mx,c) if c==i: break else: c=0 print(mx)
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≤ x holds for each i (1 ≤ i ≤ n). Input The first line of input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. t blocks follow, each d...
3
for _ in range(int(input())): m,maxn=map(int,input().strip().split()) l1=list(map(int,input().strip().split())) l2=list(map(int,input().strip().split())) l1.sort() l2.sort(reverse=True) c=[each+every for each,every in zip (l1,l2)] if max(c)>maxn: print('No') else: print('Yes') try: useless=input() excep...
Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re...
3
def Server(): n = int(input()) aReached = 0 aLost = 0 bReached = 0 bLost = 0 for i in range(n): num, r, l = list(map(int, input().split())) if num == 1: aReached += r aLost += l else: bReached += r bLost += l if aReached >= aLost: print("LIVE") else: print("DEAD") if bReached >= bLost: ...
You and your friend are participating in a TV show "Run For Your Prize". At the start of the show n prizes are located on a straight line. i-th prize is located at position ai. Positions of all prizes are distinct. You start at position 1, your friend — at position 106 (and there is no prize in any of these two positi...
3
#938B n=int(input()) a=list(map(int,input().split())) b1=0;b2=1000000 for i in range(n): if a[i]<=(1000000//2): b1=a[i] else: i-=1 break for j in range(i+1,n): b2=a[j] break print(max(b1-1,1000000-b2))
Consider a sequence of digits of length 2^k [a_1, a_2, …, a_{2^k}]. We perform the following operation with it: replace pairs (a_{2i+1}, a_{2i+2}) with (a_{2i+1} + a_{2i+2})mod 10 for 0≤ i<2^{k-1}. For every i where a_{2i+1} + a_{2i+2}≥ 10 we get a candy! As a result, we will get a sequence of length 2^{k-1}. Less for...
3
n = int(input()) s = list(map(int, input().split())) q = int(input()) cand=[0] re = [0] total=0 tre=0 for i in range(n): total+=s[i] cand.append(total) tre += s[i]//10 re.append(tre) for _ in range(q): l, r = map(int, input().split()) k = cand[r]-cand[l-1] k = k//10 p = re[r]-re[l-1] ...
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters. Dwarf Mish...
1
import sys ri = lambda: raw_input().strip() #n = int(ri()) #a, b, c, d, e = map(int, ri().split()) first = ri() second = ri() if len(first) != len(second): print "NO" else: tmp = [] for x in xrange(len(first)): if first[x] != second[x]: tmp.append(x) if len(tmp) != ...
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
sent1 = list(input().split("+")) sent2 = sorted(sent1) st="" for i in sent2: st = st+'+'+i st1=st[1:] print(st1)
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not. You are given a string s of length n, consisting of digits. In one operation you can delete any character from strin...
3
for _ in range(int(input())): n=int(input()) p=input() k=-1 suc=1 for i in range(len(p)-1,-1,-1): if(p[i]=='8'): k=i if(k==-1): suc=0 elif(n-k<11): suc=0 if(suc!=0): print("YES") else: print("NO")
In 2020, AtCoder Inc. with an annual sales of more than one billion yen (the currency of Japan) has started a business in programming education. One day, there was an exam where a one-year-old child must write a program that prints `Hello World`, and a two-year-old child must write a program that receives integers A, B...
3
#9:25〜27 2min if int(input())==1: print("Hello World") else: print(int(input())+int(input()))
You are given an integer a that consists of n digits. You are also given a sequence of digits s of length m. The digit in position j (1 ≤ j ≤ m) of sequence s means that you can choose an arbitrary position i (1 ≤ i ≤ n) in a and replace the digit in the chosen position i with sj. Each element in the sequence s can par...
3
a=list(map(int,list(input()))) b=sorted(list(map(int,list(input())))) for i in range(len(a)): if len(b)==0: break if b[-1]>a[i]: a[i]=b.pop() ans="" for c in a: ans+=str(c) print(ans)
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k. In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w...
3
from collections import Counter,defaultdict,deque #import heapq as hq #import itertools #from operator import itemgetter #from itertools import count, islice #from functools import reduce #alph = 'abcdefghijklmnopqrstuvwxyz' #from math import factorial as fact #a,b = [int(x) for x in input().split()] #sarr = [x for x i...
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with n room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ro...
1
n = input() key = [0]*26 door = 0 s = raw_input() for i in xrange(n-1): k = s[2*i] d = s[2*i+1] key[ord(k)-97]+=1 if key[ord(d)-65]>0: key[ord(d)-65]-=1 else: door+=1 print door
[The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q) For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes. Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi...
3
x,y,z=list(map(int,input().split())) a,b,c=list(map(int,input().split())) if a>=x and (x+y)<=(a+b) and (x+y+z)<=(a+b+c): print("YES") else: print("NO")
Sheldon, Leonard, Penny, Rajesh and Howard are in the queue for a "Double Cola" drink vending machine; there are no other people in the queue. The first one in the queue (Sheldon) buys a can, drinks it and doubles! The resulting two Sheldons go to the end of the queue. Then the next in the queue (Leonard) buys a can, d...
3
n = int(input()) k = 1 p = 1 while 5*p<n: k*=2 p+=k r = (n - 5*p + 5*k - 1)//k C = ["Sheldon","Leonard","Penny","Rajesh","Howard"] print(C[r])
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
b=[] v=0 for i in range(5): b.append([]) b[i]=[int(s) for s in input().split()] for c in range(5): if b[c].count(1)==1: s=b[c].index(1) v=abs(2-c)+abs(2-s) print(v) break
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
for _ in range(int(input())): a, b, n, S = list(map(int, input().split())) if n*a == S: print("YES") elif n*a < S: # TODO if n*a +b >= S: print("YES") else: print("NO") elif a*n > S: x = S//n if x * n + b >= S: print("...
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()) l=[] for i in range (0,N): a=list(map(int,input().split())) l.append(a) s=0 for i in l: count=0 for k in i: if k==1: count+=1 if count>=2: s+=1 print(s)
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
input_word = input() exists = True for i, c in enumerate("hello"): if input_word.find(c) >= 0: input_word = input_word[input_word.index(c) + 1:] else: exists = False break print(exists and "YES" or "NO")
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...
3
a=(list(map(int, input().split()))) k=a[1] if a[0]%2==0: if k<=a[0]//2: print(2*a[1]-1) else: k-=a[0]//2 print(2*k) else: if k<=(a[0]//2+1): print(2*a[1]-1) else: k-=(a[0]//2+1) print(2*k)
There are n left boots and n right boots. Each boot has a color which is denoted as a lowercase Latin letter or a question mark ('?'). Thus, you are given two strings l and r, both of length n. The character l_i stands for the color of the i-th left boot and the character r_i stands for the color of the i-th right boot...
3
n=int(input()) a=input() b=input() a1 = [[]for i in range(26)] b1 = [[] for i in range(26)] q1=[] q2 = [] for i in range(n): if a[i]=='?': q1.append(i+1) else: a1[ord(a[i])-97].append(i+1) if b[i]=='?': q2.append(i+1) else: b1[ord(b[i])-97].append(i+1) ans=[] rest...
«Next please», — the princess called and cast an estimating glance at the next groom. The princess intends to choose the most worthy groom, this is, the richest one. Whenever she sees a groom who is more rich than each of the previous ones, she says a measured «Oh...». Whenever the groom is richer than all previous on...
1
def reads(func=None): return map(func, raw_input().split()) if func else raw_input().split() ################################ n, a, b = reads(int) def solve(): global a, b result = [1] for i in xrange(1, n): if b > 0: new = sum(result) + 1 if new > 50000: ...
We have a grid with H rows and W columns. The square at the i-th row and the j-th column will be called Square (i,j). The integers from 1 through H×W are written throughout the grid, and the integer written in Square (i,j) is A_{i,j}. You, a magical girl, can teleport a piece placed on Square (i,j) to Square (x,y) by...
3
import sys input = sys.stdin.readline h, w, d = map(int, input().split()) n = h*w place = [0]*n for i in range(h): a = [int(x) for x in input().split()] for j in range(w): place[a[j]-1] = (i, j) bit = [0]*n for i in range(n): if i < d: continue bit[i] = bit[i-d]+abs(place[i][0]-place[i-d][0])+abs(plac...