problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
There are three airports A, B and C, and flights between each pair of airports in both directions. A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours. Consider a route where we start at one of th...
3
x=list(map(int,input().split())) print(sum(x)-max(x))
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
#map(int,input().strip().split(' ')) t=int(input()) while t: t-=1 n,k=map(int,input().strip().split(' ')) a=list(map(int,input().strip().split(' '))) b=list(map(int,input().strip().split(' '))) a.sort() b.sort() s=0 x=a[0:k]+b[n-k:] x.sort() s=sum(a[k:])+sum(x...
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...
1
n, a = input(), map(int, raw_input().split(" ")) m, b = input(), map(int, raw_input().split(" ")) worms = [0] i = 1 for amt in a: worms += [i] * amt i += 1 for worm in b: print worms[worm]
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
for _ in range(int(input())): n = int(input()) a = list(map(int, input().split())) max1, max2 = -1, -1 for i in a: if i >= max1: max1, max2 = i, max1 else: max2 = max(max2, i) ans = min(n - 2, min(max1 - 1, max2 - 1)) print(ans)
In Disgaea as in most role-playing games, characters have skills that determine the character's ability to use certain weapons or spells. If the character does not have the necessary skill, he cannot use it. The skill level is represented as an integer that increases when you use this skill. Different character classes...
1
epsilon = 10**-10 if __name__ == "__main__": a = {} n,m,k = map(eval,raw_input().split()) for i in range(0,int(n)): s = raw_input() x = s.split()[0] y = s.split()[1] y = int(y) if y * k >= 100: a[str(x)] = int((y * k) + epsilon) for i in range(0,int(m)...
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
t=int(input()) for _ in range(t): m=0 n=int(input()) x=input() i=0 while(i<n): if(x[i]=='A'): j=i+1 while(j<n): if(x[j]=='P'): j+=1 else: break if(j-i>m): m=j-i-1 ...
[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=[int(t) for t in input().split()] g,p,b=[int(t) for t in input().split()] f=False if g>=x: if (g-x+p)>=y: if (g-x+p-y+b) >=z: print("YES") else: print("NO") else: print("NO") else: print("NO")
Let's arrange a deck of cards. There are totally 36 cards of 4 suits(S, H, C, D) and 9 values (1, 2, ... 9). For example, 'eight of heart' is represented by H8 and 'one of diamonds' is represented by D1. Your task is to write a program which sorts a given set of cards in ascending order by their values using the Bubbl...
3
def BSort(A,n): flag=1 while flag: flag=0 for i in range(n-1,0,-1): if A[i][1]<A[i-1][1]: A[i],A[i-1]=A[i-1],A[i] flag=1 def SSort(A,n): for i in range(n): minj=i for j in range(i,n): if A[j][1]<A[minj][1]: ...
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya...
3
n, m=map(int, input().split()) t,i=0,0 for v in range(m): if "0" in input(): i+=1 if i>t: t=i else: i=0 print(t)
You are responsible for installing a gas pipeline along a road. Let's consider the road (for simplicity) as a segment [0, n] on OX axis. The road can have several crossroads, but for simplicity, we'll denote each crossroad as an interval (x, x + 1) with integer x. So we can represent the road as a binary string consist...
3
Q = int(input()) Qs = [] for _ in range(Q): n, a, b = map(int, input().split()) s = input() Qs.append([n, a, b, s]) for n, a, b, S in Qs: l = 0 L = [] for s in list(S): if s == '0': l += 1 else: if not L: L.append(l) elif l >= ...
Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them. Constraints * 1 \leq K \leq N...
1
import sys from collections import deque import copy import math def get_read_func(fileobject): if fileobject == None : return raw_input else: return fileobject.readline def main(): if len(sys.argv) > 1: f = open(sys.argv[1]) else: f = None read_func = get_read_func(...
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
# 101010 01 1010 # 0101 1010 n=int(input()) a=[] c=1 for i in range(n): a.append(int(input())) for i in range(1,n): if a[i-1]!=a[i]: c+=1 print(c)
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() inv = "" for idx, i in enumerate(n): i = int(i) if i >= 5: if idx != 0 or i != 9: i = 9-i inv += str(i) print(inv)
It is only six months until Christmas, and AtCoDeer the reindeer is now planning his travel to deliver gifts. There are N houses along TopCoDeer street. The i-th house is located at coordinate a_i. He has decided to deliver gifts to all these houses. Find the minimum distance to be traveled when AtCoDeer can start and ...
1
N = int (raw_input ()) l = [int (i) for i in raw_input ().split ()] print max (l) - min (l)
This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
3
""" Author - Satwik Tiwari . 18th Feb , 2021 - Thursday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import Byt...
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
import math t=list(map(int,input().split())) n=t[0] m=t[1] a=t[2] print(math.ceil(n/a)*math.ceil(m/a))
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya loves tickets very much. As we know, each ticket has a number that is a positive integer. It...
1
#coding: utf-8 #146A - Lucky Ticket. 18/07/2018 tam = int(raw_input()) num = raw_input() aux1 = 0 aux2 = 0 for i in range(len(num)/2): aux1 += int(num[i]) for i in range(len(num)/2, len(num)): aux2 += int(num[i]) lucky = True for i in num: if i != "4" and i != "7": lucky = False if(lucky and aux1 == aux2): pr...
A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97. Alice is given a sequence of n composite numbers a_1,a_2,…,a_n. She wants to choos...
3
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31] t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) colors = '' used = [0]*11 count = 0 for ai in a: for i in range(11): if ai%primes[i] is 0: if used[i] is 0: ...
You are given the array a consisting of n elements and the integer k ≤ n. You want to obtain at least k equal elements in the array a. In one move, you can make one of the following two operations: * Take one of the minimum elements of the array and increase its value by one (more formally, if the minimum value of ...
3
from sys import stdin from collections import * def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return [str(x) for x in stdin.readline().split()] def divide(x): num = 0 mem...
Apart from Nian, there is a daemon named Sui, which terrifies children and causes them to become sick. Parents give their children money wrapped in red packets and put them under the pillow, so that when Sui tries to approach them, it will be driven away by the fairies inside. Big Banban is hesitating over the amount ...
3
k = int(input()) if (k > 36) : print(-1) else: if (k % 2): print("4", end="") print("8" * (k // 2))
Polycarp has three sisters: Alice, Barbara, and Cerene. They're collecting coins. Currently, Alice has a coins, Barbara has b coins and Cerene has c coins. Recently Polycarp has returned from the trip around the world and brought n coins. He wants to distribute all these n coins between his sisters in such a way that ...
3
# Collecting Coins n=int(input()) for i in range(n): a,b,c,d=[int(i) for i in input().split()] e=max(max(a,b),c) d=d-(e-a) d=d-(e-b) d=d-(e-c) if(d%3==0 and d>0 or(d==0)): print("YES") else: print("NO")
This is an interactive problem. Vasya and Petya are going to play the following game: Petya has some positive integer number a. After that Vasya should guess this number using the following questions. He can say a pair of non-negative integer numbers (x, y). Petya will answer him: * "x", if (x mod a) ≥ (y mod a). ...
1
from sys import stdout def Q(x, y): print '?', x, y stdout.flush() return raw_input()[0] while 1: s = raw_input().strip() if s != 'start': break x, y = 0, 1 a = 0 for i in xrange(30): c = Q(x, y) if c == 'x': break else: x, y = y, y...
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
1
n, k, l, c, d, p, nl, np, = map(int, raw_input().split(" ")) drink = int(k*l//nl) salt = int(p / np) lime = d*c print (min(drink, salt, lime))//n
You are given a correct solution of the sudoku puzzle. If you don't know what is the sudoku, you can read about it [here](http://tiny.cc/636xmz). The picture showing the correct sudoku solution: <image> Blocks are bordered with bold black color. Your task is to change at most 9 elements of this field (i.e. choose s...
3
import sys def data(): return sys.stdin.readline().strip() out=sys.stdout.write def mdata(): return map(int, data().split()) from collections import defaultdict as dd for t in range(int(data())): l=[] for i in range(9): a=str(data()) l.append(list(a)) k=0 i=0 while i<9: for ...
Petya has a rectangular Board of size n × m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column. In one action, Petya can move all the chips to the left, right, down or up by 1 cell. If the chip was in the (x, y) cell, then after the oper...
3
n, m, k = map(int, input().split()) for i in range(2*k): _ = input() if n == 1 and m == 1: print(0) elif n == 1: print(2 * m) print("R" * m + "L" * m) elif m == 1: print(2 * n) print("U" * n + "D" * n) else: print((m) * (n-1) + m-1 + n-1 + m-1) s = "R"*(m-1)+"U"*(n-1) D = "D" * (n-1)...
RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T. Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 ≤ i < j ≤ m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black...
3
import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP2/output.txt",'w') # sys.stdin=open("CP2/input.txt",'r') # mod=pow(10,9)+7 t=int(input()) for i in range(t): n,k=map(int,input().split()) a=list(map...
Cyael is a teacher at a very famous school in Byteland and she is known by her students for being very polite to them and also to encourage them to get good marks on their tests. Then, if they get good marks she will reward them with candies :) However, she knows they are all very good at Mathematics, so she decided to...
1
t = int(raw_input()) from math import sqrt for _ in xrange(t): n, k = map(int, raw_input().split()) if k == 0: print "0 %s" % n else: student_share = n / k #Integer division print "%s %s" % (student_share, n - (k * student_share))
As a New Year's gift, Dolphin received a string s of length 19. The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`. Dolphin wants to convert the comma-separated string s into a space-separated string. Write a program to perform th...
1
a, b, c = map(str, raw_input().split(",")) print " ".join([a, b, c])
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
n = int(input()) a,b = map(int, input().rstrip().split()) count = maxi = 0 for _ in range(n-1): c,d = map(int, input().rstrip().split()) if a==c and b==d: count += 1 else: maxi = max(maxi, count) count = 0 a,b = c,d print(max(maxi,count)+1)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
tc = int(input()) for t in range(tc): n = int(input()) s = input() m = n-1 new_str = "" for i in range(n): new_str += s[m] print(new_str)
A list of names is taken as input, in which a particular name can occur multiple times. You need to arrange these names as they will appear in the dictionary and also print the number of times the arranged names appear in the list taken as input. Input: The first line of input contains an integer, t, which denotes th...
1
import operator n=int(raw_input()) d={} for _ in xrange(n): temp=raw_input() if temp in d.keys(): d[temp]+=1 else: d[temp]=1 k=sorted(d.items(), key=operator.itemgetter(0)) for i,j in k: print i,j
Innokentiy decides to change the password in the social net "Contact!", but he is too lazy to invent a new password by himself. That is why he needs your help. Innokentiy decides that new password should satisfy the following conditions: * the length of the password must be equal to n, * the password should con...
3
#!/usr/bin/env python import string def main(): n, k = [int(x) for x in input().split()] print((string.ascii_lowercase[:k] * 100)[:n]) if __name__ == '__main__': main()
Chef develops his own computer program for playing chess. He is at the very beginning. At first he needs to write the module that will receive moves written by the players and analyze it. The module will receive a string and it should report at first whether this string represents the correct pair of cells on the chess...
1
import re prog=re.compile('^[a-h]{1}[1-8]{1}-[a-h]{1}[1-8]{1}$') n=input() for i in range(n): s=str(raw_input()) if bool(prog.match(s)): one=abs(ord(s[0])-ord(s[3])) two=abs(int(s[1])-int(s[4])) if one==1 and two==2 or two==1 and one ==2: print 'Yes' else : ...
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr...
1
a,b=raw_input().strip().lower(),raw_input().strip().lower() if a==b:print 0 elif a<b:print -1 else: print 1
Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing. Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ...
3
import math for _ in range(int(input())): n,g,b=map(int,input().split()) good=math.ceil(n/2) ans = (int(good/g))*(g+b) if good %g >0 : ans +=good %g elif good%g==0: ans-=b print(max(n,ans))
We have N cards. A number a_i is written on the i-th card. Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first. The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards...
1
from sys import stdin n = int(stdin.readline()) a = map(int,stdin.readline().split()) ans = 0 a.sort() a.reverse() for i in xrange(n): if i%2: ans -=a[i] else: ans+=a[i] print ans
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n. For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10. Input The first line contains an integer t (1 ≤ t ≤ 1000) — the ...
3
import math for _ in range(int(input())): n,k = map(int, input().split()) init = k%(n-1) if(init == 0): init = n-1 div = (k/(n-1)) if(div%1 == 0): div -= 1 else: div = math.floor(div) res = init + n*div print(int(res))
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
3
import sys def input(): return sys.stdin.readline().strip() n = int(input()) count = 0 s1 = input() for i in range(n-1): s2 = input() if s1[1] == s2[0]: count += 1 s1 = s2 # s = '' # for i in range(n): # s += input() # for i in range(2, 2*n, 2): # if s[i] == s[i-1]: # count += 1 print(count+1)
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
3
for _ in range(int(input())): x=int(input()) arr=list(map(int,input().split())) tar=[] for i in range(x-1): if arr[i]!=-1 and arr[i+1]==-1: tar.append(arr[i]) elif arr[i]==-1 and arr[i+1]!=-1: tar.append(arr[i+1]) if not tar: print(0,0) else: k=(max(tar)+min(tar)+1)//2 m=0 arr=[k if num==-1 else...
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another. Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P": * "A" corresponds to an angry...
3
def greaterthan(ar,target,end): start=0 ans=-1 while(start<=end): mid=(start+end)//2 if(ar[mid]<=target): start=mid+1 else: ans=mid end=mid-1 return ans for i in range(int(input())): n=int(input()) s=input() s=s[::-1] x=0 ans=[] for j in range(n): if(s[j]=='A'): ans.append(j-x) x=j+1...
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider...
3
n, m = map(int, input().split()) a = [] for i in range(1, m + 1): a.append(i) for j in range(n): l, r = map(int, input().split()) for i in range(l - 1, r): a[i] = 0 k = 0 for i in range(len(a)): if a[i] != 0: k += 1 print(k) for i in range(len(a)): if a[i] != 0: print...
Bob is a pirate looking for the greatest treasure the world has ever seen. The treasure is located at the point T, which coordinates to be found out. Bob travelled around the world and collected clues of the treasure location at n obelisks. These clues were in an ancient language, and he has only decrypted them at hom...
1
import sys n = int(raw_input()) pillars = set() for i in range(n): t = tuple(map(int, raw_input().split())) if i == 0: pil0 = t pillars.add(t) clues = [] for i in range(n): clues.append(tuple(map(int, raw_input().split()))) for i,clue in enumerate(clues): px, py = pil0[0] + clue[0], pil0[...
You are given a rectangular cake, represented as an r × c grid. Each cell either has an evil strawberry, or is empty. For example, a 3 × 4 cake may look as follows: <image> The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contain...
3
a,b=map(int,input().split()) l=[] count=row=0 for i in range(a): l.append(input()) if 'S' not in l[i]: count+=1 for i in range(b): col=0 for j in range(a): if l[j][i] == 'S': col +=1 if col==0: row+=1 print(row*a+count*b-count*row)
There are N piles of stones. The i-th pile has A_i stones. Aoki and Takahashi are about to use them to play the following game: * Starting with Aoki, the two players alternately do the following operation: * Operation: Choose one pile of stones, and remove one or more stones from it. * When a player is unable to do t...
3
import sys N = int(input()) A = list(map(int, input().split())) x = 0 for i in A: x ^= i # 0以上A1未満 # a1 ^ a2 -> (a1-n) ^ (a2+n) # x -> 0 # a + b = 0 -> b=-aは逆元 # a * b = 1 -> b=1/aは逆元 # a ^ a = 0 -> aが逆元 # -> 自由に式変形しやすい # a1^a2^あまり=x # b1^b2^あまり=0 # a1^a2^x=b1^b2 # 上のビットからやる old = A[0] ^ A[1] ^ x # b0 ^ b1 = ...
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
def fun(): n = int(input()) a = list(map(int, input().split())) if a[n-1] < (a[0] + a[1]): print('-1') else: print('1 2 '+ str(n)) for i in range(int(input())): fun()
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
3
n=int(input()) a=input().split() for i in range(0,len(a)): a[i]=int(a[i]) a.sort() a.reverse() polsum=sum(a)/2 sym=0 kol=0 for i in range(0,len(a)): sym+=a[i] kol+=1 if sym>polsum: break print(kol)
Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt ...
3
n = int(input()) m = list(map(int, input().split())) r = list(map(int, input().split())) days = [0 for i in range(30030)] d = 0 for mi in range(n): for i in range(30030): if (i+1) % m[mi] == r[mi]: if days[i] != 1: d+=1 days[i] = 1 print("%.6f"%(d / 30030))
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...
1
n,m = map(int,raw_input().split()) def f(x): if(x<=n<=x*2): print x return True for i in xrange(1,n): if f(m*i): exit() print (-1)
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana). He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas? Input The first lin...
3
import math k, n, w = map(int, input().split()) total = 0 for x in range(1, w + 1): total += x*k print(max(0, total - n))
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said to be good when its elevation is higher than those of all observatories that can be r...
3
N, M = map(int, input().split()) H = list(map(int, input().split())) sm = [] for i in range(M): A, B = map(int, input().split()) if H[A-1] <= H[B-1] : sm.append(A) if H[B-1] <= H[A-1] : sm.append(B) print(N - len(set(sm)))
You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ...
3
w,h,k=map(int,input().split()) sum=0 for i in range(k): sum+=2*(w+h-2) w-=4 h-=4 print(sum)
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
n = int(input()) left = [None]*n right = [None]*n for i in range(n): left[i], right[i] = map(int, input().split()) answer = -1 minL = 10**9 + 1 for i in range(n): if (left[i] < minL): minL = left[i] maxR = 0 for i in range(n): if (right[i] > maxR): maxR = right[i] for i in range(n): if...
You are given a string s[1 ... n] consisting of lowercase Latin letters. It is guaranteed that n = 2^k for some integer k ≥ 0. The string s[1 ... n] is called c-good if at least one of the following three conditions is satisfied: * The length of s is 1, and it consists of the character c (i.e. s_1=c); * The lengt...
3
t = int(input()) alph = "abcdefghijklmnopqrstuvwxyz" def sim(s, it): if len(s) == 1: if s == alph[it]: return 0 else: return 1 l = s[:len(s)//2] r = s[len(s)//2:] sc1 = 0 sc2 = 0 for i in l: if i != alph[it]: sc1 += ...
Mike is trying rock climbing but he is awful at it. There are n holds on the wall, i-th hold is at height ai off the ground. Besides, let the sequence ai increase, that is, ai < ai + 1 for all i from 1 to n - 1; we will call such sequence a track. Mike thinks that the track a1, ..., an has difficulty <image>. In othe...
3
n = int(input()) a = list(map(int, input().split())) ans = 10 ** 10 for i in range(1, n - 1): cur = a[:i] + a[i + 1:] ans = min(ans, max(cur[j] - cur[j - 1] for j in range(1, len(cur)))) print(ans)
Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had. Constraints * 1 \leq N \leq 10^5 * 0 \leq K \leq N-1 * All input values are integers. ...
3
N, K = map(int,input().split()) ans = 0 for b in range(1,N+1): ans += (N//b)*max(0,b-K) + max(0,N%b-K+1) if K == 0: ans -= N print(ans)
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any bett...
3
n=int(input()) s=input() A=0 I=0 for i in range(n): if(s[i]=='A'): A+=1 elif(s[i]=='I'): I+=1 if(I==1): print(I) elif(I>1): print("0") else: print(A)
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the...
1
(n,h)= map(int,raw_input().split()) ar = map(int,raw_input().split()) c=0; for i in range(n): if ar[i] > h: c += 2 else: c += 1 print c
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
def possible(arr,v,x): visited = set() for i in arr: if i <= v: visited.add(i) for i in range(1,v+1): if i not in visited: x -= 1 if x < 0: return False return True def solve(arr,x): arr = list(arr) arr.sort() #print(arr) for v in r...
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
3
if __name__ == "__main__": n = int(input()) a = list(map(int, input().split(" "))) a = [0] + a acc = [0 for _ in range(n+1)] for i in range(1, n+1): acc[i] = a[i] + acc[i-1] m = {} for i in range(0, n+1): for j in range(i+1, n+1): if acc[j]-acc[i] not in m: ...
Haiku is a genre of Japanese traditional poetry. A haiku poem consists of 17 syllables split into three phrases, containing 5, 7 and 5 syllables correspondingly (the first phrase should contain exactly 5 syllables, the second phrase should contain exactly 7 syllables, and the third phrase should contain exactly 5 syll...
3
a=input() b=input() c=input() t=0 for i in a: if i=="a" or i=="e" or i=="i" or i=="o" or i=="u": t +=1 if (t==5): t=0 for i in b: if i=="a" or i=="e" or i=="i" or i=="o" or i=="u": t +=1 if t==7: t=0 for i in c: if i=="a" or i=="e" or i=="i" or i==...
Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there. If t...
1
n=input() a=map(int,raw_input().strip().split()) b=[] for i in range(0,n): b.append(0) for i in range(0,n): b[a[i]-1]=i for i in b: print i+1,
You are given the string s of length n and the numbers p, q. Split the string s to pieces of length p and q. For example, the string "Hello" for p = 2, q = 3 can be split to the two strings "Hel" and "lo" or to the two strings "He" and "llo". Note it is allowed to split the string s to the strings only of length p or...
3
S = input().split() n = int(S[0]) p = int(S[1]) q = int(S[2]) s = input() i=0 t=0 c=0 b=0 if (n%q == 0) and (n%p != 0): print(int(n/q)) for k in range(0,n,q): print(s[k:k+q]) elif (n%p == 0) and (n%q != 0): print(int(n/p)) for k in range(0,n,p): print(s[k:k+p]) elif (n%q == 0) and (n%p =...
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...
1
__author__ = 'Devesh Bajpai' ''' https://codeforces.com/problemset/problem/520/A Solution: Maintain a set of characters seen in the string. In the end, the size of that set should be 26 denoting all characters were observed at least once in the string. Make sure we add characters in one case in the set to deal with u...
Amugae is in a very large round corridor. The corridor consists of two areas. The inner area is equally divided by n sectors, and the outer area is equally divided by m sectors. A wall exists between each pair of sectors of same area (inner or outer), but there is no wall between the inner area and the outer area. A wa...
3
def compute_gcd(x, y): while(y): x, y = y, x % y return x def compute_lcm(x, y): lcm = (x*y)//compute_gcd(x,y) return lcm n,m,q = map(int,input().split()) val = compute_lcm(n,m) first = val//m second = val//n for j in range(q): a,b,c,d = map(int,input().split()) if(a==c): x = first ...
When Valera has got some free time, he goes to the library to read some books. Today he's got t free minutes to read. That's why Valera took n books in the library and for each book he estimated the time he is going to need to read it. Let's number the books by integers from 1 to n. Valera needs ai minutes to read the ...
3
a = [int(x) for x in input().split()] length = a[0] time = a[1] b = [int(x) for x in input().split()] answer = 0 current_sum = 0 x = 0 while x < length: current_sum += b[x] answer += 1 if current_sum > time: answer -= 1 current_sum -= b[x - answer] x += 1 print(answer)
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
3
x=int(input()) a={} for y in range(x): s=input() if s in a: a[s]+=1 print(s+str(a[s])) else: a[s]=0 print("OK")
Alice and Bob are decorating a Christmas Tree. Alice wants only 3 types of ornaments to be used on the Christmas Tree: yellow, blue and red. They have y yellow ornaments, b blue ornaments and r red ornaments. In Bob's opinion, a Christmas Tree will be beautiful if: * the number of blue ornaments used is greater b...
3
y,b,r = map(int,input().split()) for i in range(98,0,-1): if y >= i and b >= i+1 and r >= i+2: print(3*i+3) break
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n. Input The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m l...
1
from __future__ import print_function import heapq as hq Inf = float("inf") def dijkstra(n, adj, src): d = [Inf] * (n+1) d[src] = 0 q = [] parent = [None] *(n+1) hq.heappush(q, (d[src], src)) while q: _, u = hq.heappop(q) for v, w in adj[u]: if d[v] > d[u] + w: ...
Fifa and Fafa are sharing a flat. Fifa loves video games and wants to download a new soccer game. Unfortunately, Fafa heavily uses the internet which consumes the quota. Fifa can access the internet through his Wi-Fi access point. This access point can be accessed within a range of r meters (this range can be chosen by...
3
import math R,x1,y1,x2,y2=map(int,input().split()) x=math.sqrt((x2-x1)**2 + (y2-y1)**2) if(x>R): print(x1,y1,R) else: if(x==0): print(x1+R/2,y1,R/2) else: x3=x2+(x1-x2)*((R+x)/2)/x y3=y2 + (y1-y2)*(R+x)/2/x print(x3,y3,(R+x)/2)
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
for _ in range(int(input())): x,y,a,b=map(int,input().split()) if((y-x)%(a+b)==0): print((y-x)//(a+b)) else: print(-1)
You are given a rectangular board of M × N squares. Also you are given an unlimited number of standard domino pieces of 2 × 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
1
m, n = [int(i) for i in raw_input().split(' ')] print (m * n) / 2
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...
1
n=input() i=n+1 #k=0 s="" s1="" while i: s=str(i) for j in s: if j not in s1: s1+=j else: #print i #k+=1 break if s==s1: break s1="" i+=1 print s
Artem has an array of n positive integers. Artem decided to play with it. The game consists of n moves. Each move goes like this. Artem chooses some element of the array and removes it. For that, he gets min(a, b) points, where a and b are numbers that were adjacent with the removed number. If the number doesn't have a...
1
n,a,s,ans=raw_input(),map(int,raw_input().split(' ')),[],0 for i in a: while len(s)>1 and s[-1]<=i and s[-2]>=s[-1]: ans+=min(i,s[-2]) del(s[-1]) s.append(i) s.sort() print ans+sum(s[0:-2])
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
x = 0 for i in range(int(input())): o = input() if "++" in o: x += 1 else: x -= 1 print(x)
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are n lines in that description each of which described one goal. Eve...
1
teams = [raw_input() for i in xrange(input())] win_times = reduce(max, [teams.count(i) for i in teams]) print([i for i in teams if win_times == teams.count(i)][0])
This problem is given in two editions, which differ exclusively in the constraints on the number n. You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r). Find a...
3
#!/usr/bin/env python # -*- coding: utf-8 -*- # @oj: codeforces # @id: hitwanyang # @email: 296866643@qq.com # @date: 2020/12/15 19:12 # @url: https://codeforc.es/contest/1141/problem/F1 import sys, os from io import BytesIO, IOBase import collections, itertools, bisect, heapq, math, string from decimal import * # reg...
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si...
3
import sys def solve(n): return n // 2 + 1 caseCount = int(next(sys.stdin)) for i in range(caseCount): x = int(next(sys.stdin)) ans = solve(x) print(ans)
Sasha likes programming. Once, during a very long contest, Sasha decided that he was a bit tired and needed to relax. So he did. But since Sasha isn't an ordinary guy, he prefers to relax unusually. During leisure time Sasha likes to upsolve unsolved problems because upsolving is very useful. Therefore, Sasha decided ...
3
import os import sys from io import BytesIO, IOBase import math from queue import Queue import itertools import bisect import heapq #sys.setrecursionlimit(100000) #^^^TAKE CARE FOR MEMORY LIMIT^^^ def main(): pass BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd ...
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr...
1
y,w = map(int,raw_input().strip().split()) def hcf(a,b): if b!=0: return hcf(b,a%b) else: return a h = hcf(7-max(y,w),6) n = (7-max(y,w))/h d = 6/h print "%d/%d" %(n,d)
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus. She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t...
3
import io import os from collections import Counter, defaultdict, deque def solve(N, A): counts = Counter(A) curr = 0 waiting = 0 for k in sorted(counts.keys()): v = counts[k] if curr + waiting + v >= k: curr += waiting + v waiting = 0 else: ...
One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won. Alex has grown up since then, so he easily wins the most difficu...
3
if __name__ == '__main__': n, m = map(int, input().split()) a = ["." * (m + 2)] + [".%s." % (input()) for _ in range(n)] + ["." * (m + 2)] b = [["."] * (m + 2) for i in range(n + 2)] convert = lambda c: 1 if str(c) == "." else c if str(c) == "*" else c + 1 for i in range(1, n + 1): if "*" ...
In the beginning, Takahashi has A cookies, and Aoki has B cookies. They will perform the following operation alternately, starting from Takahashi: * If the number of cookies in his hand is odd, eat one of those cookies; if the number is even, do nothing. Then, give one-half of the cookies in his hand to the other pers...
3
A,B,K=map(int,input().split()) for i in range(K): A//=2 B+=A A,B=B,A if(K%2): A,B=B,A print(A,B)
There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that <image>, where <image> is bitwise xor operation (see notes for explanation). <image> Immediately, Mehrdad d...
3
someDict={} def sumOfNumbers(m): return (m-1)*m//2 class Pair: def __init__(self,k,y): self.k=k self.y=y a,x=map(lambda x : int(x), input().split()) arr=list(map( lambda x : int(x), input().split() )) for i in arr: if i in someDict.keys() or i^x in someDict.keys(): if i in someDict.k...
We have two distinct integers A and B. Print the integer K such that |A - K| = |B - K|. If such an integer does not exist, print `IMPOSSIBLE` instead. Constraints * All values in input are integers. * 0 \leq A,\ B \leq 10^9 * A and B are distinct. Input Input is given from Standard Input in the following format: ...
3
a,b=map(int,input().split()) print((a+b)//2 if (a+b)//2 == (a+b)/2 else 'IMPOSSIBLE')
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
s = list(input()) m = list('hello') for c in s: if c == m[0]: if len(m) == 1: m = [] break m = m[1:] if len(m) == 0: print('YES') else: print('NO')
Inna is a great piano player and Dima is a modest guitar player. Dima has recently written a song and they want to play it together. Of course, Sereja wants to listen to the song very much. A song is a sequence of notes. Dima and Inna want to play each note at the same time. At that, they can play the i-th note at vo...
3
n = int(input()) a = list(map(int, input().split(' '))) b = list(map(int, input().split(' '))) sum = 0 for i in range(n): if b[i] == 1 or a[i] + a[i] < b[i]: sum = sum - 1 else: sum = sum + (b[i] // 2) * (b[i] - b[i] // 2) print(sum)
Anton likes to play chess. Also he likes to do programming. No wonder that he decided to attend chess classes and programming classes. Anton has n variants when he will attend chess classes, i-th variant is given by a period of time (l1, i, r1, i). Also he has m variants when he will attend programming classes, i-th v...
3
mn,mx=1<<31,0 mn1,mx1=1<<31,0 def li():return list(map(int,input().split())) for x in range(int(input())): l,r=li() if r<mn:mn=r if mx1<l:mx1=l for x in range(int(input())): l,r=li() if l>mx:mx=l if mn1>r:mn1=r if mx>mn or mx1>mn1:print(max(mx-mn,mx1-mn1)) else:print(0)
"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
inp= input() n,k = int(inp.split()[0]),int(inp.split()[1]) arr = input() arr = list(map(lambda el :int(el),arr.split())) if(n>=k): t_p =0 ts= arr[k-1] for el in arr: if(el>0 and el>=ts): t_p+=1 else: break print(t_p) else: print(0)
Orac is studying number theory, and he is interested in the properties of divisors. For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b. For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1. For example, f(7)=7,f(10)=2,f(35)=5. ...
3
# import sys # sys.setrecursionlimit(10**5) from collections import defaultdict geta = lambda fn: list(map(fn, input().split())) gete = lambda fn: fn(input()) for _ in range(gete(int)): n, k = geta(int) if n & 1 == 0: print(n + k * 2) else: d = 3 ok = False while d * d <= ...
At first, there was a legend related to the name of the problem, but now it's just a formal statement. You are given n points a_1, a_2, ..., a_n on the OX axis. Now you are asked to find such an integer point x on OX axis that f_k(x) is minimal possible. The function f_k(x) can be described in the following way: ...
3
def main(): buf = input() T = int(buf) n = [] k = [] a = [] for i in range(T): buf = input() buflist = buf.split() n.append(int(buflist[0])) k.append(int(buflist[1])) buf = input() buflist = buf.split() a.append(list(map(int, buflist))) ...
Jamie loves sleeping. One day, he decides that he needs to wake up at exactly hh: mm. However, he hates waking up, so he wants to make waking up less painful by setting the alarm at a lucky time. He will then press the snooze button every x minutes until hh: mm is reached, and only then he will wake up. He wants to kno...
3
if __name__ == "__main__": x = int(input()) hh,mm=map(int, input().split()) s = str(hh)+str(mm) count=0 while '7' not in s: mm-=x if mm < 0: hh-=1 mm=60+mm count +=1 s = str(hh)+str(mm) print(count)
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
if __name__ == "__main__": set = input(); set = set[1:len(set) - 1] if len(set) == 0: print(0) else: set = set.split(", ") count = 0 dict = {} for ch in set: if ch not in dict: dict[ch] = 1 count += 1 print(len(d...
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`. Constraints * 2 ≤ N ≤ 200000 * 1 ≤ A_i ≤ 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 ... A_N Output If the elements...
3
n = int(input()) a = set(map(int, input().split())) print('YES') if n==len(a) else print('NO')
While playing with geometric figures Alex has accidentally invented a concept of a n-th order rhombus in a cell grid. A 1-st order rhombus is just a square 1 × 1 (i.e just a cell). A n-th order rhombus for all n ≥ 2 one obtains from a n-1-th order rhombus adding all cells which have a common side with it to it (look ...
3
a = int(input()) print(2 * a ** 2 - 2 * a + 1)
Polycarp loves ciphers. He has invented his own cipher called repeating. Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm: * he writes down s_1 ones, * he writes down s_2 twice, * he writes down s_3 three times, * ... ...
3
t = int(input()) r = input() index = 0 string = '' n = (pow(1 + 8*t,0.5)-1)//2 n = int(n) for i in range(1, n+1): string += r[index] index += i print(string)
A permutation of length n is an array p=[p_1,p_2,...,p_n], which contains every integer from 1 to n (inclusive) and, moreover, each number appears exactly once. For example, p=[3,1,4,2,5] is a permutation of length 5. For a given number n (n ≥ 2), find a permutation p in which absolute difference (that is, the absolut...
3
def solve(n): if(n<4): print(-1) return ans=[] l=n if(n%2==0): l=n-1 while(l>0): ans.append(l) l-=2 ans.extend([4,2]) l=6 while (l<=n): ans.append(l) l+=2 print(*ans,sep=" ") t=int(input()) for _ in range(t): n=int(input()) solve(n)
Do you know a story about the three musketeers? Anyway, you will learn about its origins now. Richelimakieu is a cardinal in the city of Bearis. He is tired of dealing with crime by himself. He needs three brave warriors to help him to fight against bad guys. There are n warriors. Richelimakieu wants to choose three ...
1
from sys import stdin n, m = map(int, stdin.readline().split()) g = [set() for i in range(n)] for _ in range(m): i, j = map(int, stdin.readline().split()) g[i-1].add(j-1) g[j-1].add(i-1) m = float('inf') for i in range(len(g)-1): wi = len(g[i]) for j in range(1, len(g)): wj = len(g[j]) ...
One evening Rainbow Dash and Fluttershy have come up with a game. Since the ponies are friends, they have decided not to compete in the game but to pursue a common goal. The game starts on a square flat grid, which initially has the outline borders built up. Rainbow Dash and Fluttershy have flat square blocks with si...
3
import sys input=sys.stdin.buffer.readline from collections import deque as que, defaultdict as vector, Counter from bisect import bisect as bsearch from heapq import* inin = lambda: int(input()) inar = lambda: list(map(int,input().split())) inst= lambda: input().decode().rstrip('\n\r') INF=float('inf') '''from types i...
You are given two integer sequences S and T of length N and M, respectively, both consisting of integers between 1 and 10^5 (inclusive). In how many pairs of a subsequence of S and a subsequence of T do the two subsequences are the same in content? Here the subsequence of A is a sequence obtained by removing zero or ...
3
N, M = map(int, input().split()) s_list = list(map(int, input().split())) t_list = list(map(int, input().split())) mod = 10 ** 9 + 7 dp = [[0 for _ in range(M + 1)] for _ in range(N + 1)] for i in range(1, N + 1): for j in range(1, M + 1): if s_list[i - 1] == t_list[j - 1]: dp[i][j] += dp[i - 1]...
The door of Snuke's laboratory is locked with a security code. The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same. You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`. Constraint...
1
#!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip import random import collections import math import itert...