problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
3
l = list(map(int, input().strip().split())) n = l[0] m = l[1] k = l[2] if m >= n and k >= n: print("Yes") else: print("No")
Patrick has just finished writing a message to his sweetheart Stacey when he noticed that the message didn't look fancy. Patrick was nervous while writing the message, so some of the letters there were lowercase and some of them were uppercase. Patrick believes that a message is fancy if any uppercase letter stands to...
3
s=input() n=len(s) if all(i.isupper() for i in s): print(0) exit() if all(i.islower() for i in s): print(0) exit() pres=[0]*n pre=[0]*n if s[0].isupper(): pre[0]=1 else: pres[0]=1 for i in range(1,n): pre[i]=pre[i-1]+(s[i].isupper()) pres[i]=pres[i-1]+(s[i].islower()) mini=10**9 mini...
Dreamoon wants to climb up a stair of n steps. He can climb 1 or 2 steps at each move. Dreamoon wants the number of moves to be a multiple of an integer m. What is the minimal number of moves making him climb to the top of the stairs that satisfies his condition? Input The single line contains two space separated i...
3
nm=input().split() n=int(nm[0]) m=int(nm[1]) k=0 if n<m: print(-1) elif n==m and n==1: print(1) else: if n%2==0: k=n//2 else: k=n//2+1 while k%m!=0: k+=1 print(k)
The only difference between easy and hard versions is that you should complete all the projects in easy version but this is not necessary in hard version. Polycarp is a very famous freelancer. His current rating is r units. Some very rich customers asked him to complete some projects for their companies. To complete ...
3
import sys input = sys.stdin.readline n, r = map(int, input().split()) l = [] for _ in range(n): l.append(list(map(int, input().split()))) p = 0 ans = 0 while (p < n): if l[p][0] <= r and l[p][1] >= 0: r += l[p][1] l = l[:p] + l[p + 1:] p = 0 n -= 1 ans += 1 else: p += 1 if l == []: print(ans) exit(0)...
Let's denote a k-step ladder as the following structure: exactly k + 2 wooden planks, of which * two planks of length at least k+1 — the base of the ladder; * k planks of length at least 1 — the steps of the ladder; Note that neither the base planks, nor the steps planks are required to be equal. For example...
3
# # Yet I'm feeling like # There is no better place than right by your side # I had a little taste # And I'll only spoil the party anyway # 'Cause all the girls are looking fine # But you're the only one on my mind import sys inf = float("inf") #sys.setrecursionlimit(1000000) # abc='abcdefghijklmnopq...
Vasya collects coins: he has exactly one coin for every year from 1 to n. Naturally, Vasya keeps all the coins in his collection in the order in which they were released. Once Vasya's younger brother made a change — he took all the coins whose release year dated from l to r inclusively and put them in the reverse order...
1
n=int(raw_input()) a=raw_input().split(" ") a=[int(v) for v in a] b=range(1,n+1) x=[] y=[] begin=0 end=0 for i in range(n): if a[i]!=b[i]: begin=i break for i in range(n-1,0,-1): if a[i]!=b[i]: end=i break x=a[begin:(end+1)] y=b[begin:(end+1)] x.reverse() if y==x and len(x)>1:...
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
1
n = int(raw_input()) for i in range(n): print ' '*(2*n-2*i-1), for j in range(i): print j, for j in range(i,0,-1): print j, print 0 for j in range(n): print j, for j in range(n,0,-1): print j, print 0 for i in range(1,n+1): print ' '*(2*i-1), for j in range(n-i): ...
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: <image>. The lucky number of the sequence of distinct positive integers x1, x2, ..., xk (k > 1) is t...
3
n = int(input()) li_t = list(map(int,input().split())) stk1 =[] ans = 0 for i in li_t: while stk1!=[]: if stk1[-1]<i: ans = max(ans,(stk1[-1]^i)) stk1.pop() else: ans = max(ans,(stk1[-1]^i)) break stk1.append(i) print(ans)
The only difference between easy and hard versions is constraints. A session has begun at Beland State University. Many students are taking exams. Polygraph Poligrafovich is going to examine a group of n students. Students will take the exam one-by-one in order from 1-th to n-th. Rules of the exam are following: *...
3
import math import sys #imgur.com/Pkt7iIf.png #n, m = map(int, input().split()) #n = int(input()) #d = list(map(int, input().split())) n, m = map(int, input().split()) t = list(map(int, input().split())) pt = [t[0]] for i in range(1, n): pt.append(pt[-1] + t[i]) print(0, end = ' ') for i in range(1,n): if...
2N players are running a competitive table tennis training on N tables numbered from 1 to N. The training consists of rounds. In each round, the players form N pairs, one pair per table. In each pair, competitors play a match against each other. As a result, one of them wins and the other one loses. The winner of the...
3
n,a,b=map(int,input().split()) if (a-b)%2==0: print((b-a)//2) else: print(min(a+(b-a-1)//2, n-b+1+(b-a-1)//2))
A coordinate line has n segments, the i-th segment starts at the position li and ends at the position ri. We will denote such a segment as [li, ri]. You have suggested that one of the defined segments covers all others. In other words, there is such segment in the given set, which contains all other ones. Now you want...
3
import math def main(): n = int(input()) m = [] for _ in range(n): x = list(map(int,input().split())) m.append(x) s = m[0][0] e = m[0][1] q = 0 for r in range(1,n): if m[r][0] <= s and (m[r][1] >= e): s = m[r][0] e = m[r][1] q = r ...
Takahashi is a user of a site that hosts programming contests. When a user competes in a contest, the rating of the user (not necessarily an integer) changes according to the performance of the user, as follows: * Let the current rating of the user be a. * Suppose that the performance of the user in the contest is b. ...
3
a=int(input()) b=int(input()) print((2*b)-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
g=int(input()) x=input() a=x.count("A") b=x.count("D") if a==b: print("Friendship") elif(a>b):print("Anton") else:print("Danik")
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
3
from math import * t=int(input()) while t: t=t-1 n,m=map(int,input().split()) c,d=map(int,input().split()) mn=min(n,m)+min(c,d) if mn==max(n,m) and mn==max(c,d): print("YES") else: print("NO") #n=int(input()) #a=list(map(int,input().split()))
In order to do some research, n^2 labs are built on different heights of a mountain. Let's enumerate them with integers from 1 to n^2, such that the lab with the number 1 is at the lowest place, the lab with the number 2 is at the second-lowest place, …, the lab with the number n^2 is at the highest place. To transpor...
3
n = int(input()) ans = [] for i in range(1, n+1): ans.append([i]) k = n+1 for i in range(1, n): for j in range(n): if i % 2 != 0: ans[n-1-j].append(k) k += 1 else: ans[j].append(k) k += 1 for i in range(n): print(*ans[i])
<image> A directed acyclic graph (DAG) can be used to represent the ordering of tasks. Tasks are represented by vertices and constraints where one task can begin before another, are represented by edges. For example, in the above example, you can undertake task B after both task A and task B are finished. You can obt...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- # # FileName: topological_sort # CreatedDate: 2020-05-18 14:33:31 +0900 # LastModified: 2020-05-18 14:50:54 +0900 # import os import sys #import numpy as np #import pandas as pd def main(): v,e = map(int,input().split()) path_list = [[] for _ in range(v)] ...
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...
1
n, m = map(int, raw_input().split()) print (n*m//2)
Snuke has decided to construct a string that starts with `A` and ends with `Z`, by taking out a substring of a string s (that is, a consecutive part of s). Find the greatest length of the string Snuke can construct. Here, the test set guarantees that there always exists a substring of s that starts with `A` and ends w...
1
# -*- coding: utf-8 -*- s = raw_input() start = 0 end = 0 for i,stri in enumerate(s): if stri == "A": start = i break for i,stri in enumerate(s[::-1]): if stri == "Z": end = i break print (len(s)-end)-start
A string t is called an anagram of the string s, if it is possible to rearrange letters in t so that it is identical to the string s. For example, the string "aab" is an anagram of the string "aba" and the string "aaa" is not. The string t is called a substring of the string s if it can be read starting from some posi...
1
r=raw_input s=r() p=r() v=[0]*(ord('z') - ord('?')+1) l=len(p) L=len(s) if l > L: print 0 exit() P=set() r=0 for i in range(l): k = ord(p[i])-ord('?') v[k] -=1 j = ord(s[i])-ord('?') v[j] +=1 if v[j] > 0 and j: P.add(j) if not v[k] and k and j != k: P.discard(k) #print ...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
ch=input() L=[] ch1='' for i in ch: L.append(i) L[0]=L[0].upper() ch1="".join(L) print(ch1)
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
t=int(input()) import math ls =[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79, 83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211, 223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353, 359,367,373,379,383,389,397,40...
Many students live in a dormitory. A dormitory is a whole new world of funny amusements and possibilities but it does have its drawbacks. There is only one shower and there are multiple students who wish to have a shower in the morning. That's why every morning there is a line of five people in front of the dormitory...
3
# coding: utf-8 import itertools g = [] for i in range(5): g.append([int(i) for i in input().split()]) permutations = list(itertools.permutations([0,1,2,3,4],5)) ans = -1 for per in permutations: tmp = (g[per[0]][per[1]]+g[per[1]][per[0]])*1\ + (g[per[1]][per[2]]+g[per[2]][per[1]])*1\ + (g[per[2...
You like playing chess tournaments online. In your last tournament you played n games. For the sake of this problem, each chess game is either won or lost (no draws). When you lose a game you get 0 points. When you win you get 1 or 2 points: if you have won also the previous game you get 2 points, otherwise you get 1 ...
3
for i in range(int(input())): n, k = map(int, input().split()) s = input() wins = s.count('W') + k if wins >= n: print(2 * n - 1) else: streaks = int(s[0] == 'W') + s.count('LW') or int(wins > 0) gaps = s.strip('L').replace('W', ' ').strip().split() for g in sorted(ma...
Carousel Boutique is busy again! Rarity has decided to visit the pony ball and she surely needs a new dress, because going out in the same dress several times is a sign of bad manners. First of all, she needs a dress pattern, which she is going to cut out from the rectangular piece of the multicolored fabric. The piec...
3
###################################################################### # Write your code here import sys #import resource #resource.setrlimit(resource.RLIMIT_STACK, [0x10000000, resource.RLIM_INFINITY]) #sys.setrecursionlimit(0x100000) # Write your code here # For getting input from input.txt file # sys.stdin = open('...
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word. Note, that during capitalization all the letters except the first one remains unchanged. Input A single line contains a non-empty word. This word consists of lowercase and uppercase English letters....
3
palabra = input() l = list(palabra) x = l[0].upper() new = palabra[1:] newWord = x + new print(newWord)
Navi got a task at school to collect N stones. Each day he can collect only one stone. As N can be a very large number so it could take many days to complete the task, but then he remembers that his mother gave him a magic that can double anything (i.e if he has 2 stones, the magic will make them to 4 stones). Navi ...
1
x=input() for i in range(x): y=input() c=0 while y!=0: if y%2==0: y/=2 else: y-=1 c+=1 print c
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O...
3
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 20:26:50 2019 @author: zheng """ g=list(input()) h=list(input()) bad=list(input()) a=g+h a.sort() n=len(a) bad.sort() if len(bad)!=len(a): print('NO') else: if all(a[i]==bad[i] for i in range(n)): print('YES') else: print('NO') ...
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. Input The first line contai...
1
n = int(raw_input()) m = int(raw_input()) a = [] for i in range(n): a.append(int(raw_input())) def qsort(a, l, r): bl, br = l, r if l >= r: return p = a[(l + r) // 2] while l <= r: while a[l] > p: l += 1 while a[r] < p: r -= 1 if l <= r: ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
name = input() myset = set(name) if len(myset) % 2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
3
def find_next(number): if(len(number) == 1): return int(number)+1 first = str(int(number[0]) + 1) output = first for x in range(0,len(str(number))-1) : output += '0' return output number = input() output = int(find_next(number)) - int(number) print(output)
Once Bob got to a sale of old TV sets. There were n TV sets at that sale. TV set with index i costs ai bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most m TV sets, and he ...
1
class Sale: def solve(self,n,m,arr): total =0 count = 0 for x in arr: if count==m: break else: if x>0:break total+=abs(x) count+=1 return total if __name__ == "__main__": n,m = map(int,raw_inp...
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them. Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu...
3
texto = input('').split('WUB') texto = [x for x in texto if x != ''] print(' '.join(texto))
You are given a string, consisting of lowercase Latin letters. A pair of neighbouring letters in a string is considered ugly if these letters are also neighbouring in a alphabet. For example, string "abaca" contains ugly pairs at positions (1, 2) — "ab" and (2, 3) — "ba". Letters 'a' and 'z' aren't considered neighbou...
3
T=int(input()) for i in range(0,T): s=input() temp=0 pos=[0]*26 for j in range(0,len(s)): pos[ord(s[j])-97]=pos[ord(s[j])-97]+1 #print(pos) st='' L1=[] L2=[] """for j in range(0,len(pos),2): st=st+chr(j+97)*pos[j] for j in range(1,len(pos),2): ...
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
l = [] m = int(input()) for i in range(m): if i % 2 is 0: l.append('hate') else: l.append('love') x = ' that '.join(['I ' + i for i in l]) + ' it' print(x)
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and ...
3
n,a,b=map(int,input().split()) f=n-a if(f<=b): print(f) else: (print(b+1))
An n × n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n = int(input()) a = [] for i in range(n): a.append([]) for j in range(n): if j == 0 or i == 0: a[i].append(1) else: a[i].append(a[i][j-1]+ a[i-1][j]) print(a[n-1][n-1])
You are given an array a consisting of n integers a_1, a_2, ... , a_n. In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],...
3
for i in range(int(input())): x = int(input()) y = [int(i) for i in input().split()] a = 0 b = 0 c = 0 for i in range(x): if y[i]%3 != 0: if y[i]%3 == 2: a += 1 else: b += 1 y[i] = y[i]%3 else: y[i] =...
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even. He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh...
3
t=int(input()) for T in range(t): n=int(input()) sum1=2**n sum2=2**(n-1) for i in range((n-2)//2): if(sum1>=sum2): sum1+=2**(i+1) sum2+=2**(n-2-i) print(abs(sum1-sum2))
Snuke has one biscuit and zero Japanese yen (the currency) in his pocket. He will perform the following operations exactly K times in total, in the order he likes: * Hit his pocket, which magically increases the number of biscuits by one. * Exchange A biscuits to 1 yen. * Exchange 1 yen to B biscuits. Find the maxi...
3
N,A,B = list(map(int,input().split())) another=1+1*N ans =A N -= A-1 ans += N//2 * (B-A) ans += N%2 print(max(ans,another))
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 = int(input()) s = list(input()) tR = 0 tG = 0 tB = 0 for i in range(n-1): if s[i] == s[i+1]: if s[i] == 'R': tR += 1 elif s[i] == 'G': tG += 1 elif s[i] == 'B': tB += 1 print(tR+tG+tB)
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
1
n,k=raw_input().split(' ') n,k=int(n),int(k) a=map(int,raw_input().split(' ')) b=a[:] count=0 for i in range(0,n-1): sum=b[i]+b[i+1] if sum<k: b[i+1]=k-b[i] count+=b[i+1]-a[i+1] print count for i in range(0,n): print(b[i]),
You are given a grid with n rows and m columns, where each cell has a non-negative integer written on it. We say the grid is good if for each cell the following condition holds: if it has a number k > 0 written on it, then exactly k of its neighboring cells have a number greater than 0 written on them. Note that if the...
3
b = input() for _ in range(int(b)): c = input().split(" ") ans = [[0 for i in range(int(c[1]))] for i in range(int(c[0]))] dict = [] for i in range(int(c[0])): d = input().split(" ") for j in range(len(d)): ans[i][j] = int(d[j]) if(ans[i][j]!=0): d...
Vasya's bicycle chain drive consists of two parts: n stars are attached to the pedal axle, m stars are attached to the rear wheel axle. The chain helps to rotate the rear wheel by transmitting the pedal rotation. We know that the i-th star on the pedal axle has ai (0 < a1 < a2 < ... < an) teeth, and the j-th star on t...
3
n = int(input()) a = list(map(int, input().split())) m = int(input()) b = list(map(int, input().split())) arr = [0] for i in range(m): for j in range(n): if b[i] % a[j] == 0 and b[i]//a[j] >= max(arr): arr.append(b[i]//a[j]) ans = arr.count(max(arr)) print(ans)
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits. Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on...
3
n = int(input()) while True: n += 1 stringn = str(n) lista = list(stringn) used = [] prox = False for i in range(len(lista)): if lista[i] not in used: used.append(lista[i]) else: prox = True break if prox: continue print(n) ...
Several days ago you bought a new house and now you are planning to start a renovation. Since winters in your region can be very cold you need to decide how to heat rooms in your house. Your house has n rooms. In the i-th room you can install at most c_i heating radiators. Each radiator can have several sections, but ...
3
for _ in range(int(input())): c, s = map(int, input().split()) if s < c: print(s) else: div = s//c mod = s % c ans = pow((div + 1), 2) * mod ans += pow(div, 2) * (c-mod) print(ans)
A mad scientist Dr.Jubal has made a competitive programming task. Try to solve it! You are given integers n,k. Construct a grid A with size n × n consisting of integers 0 and 1. The very important condition should be satisfied: the sum of all elements in the grid is exactly k. In other words, the number of 1 in the gr...
3
T = int(input()) for t in range(T): n, k = (int(i) for i in input().split()) a = [[0 for j in range(n)] for i in range(n)] i, j = 0, 0 if k > 0: a[i][j] = 1 for l in range(k - 1): j += 1 if j == n: j = 0 i += 1 if i == n: i = 0 ...
Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk. Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a...
1
# Enter your code here. Read input from STDIN. Print output to STDOUT from sys import stdin n,k = map(int,stdin.readline().split()) a = map(int,stdin.readline().split()) b = [0]*n ans = 0 if n > 1: for i in xrange(1,n): x = a[i] + a[i-1] if x<k: b[i] = k - x a[i] = k - a[i-1]...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
n,k = list(map(int,input().strip().split())) l = list(map(int,input().strip().split())) count = 0 for i in range(0,n) : if l[i] >= l[k-1] and l[i] != 0: count = count + 1 print(count)
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees. Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employ...
3
n = int(input()) r = 0 for i in range(1,n): if n % i == 0: r += 1 print(r)
We have a point A with coordinate x = n on OX-axis. We'd like to find an integer point B (also on OX-axis), such that the absolute difference between the distance from O to B and the distance from A to B is equal to k. <image> The description of the first test case. Since sometimes it's impossible to find such point ...
3
t=int(input()) for _ in range(t): n,k=list(map(int,input().split())) if k>=n: print(k-n) elif k%2!=n%2: print(1) else: print(0)
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 = map(int, input().split(' ')) a = 2*t1 + v1*s b = 2*t2 + v2*s if a < b: print("First") elif b < a: print("Second") else: print("Friendship")
In a small restaurant there are a tables for one person and b tables for two persons. It it known that n groups of people come today, each consisting of one or two people. If a group consist of one person, it is seated at a vacant one-seater table. If there are none of them, it is seated at a vacant two-seater tabl...
3
n,a,b=[int(s) for s in input().split()] t=[int(s) for s in input().split()] rez=0 c=0 for ti in t: if ti==1: if a>0: a-=1 elif b>0: b-=1 c+=1 elif c>0: c-=1 else: rez+=1 else: if b>0: b-=1 els...
There is a triangle formed by three points $(x_1, y_1)$, $(x_2, y_2)$, $(x_3, y_3)$ on a plain. Write a program which prints "YES" if a point $P$ $(x_p, y_p)$ is in the triangle and "NO" if not. Constraints You can assume that: * $ -100 \leq x_1, y_1, x_2, y_2, x_3, y_3, x_p, y_p \leq 100$ * 1.0 $\leq$ Length of ea...
3
E = 10**-10 def cp(a, b): c = [a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0]] return c while True: try: x1,y1,x2,y2,x3,y3,xp,yp = [float(i) for i in input().split()] ax = x3-x1 ay = y3-y1 bx = x1-x2 by = y1-y2 cx = x2-x3...
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task. Recently, out of blue Captain Flint has been interested in ma...
3
for _ in range(int(input())): n=int(input()) d=n if n-(6+10+14)>0 and n-(6+10+14)!=6 and n-(6+10+14)!=10 and n-(6+10+14)!=14: print('YES') print(6,10,14,n-(6+10+14)) elif n-(6+10+15)>0 and n-(6+10+15)!=6 and n-(6+10+15)!=10 and n-(6+10+15)!=15: print('YES') print(6, 10, ...
Vasya has a beautiful garden where wonderful fruit trees grow and yield fantastic harvest every year. But lately thieves started to sneak into the garden at nights and steal the fruit too often. Vasya can’t spend the nights in the garden and guard the fruit because there’s no house in the garden! Vasya had been saving ...
1
import sys n, m = map(int, raw_input().split()) grid = [] for _ in range(n): grid += [map(int, raw_input().split())] a,b = map(int, raw_input().split()) t = cur = 99999 for i in xrange(n-a+1): for j in xrange(m-b+1): t = 0 for k in xrange(a): for l in xrange(b): t +...
This night wasn't easy on Vasya. His favorite team lost, and he didn't find himself victorious either — although he played perfectly, his teammates let him down every time. He had to win at least one more time, but the losestreak only grew longer and longer... It's no wonder he didn't get any sleep this night at all. ...
3
import sys sys.setrecursionlimit(10**5) n = str(input()) C = [0]*10 for c in n: C[int(c)] += 1 import copy memo = {} def dfs(state): res = 0 if tuple(state) in memo: return memo[tuple(state)] for i in range(10): if C[i] != 0 and state[i] == 0: break else: res +...
Write a program which reads a sequence and prints it in the reverse order. Note 解説 Constraints * n ≤ 100 * 0 ≤ ai < 1000 Input The input is given in the following format: n a1 a2 . . . an n is the size of the sequence and ai is the ith element of the sequence. Output Print the reversed sequence in a line. P...
3
input() nums = list(map(int,input().split(' '))) print(*nums[::-1])
Utkarsh being a very talkative child, was scolded by his teacher multiple times. One day, the teacher became very angry and decided to give him a very rigorous punishment. He made him stand on the school field which is X axis. Utkarsh initially stood at X = 0. The teacher asked him to run to X = N. But, to make the ...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' n,p = [int(i) for i in raw_input().split()] lis = [1,0,p/100.0,1-p/100.0] for i in range(4,n+1): val = lis[i-2]*p/100.0 + lis[i-3]*(1-p/100.0) lis.append(val) print "%.6f" %lis[-1]
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...
1
t = raw_input() a = '' b = '' for i in xrange(len(t)): a += t[i] if t[i] != 'a': b += t[i] if a + b == t: break if a + b == t: print a else: print ':('
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 ...
1
c, d = 0, 0 for i in range(input()): a, b = map(int, raw_input().split()) c += (b - a) d = max(d, c) print d
Nastya just made a huge mistake and dropped a whole package of rice on the floor. Mom will come soon. If she sees this, then Nastya will be punished. In total, Nastya dropped n grains. Nastya read that each grain weighs some integer number of grams from a - b to a + b, inclusive (numbers a and b are known), and the wh...
3
t = int(input()) for i in range(t): (n, a,b,c,d) = map(int, input().split(" ")) min = n * (a-b); max = n * (a + b); if((min >= c-d and min <= c+d) or (max >= c-d and max <= c+d) or (min <= c-d and max >= c+d)): print("Yes") else: print("No")
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
1
# -*- coding: utf-8 -*- s = raw_input() count = 0 l = len(s) for i in range(l): for j in range(i+1, l): for k in range(j+1, l): if s[i] == 'Q' and s[j] == 'A' and s[k] == 'Q': count += 1 print count
You are given an integer n (n > 1). Your task is to find a sequence of integers a_1, a_2, …, a_k such that: * each a_i is strictly greater than 1; * a_1 ⋅ a_2 ⋅ … ⋅ a_k = n (i. e. the product of this sequence is n); * a_{i + 1} is divisible by a_i for each i from 1 to k-1; * k is the maximum possible (i. e...
3
import math tc = int(input()) for i in range(tc): integer = int(input()) k = integer kamus = dict() while k % 2 == 0: try: kamus[2] += 1 except: kamus[2] = 1 k /= 2 for i in range(3,int(math.sqrt(k))+1,2): while k % i == 0: try...
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
3
a,b,c,d=list(map(int,input().split())) misha=max(((3*a)/10),(a-(a/250)*c)) vasya=max(((3*b)/10),(b-(b/250)*d)) if misha>vasya: print("Misha") elif vasya>misha: print("Vasya") else: print("Tie")
You are given an array a consisting of n integers a_1, a_2, ..., a_n. You want to split it into exactly k non-empty non-intersecting subsegments such that each subsegment has odd sum (i. e. for each subsegment, the sum of all elements that belong to this subsegment is odd). It is impossible to rearrange (shuffle) the e...
3
''' import sys sys.stdin=open('input.txt') ''' T=int(input()) t=0 while t<T: n,k=map(int,input().split()) L=list(map(int,input().split())) x=0 d=0 while x<len(L): if L[x]%2!=0: d+=1 x+=1 if d<k or d%2!=k%2: print('NO') else: print ('YES') ...
Let's define the following recurrence: $$$a_{n+1} = a_{n} + minDigit(a_{n}) ⋅ maxDigit(a_{n}).$$$ Here minDigit(x) and maxDigit(x) are the minimal and maximal digits in the decimal representation of x without leading zeroes. For examples refer to notes. Your task is calculate a_{K} for given a_{1} and K. Input The ...
3
t=int(input()) while (t>0): one,k=input().split(" ") one,k=int(one),int(k) s=one ans=0 for i in range(k-1): temp=[int(j) for j in list(str(s))] if (min(temp)==0): break else: ans=s+(max(temp)*min(temp)) s=ans print(s) t-=1
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≤ a ≤ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
3
def inp(): n = int(input()) if n % 2 == 1: print('Ehab') else: print('Mahmoud') inp()
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
import sys import math from math import factorial as f from collections import defaultdict as dd mod=1000000007 T=1 T=int(sys.stdin.readline()) for _ in range(T): n=int(input()) l=list(map(int,input().split())) nn=n<<1 ev,od=[],[] for i in range(nn): if l[i]&1: od.append(i+1) ...
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
#Codeforce 236A str1=input().strip("\n\r") s=set(v for v in str1) if len(s)%2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Vova promised himself that he would never play computer games... But recently Firestorm — a well-known game developing company — published their newest game, World of Farcraft, and it became really popular. Of course, Vova started playing it. Now he tries to solve a quest. The task is to come to a settlement named Ove...
3
n, m = map(int, input().split()) cs = [0] + list(map(int, input().split())) p = [0] + list(range(1, n+1)) def find(x): while p[x] != x: p[x] = p[p[x]] x = p[x] return x for _ in range(m): x, y = map(find, (map(int, input().split()))) if cs[x] < cs[y]: p[y] = x else: ...
Given two integers n and x, construct an array that satisfies the following conditions: * for any element a_i in the array, 1 ≤ a_i<2^n; * there is no non-empty subsegment with [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) equal to 0 or x, * its length l should be maximized. A sequenc...
3
def gns(): return [int(x) for x in input().split()] n,x=gns() # if len(str(x))>n: # n+=1 if n==1: if x==1: print(0) quit() print(1) print(1) quit() b=len(bin(x))-2 if x!=1: ans=[1] else: ans=[2] cur=1 for i in range(n-2): if cur==b-1: cur+=1 ans=ans+[1<<c...
Vasya has a multiset s consisting of n integer numbers. Vasya calls some number x nice if it appears in the multiset exactly once. For example, multiset \{1, 1, 2, 3, 3, 3, 4\} contains nice numbers 2 and 4. Vasya wants to split multiset s into two multisets a and b (one of which may be empty) in such a way that the q...
1
import sys from collections import defaultdict as di range = xrange input = raw_input n = int(input()) A = [int(x) for x in input().split()] count = di(int) for x in A: count[x]+=1 single = [x for x in count if count[x]==1] extra = [x for x in count if count[x]>=3] L = [] #R = [] Lscore = 0 Rscore = 0 for x i...
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
n = int(input()) for i in range(n): k = int(input()) i = 1 ar = [] j = 0 while k!=0: r = k%10 if r != 0: ar.append(r*i) j += 1 i *= 10 k = k//10 print(j) print(" ".join(map(str,ar)))
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
t = int(input()) for _ in range(t): b = input() tab = [] ans = '' for i in range(1 , len(b) + 1 , 2): tab.append(b[i - 1] + b[i]) ans += tab[0] for i in range(1 , len(tab)): ans += tab[i][1] print(ans)
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): s = input() a = s.rfind("po") b = s.rfind("desu") c = s.rfind("masu") d = s.rfind("mnida") if(s.count("po")!=0 and a+2==len(s)): print("FILIPINO") elif(s.count("desu")!=0 and b+4==len(s)): print("JAPANESE") elif(s.count("masu")!=0 and c...
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that: gcd(sum(S_1), sum(S_2)) > 1 Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Ev...
3
N = int(input()) if N <=2: print("No") else: i = 1 sum = 0 while (i <= N): sum += i i += 1 print("Yes") print("1",N) i = 1 d = [] while (i < N): d.append(i) i += 1 print(f"{len(d)}", end=" ") print(*d)
Ilya lives in a beautiful city of Chordalsk. There are n houses on the street Ilya lives, they are numerated from 1 to n from left to right; the distance between every two neighboring houses is equal to 1 unit. The neighboring houses are 1 and 2, 2 and 3, ..., n-1 and n. The houses n and 1 are not neighboring. The ho...
3
n = int(input()) colors = list(map(int, input().split())) used = [0] * n maxdist = 0 for i in range(n-2): if not used[colors[i]-1]: used[colors[i]-1] = 1 j = n - 1 while j > i and colors[j] == colors[i]: j -= 1 if j-i > maxdist: maxdist = j - i print(maxdist...
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa...
3
a,b,c,d = [int(i) for i in input().split(" ")] x = [a,b,c] x.sort() print(max(0, d - x[1] + x[0]) + max(0, d - x[2] + x[1]))
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
3
x , y = input().split() num = 6 - max(int(x) , int(y)) + 1 denom = 6 for i in range (1 , 5) : if num % i == 0 and denom % i == 0 : num /= i denom /= i i -= 1 num = int(num) denom = int(denom) print(str(num) + "/" + str(denom))
Andre has very specific tastes. Recently he started falling in love with arrays. Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements — 6 — is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't div...
3
for _ in range(int(input())): n = int(input()) print('1 '*n)
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d...
3
s=list(input()) k=0 w={'4','7'} for i in s: if i=='4' or i=='7': k+=1 k1=set(list(str(k))) if w>=k1: print('YES') else: print('NO')
You're given an integer n. For every integer i from 2 to n, assign a positive integer a_i such that the following conditions hold: * For any pair of integers (i,j), if i and j are coprime, a_i ≠ a_j. * The maximal value of all a_i should be minimized (that is, as small as possible). A pair of integers is call...
3
# -*- coding: utf-8 -*- """ Created on Mon Jun 3 10:01:38 2019 @author: plosi """ def compute(n): val=1 primes=[True for i in range(n+1)] primes[0]=False primes[1]=False fs=[0 for i in range(n+1)] p=2 fs[2]=1 while p<=int(n**(.5)) : cur=p cur=cur+p while c...
Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split. Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic g...
3
import sys # How to multiply matrices in 32 bit python? # Solution: Use doubles # New problem: Might not have integer precision # Solution: Mod when outside of double precision # Alt solution: Use 64 bit python MOD = 10**9 + 7 double_prec = float(2**50) def mult(A,B): n = len(A) cutmask = 2**16-1 C = [[0...
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order...
1
n = int(raw_input()) diff = [int(x) for x in raw_input().split()] inds = [] for i in range(n): inds.append((diff[i],i)) inds.sort() resp = [] resp.append([x[1]+1 for x in inds]) cont = 0 for i in range(n-1): if inds[i][0]==inds[i+1][0]: cont+=1 temp = inds[i] inds[i] = inds[i+1] ...
Valera runs a 24/7 fast food cafe. He magically learned that next day n people will visit his cafe. For each person we know the arrival time: the i-th person comes exactly at hi hours mi minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than ...
3
from collections import Counter n=int(input()) print(max(Counter(list([input() for i in range(n)])).values()))
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
w = input('') if int(w) % 2 == 0 and int(w) != 2: print('YES') else: print('NO')
Petya and Vasya are playing a game. Petya's got n non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to n from left to right. Note that the positions are indexed but the glasses are not. First Petya puts a marble under the glass in position s. Then he performs some (pos...
3
n,s,t = input().split() n=int(n) s=int(s) t=int(t) l=input().split() for i in range(n): l[i]=int(l[i]) j=0 i=s flag=0 if(s==t): flag=1 while(j<n and flag!=1): if(i==l[i-1]): if(i==t): flag=1 break break i=l[i-1] if(i==t): flag=1 j+=1 br...
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches th...
3
def func(s, s1): if(s > s1): s, s1 = s1, s for i in range(len(s)): if(s[i] >= s1[i]): return "NO" return "YES" n = int(input()) s = input() s1 = s[n:] s = s[:n] s = sorted(s) s1 = sorted(s1) print(func(s, s1))
Appleman has n cards. Each card has an uppercase letter written on it. Toastman must choose k cards from Appleman's cards. Then Appleman should give Toastman some coins depending on the chosen cards. Formally, for each Toastman's card i you should calculate how much Toastman's cards have the letter equal to letter on i...
3
import sys from functools import reduce from collections import Counter # import time # import datetime from math import sqrt,gcd # def time_t(): # print("Current date and time: " , datetime.datetime.now()) # print("Current year: ", datetime.date.today().strftime("%Y")) # print("Month of year: ", datetime....
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
3
a,b,n = map(int,input().split()) c = 0 def gcd(a,b) : while(b) : a,b = b,a%b return a while(n>0) : if(c%2==0) : k = gcd(a,n) n -= k else : k = gcd(b,n) n -= k c += 1 if(c%2!=0) : print(0) else : print(1)
And again a misfortune fell on Poor Student. He is being late for an exam. Having rushed to a bus stop that is in point (0, 0), he got on a minibus and they drove along a straight line, parallel to axis OX, in the direction of increasing x. Poor Student knows the following: * during one run the minibus makes n st...
3
from math import * n,x,y=map(int,input().split()) r=list(map(int,input().split())) xx,yy=map(int,input().split()) t=10**10 array=[] for i in range(1,n): ti=r[i]/x+sqrt((r[i]-xx)**2+yy**2)/y if ti<t: t=ti array=[] if ti==t: array.append([(r[i]-xx)**2+yy**2,i]) array.sort() print(array[0...
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1...
3
for i in range(int(input())): n = int(input()) arr = list(map(int,input().split())) a = [0] p = arr[0] for i in range(1,n): r = p - (p & arr[i]) p = p|arr[i] a.append(r) print(*a)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a=int(input()) b=int(input()) c=int(input()) x1=a*b*c x2=(a+b)*c x3=a*(b+c) x4=a+b+c print(max(x1, x2, x3, x4))
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) x = 0 arr = [] for i in range(n): if '+' in input(): x += 1 else: x -= 1 print(x)
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If...
1
t=raw_input() dangerous = False for i in range (len(t)-6): if t[i] == '0' and t[i+1]=='0' and t[i+2]=='0' and t[i+3]=='0' and t[i+4]=='0' and t[i+5]=='0' and t[i+6]=='0' or t[i] == '1' and t[i+1]=='1' and t[i+2]=='1' and t[i+3]=='1' and t[i+4]=='1' and t[i+5]=='1' and t[i+6]=='1' : dangerous = True ...
You are playing a new famous fighting game: Kortal Mombat XII. You have to perform a brutality on your opponent's character. You are playing the game on the new generation console so your gamepad have 26 buttons. Each button has a single lowercase Latin letter from 'a' to 'z' written on it. All the letters on buttons ...
3
def brutal(n1,n2,m,comb): m=[int(m[i]) for i in range(len(m))] if n2>n1: return "Incorrect input" count=[] new=comb[0] result=0 for i in range(len(comb)): if comb[i]!=new: if len(count)<=n2: result+= sum(count) else: count.s...
Alice and Bob are playing a game on a line with n cells. There are n cells labeled from 1 through n. For each i from 1 to n-1, cells i and i+1 are adjacent. Alice initially has a token on some cell on the line, and Bob tries to guess where it is. Bob guesses a sequence of line cell numbers x_1, x_2, …, x_k in order....
3
import math from decimal import Decimal def na(): n = int(input()) b = [int(x) for x in input().split()] return n,b def nab(): n = int(input()) b = [int(x) for x in input().split()] c = [int(x) for x in input().split()] return n,b,c def dv(): n, m = map(int, input().split()) return n,m def dva(): ...
You are given the array a consisting of n positive (greater than zero) integers. In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a...
3
for i in range(int(input())): n=int(input()) A=list(map(int,input().split())) c=0 s=0 if n%2==0: for i in A: if i%2==0: c+=1 else: s+=1 if c==n or s==n: print('NO') else: print('YES') else...
Luke Skywalker gave Chewbacca an integer number x. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit t means replacing it with digit 9 - t. Help Chewbacca to transform the initial number x to the minimum possible positive number by inverting some (possibly, zero) digits. The decim...
3
n=input() a=[] for i in range(len(n)): a.append(int(n[i])) if a[0]!=9: for i in range(len(a)): if a[i]>4: a[i]=9-a[i] else: for i in range(1,len(a)): if a[i]>4: a[i]=9-a[i] for i in range(len(a)): print(a[i],end='') print()
You are given an integer n (n ≥ 0) represented with k digits in base (radix) b. So, $$$n = a_1 ⋅ b^{k-1} + a_2 ⋅ b^{k-2} + … a_{k-1} ⋅ b + a_k.$$$ For example, if b=17, k=3 and a=[11, 15, 7] then n=11⋅17^2+15⋅17+7=3179+255+7=3441. Determine whether n is even or odd. Input The first line contains two integers b and...
3
#!/usr/bin/python3 import math import sys DEBUG = False def inp(): return sys.stdin.readline().rstrip() def dprint(*value, sep=' ', end='\n'): if DEBUG: print(*value, sep=sep, end=end) def solve(B, K, A): A.reverse() v = 0 d = 1 for a in A: v += a * d v %= 2 ...