problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Nastya owns too many arrays now, so she wants to delete the least important of them. However, she discovered that this array is magic! Nastya now knows that the array has the following properties: * In one second we can add an arbitrary (possibly negative) integer to all elements of the array that are not equal to z...
3
n = int(input()) l = list(map(int,input().split())) x = set(l) if 0 in x : x.remove(0) print(len(x))
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a: * Swap any two bits at indices i and j respectively (1 ≤ i, j ≤ n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. * Select any arbitrary index i (1 ...
3
from sys import stdin input=lambda : stdin.readline() from math import ceil,sqrt,gcd,factorial n=int(input()) a=list(input().strip()) b=list(input().strip()) l=[0 for i in range(n)] for i in range(n): if a[i]!=b[i]: if a[i]=='0': l[i]=2 else: l[i]=1 count=0 for i in range(1,n): if l[i]==1: if l[i-1]==2: ...
You are given an array a_1, a_2, ..., a_n, consisting of n positive integers. Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves: 1. move right — go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n. 2. mo...
3
import math T = int(input()) for i in range(T): #n = int(input()) n,k,z = map(int, input().split()) a = list(map(int,input().split())) #a = list(input()) d = False """if z == 0: print(sum(a[:n])) continue""" dp = [[0]*(z+1) for i in range(n)] dp[0][0] = a[0] for i in range(1,n): dp[...
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...
3
n=int(input()) l=list(map(int,input().split())) for i in range(1,n+1): m=l.index(i)+1 print(m,end=" ")
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
t=int(input()) for i in range(t): n=int(input()) lst = list(map(int, input().strip().split(' '))) lst.sort() f=0 for j in reversed(range(n)): if (j+1)>=lst[j]: f=j+1 break print(f+1)
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right. AquaMoon can make some operations on friends. On each operation, AquaM...
3
for _ in range(int(input())): n = int(input()) l = list(map(int, input().split())) d1 = {} d2 = {} for x in range(n): if l[x] not in d1: d1[l[x]] = x % 2 else: d1[l[x]] += x % 2 l.sort() for x in range(n): if l[x] not in d2: d2[l...
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves. We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair m...
3
k = map(int, input().split()) a = list(map(int, input().split())) k = map(int, input().split()) b = list(map(int, input().split())) a,b = sorted(a), sorted(b) count, i, j = 0, 0, 0 while(i < len(a) and j < len(b)): if abs(a[i] - b[j]) <= 1: count += 1 i += 1 j += 1 continue else:...
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'...
1
import math def c(x,y,a): return int(math.ceil(1.0*x/a)*math.ceil(1.0*y/a)) x,y,a = map(int,raw_input().split()) print c(x,y,a)
Kurohashi has never participated in AtCoder Beginner Contest (ABC). The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same. What is the earliest ABC where Kurohashi can make his debut? Constraints * 100 \leq N...
3
n = int(input()) if n%111==0: print(n) else: print(n+111-(n%111))
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
size = int(input()) s = input() if s.count('A') > s.count('D'): print("Anton") elif s.count('D') > s.count('A'): print("Danik") else: print("Friendship")
The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang. The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital. The capital's main detective Polycarpus took a map and marked ...
3
a,b=map(int,input().split());x=[];d=[];cnt1=0;cnt2=0;r=0;c=0;k=0 for i in range(a) : d=list(input()) x.append(d) for i in range(a) : cnt1=0;cnt2=0 for j in range(b) : if x[i][j]=="*": cnt1+=1 elif x[i][j]==".": cnt2+=1 if cnt1==1 and cnt2>=1: r=i;k=1;b...
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
import sys count=0 s=input() for i in range(len(s)): if s[i]=='h': count+=1 break try: for j in range(i+1,len(s)): if s[j]=='e': count+=1 break except: print("NO") sys.exit() try: for k in range(j+1,len(s)): if s[k]=='l': count+=1 break except: print("NO") sys.exit() try: for l in range(k+...
When Serezha was three years old, he was given a set of cards with letters for his birthday. They were arranged into words in the way which formed the boy's mother favorite number in binary notation. Serezha started playing with them immediately and shuffled them because he wasn't yet able to read. His father decided t...
3
n = int(input()) word = input() z,e,r,o,n=0,0,0,0,0 for i in word: if i =="z":z+=1 elif i =="e":e+=1 elif i =="r":r+=1 elif i =="o":o+=1 elif i =="n":n+=1 temp1 = min([o,n,e]) o-=temp1 n-=temp1 e-=temp1 temp2 = min([z,e,r,o]) print(*[1 for i in range(temp1)] + [0 for i in range(temp2)])
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels the bo...
1
a = int(raw_input()) from math import log10 a = a + 1 print a*(int(log10(a)) + 1) - 10*(10**int(log10(a)) -1)/9 - 1
Polycarp has built his own web service. Being a modern web service it includes login feature. And that always implies password security problems. Polycarp decided to store the hash of the password, generated by the following algorithm: 1. take the password p, consisting of lowercase Latin letters, and shuffle the l...
3
from collections import Counter for _ in range(int(input())): s1=list(input()) s2=list(input()) d1=Counter(s1) ans="NO" for i in range(len(s2)): for j in range(i,len(s2)+1): if(d1==Counter(s2[i:j])): ans="YES" break print(ans)
Let \mathrm{popcount}(n) be the number of `1`s in the binary representation of n. For example, \mathrm{popcount}(3) = 2, \mathrm{popcount}(7) = 3, and \mathrm{popcount}(0) = 0. Let f(n) be the number of times the following operation will be done when we repeat it until n becomes 0: "replace n with the remainder when n...
3
from sys import stdin import sys import itertools import array import textwrap import math N = int(input()) X = input() temp = X.count("1") t = [0, 0, 0] t[0] = int(X, 2) % (temp-1) if temp != 1 else 0 t[2] = int(X, 2) % (temp+1) cnt = 0 for i in range(N): if X[i] == "1" and temp == 1: print(0) co...
Kirito is stuck on a level of the MMORPG he is playing now. To move on in the game, he's got to defeat all n dragons that live on this level. Kirito and the dragons have strength, which is represented by an integer. In the duel between two opponents the duel's outcome is determined by their strength. Initially, Kirito'...
3
s, n = map(int, input().split()) res = 'YES' lst = [] for i in range(n): x, y = map(int, input().split()) lst.append([x, y]) lst.sort(key = lambda x: x[0]) for i in lst: if s <= i[0]: res = 'NO' break else: s += i[1] print(res)
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied: * For any two vertices p...
3
N = int(input()) links = [[] for _ in range(N)] for _ in range(N - 1): u, v, w = map(int, input().split()) links[u - 1].append((v - 1, w)) links[v - 1].append((u - 1, w)) distance = [-1] * N distance[0] = 0 q = [0] while q: p = q.pop() for n, w in links[p]: if distance[n] == -1: ...
Kana was just an ordinary high school girl before a talent scout discovered her. Then, she became an idol. But different from the stereotype, she is also a gameholic. One day Kana gets interested in a new adventure game called Dragon Quest. In this game, her quest is to beat a dragon. <image> The dragon has a hit p...
3
from math import floor def main(): t = int(input()) for _ in range(t): l = list(map(int, input().split())) h, v, l = l[0], l[1], l[2] while h > 20 and v > 0: h = floor(h/2) + 10 v -= 1 h -= 10 * l if h > 0: print("NO") else: pri...
It is known that the area of a regular dodecagon inscribed in a circle of radius a is 3a^2. Given an integer r, find the area of a regular dodecagon inscribed in a circle of radius r. Constraints * 1 \leq r \leq 100 * r is an integer. Input Input is given from Standard Input in the following format: r Output ...
3
x = input() print(int(x)*int(x)*3)
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()) inp=list(input())[:n] c=0 for i in range(1,n): if(inp[i]==inp[i-1]): c+=1 print(c)
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
n=raw_input().split() y=int(n[0]) w=int(n[1]) t=max(y,w) t=6-t+1 if t==1 : print "1/6" elif t==2: print "1/3" elif t==3: print "1/2" elif t==4: print "2/3" elif t==5: print "5/6" else: print "1/1"
Snuke prepared 6 problems for a upcoming programming contest. For each of those problems, Rng judged whether it can be used in the contest or not. You are given a string S of length 6. If the i-th character of s is `1`, it means that the i-th problem prepared by Snuke is accepted to be used; `0` means that the problem...
1
sum = 0 for x in raw_input(): sum += int(x) print sum
Leo has developed a new programming language C+=. In C+=, integer variables can only be changed with a "+=" operation that adds the right-hand side value to the left-hand side variable. For example, performing "a += b" when a = 2, b = 3 changes the value of a to 5 (the value of b does not change). In a prototype progr...
3
t = int(input()) F = [0]*(1000) F[0] = 1 F[1] = 1 for i in range(2, 1000): F[i] = F[i-1]+F[i-2] #print(F[0:10]) #print(F[-1]) for _ in range(t): a, b, n = map(int, input().split()) x, y = min(a, b), max(a, b) for i in range(1, 1000): if F[i]*y + F[i-1]*x > n: print(i) bre...
We have N+M balls, each of which has an integer written on it. It is known that: * The numbers written on N of the balls are even. * The numbers written on M of the balls are odd. Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even. It c...
3
n,m=map(int,input().split()) print(int(n*(n-1)/2)+int(m*(m-1)/2))
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl...
3
n,m=list(map(int,input().split())) a=list(map(int,input().split())) a.sort() diff=[] for i in range(0,m-n+1): diff.append(abs(a[i]-a[i+n-1])) print(min(diff))
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer. At the start of the day they have x ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the q...
3
n, x = map(int, input().split()) d = 0 for i in range(n): s = input() if s[0]=='+': x+=int(s[2:]) elif int(s[2:])<=x: x-=int(s[2:]) else: d+=1 print(x, d)
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
#!/usr/bin/env python #-*- coding:utf-8 -*- import sys, math, random, operator from string import ascii_lowercase, ascii_uppercase from fractions import Fraction, gcd #from decimal import Decimal, getcontext from itertools import product, permutations, combinations from Queue import Queue, PriorityQueue from collectio...
We have N voting papers. The i-th vote (1 \leq i \leq N) has the string S_i written on it. Print all strings that are written on the most number of votes, in lexicographical order. Constraints * 1 \leq N \leq 2 \times 10^5 * S_i (1 \leq i \leq N) are strings consisting of lowercase English letters. * The length of S...
3
from collections import defaultdict d=defaultdict(int) n=int(input()) for i in range(n): s=input() d[s]+=1 M=max(d.values()) d1 = sorted(d.items()) for i,k in d1: if k==M: print(i)
There is a hotel with the following accommodation fee: * X yen (the currency of Japan) per night, for the first K nights * Y yen per night, for the (K+1)-th and subsequent nights Tak is staying at this hotel for N consecutive nights. Find his total accommodation fee. Constraints * 1 \leq N, K \leq 10000 * 1 \leq ...
3
n,k,x,y=[int(input())for _ in [0]*4] print(n*x) if n<k else print(y*(n-k)+x*k)
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
a = input() low = high = 0 for i in a: if(i.islower()): low += 1 else: high += 1 if(low >= high): print(a.lower()) else: print(a.upper())
A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree. A binary heap data structure is an array...
3
h = int(input()) t = input().split() for i in range(h): ans = f"node {i+1}: key = {t[i]}, " p = (i+1)//2-1 if p >= 0: ans += f"parent key = {t[min([p,h])]}, " l, r = (i+1)*2-1, (i+1)*2 if l < h: ans += f"left key = {t[l]}, " if r < h: ans += f"right key = {t[r]}, ...
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 = int(input("")) if w > 2 and w < 101: if w % 2 == 0: print("YES") else: print("NO") else: print("NO")
You are given an integer n. You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times: 1. Replace n with n/2 if n is divisible by 2; 2. Replace n with 2n/3 if n is divisible by 3; 3. Replace n with 4n/5 if n is divisible by 5. For example, you can repl...
3
#------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "...
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible. The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S. Input The first line of the input ...
3
a = int(input()) a %= 4 if a == 0 or a == 3: print(0) else: print(1)
There are two standard ways to represent a graph $G = (V, E)$, where $V$ is a set of vertices and $E$ is a set of edges; Adjacency list representation and Adjacency matrix representation. An adjacency-list representation consists of an array $Adj[|V|]$ of $|V|$ lists, one for each vertex in $V$. For each $u \in V$, th...
3
# Graph I - Graph n = int(input()) for _ in range(n): ss = list(map(int, input().split())) u = ss[0] - 1 row = [0 for _ in range(n)] for i in range(ss[1]): idx = 2 + i row[ss[idx]-1] = 1 print(*row)
Given is a positive integer L. Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L. Constraints * 1 ≤ L ≤ 1000 * L is an integer. Input Input is given from Standard Input in the following format: L Output Print the maximum possible volume of a re...
3
は=int(input()) print((は/3)**3)
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The ...
1
N, M = map(int, raw_input().split()) ret = [0] * M L = (M + 1) / 2 R = L + 1 for i in range(0, min(N, M)): if abs(M + 1 - 2 * L) <= abs(M + 1 - 2 * R): ret[i] = L L -= 1 else: ret[i] = R R += 1 for i in range(0, N): print ret[i % M]
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
from math import * for i in range(int(input())): m, g, b=map(int, input().split()) needG=int(ceil(m/2)) mul=needG//g totalG=mul*(g+b) M=needG%g if needG%g==0: totalG-=b else: totalG+=M print(max(m, totalG))
DZY loves chessboard, and he enjoys playing with it. He has a chessboard of n rows and m columns. Some cells of the chessboard are bad, others are good. For every good cell, DZY wants to put a chessman on it. Each chessman is either white or black. After putting all chessmen, DZY wants that no two chessmen with the sa...
3
a,b=map(int,input().split()) for i in range(a): x="";z=input() for j in range(b): if z[j]==".":x+="BW"[(i+j)&1] else:x+=z[j] print(x)
Monk's birthday is coming this weekend! He wants to plan a Birthday party and is preparing an invite list with his friend Puchi. He asks Puchi to tell him names to add to the list. Puchi is a random guy and keeps coming up with names of people randomly to add to the invite list, even if the name is already on the list...
1
def fun(): n=input() l=[] for i in range(n): l.append(raw_input()) l=set(l) l=list(l) l.sort() for i in l: print(i) a=input() for i in range(a): fun()
Mahmoud wrote a message s of length n. He wants to send it as a birthday present to his friend Moaz who likes strings. He wrote it on a magical paper but he was surprised because some characters disappeared while writing the string. That's because this magical paper doesn't allow character number i in the English alpha...
3
from sys import stdin, stdout n = int(stdin.readline()) s = stdin.readline().strip() length = list(map(int, stdin.readline().strip().split())) bn = [2 ** i for i in range(10 ** 3 + 2)] dp = [0 for i in range(n + 10)] dp[0] = 1 ans = [0, 1, 0] dp1 = [0 for i in range(n + 5)] dp1[0] = 1 for i in range(1, n): labe...
There are N mountains ranging from east to west, and an ocean to the west. At the top of each mountain, there is an inn. You have decided to choose where to stay from these inns. The height of the i-th mountain from the west is H_i. You can certainly see the ocean from the inn at the top of the westmost mountain. F...
3
n=int(input()) H=list(map(int,input().split())) ans=0 m=-1000 for i in range(n): if m<=H[i]: m=H[i] ans+=1 print(ans)
You are given an array of n integer numbers a0, a1, ..., an - 1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times. Input The first line contains positive integer n (2 ≤ n ≤ 105) — size of the given array. The second line contains n ...
1
t=int(raw_input()) s=map(int,raw_input().strip().split(' ')) q=[] a=[] k=[] for i in s: q.append(i) s.sort() l=s[0] for i in range(0,t): if q[i]==l: a.append(i) for i in range(1,len(a)): k.append(a[i]-a[i-1]) k.sort() print k[0]
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n = int(input()) l = input() s = l.split(" ") s = [int(x) for x in s] if max(s) == 1: print ("HARD") else: print("EASY")
You are given two strings of equal length s and t consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings. During each operation you choose two adjacent characters in any string and assign the value of the first character to the value of the second or vice versa. ...
3
s = 'abcdefghijklmnopqrstuvwxyz' Q = int(input()) for q in range(Q): s1 = input() s2 = input() if len(s1) != len(s2): print('NO') continue flag = False for i in s: if i in s1 and i in s2: print('YES') flag = True break if not flag: ...
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes. Input The single line of the input contains a pa...
3
m, s = map(int, input().split()) if s == 0 and m > 1: print('-1 -1') elif s == 0 and m == 1: print('0 0') else: nmax = '' nmin = '' ts= s for i in range(m - 1): if ts > 9: nmin = '9' + nmin ts -= 9 else: nmin = chr(ts + 47) + nmin ...
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u...
3
n = int(input()) t = list(map(int, input().split())) d, a, b = abs(t[-1] - t[0]), n, 1 for i in range(1, n): k = abs(t[i] - t[i - 1]) if k < d: d, a, b = k, i, i + 1 if d == 0: break print(a, b)
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, b, c = int(input()), int(input()), int(input()) s1 = a + b + c s2 = a * b * c s3 = a * b + c s4 = (a + b) * c s5 = a * (b + c) s6 = a + (b * c) print(max(s1, s2, s3, s4, s5, s6))
Almost Identical Programs The programming contest named Concours de Programmation Comtemporaine Interuniversitaire (CPCI) has a judging system similar to that of ICPC; contestants have to submit correct outputs for two different inputs to be accepted as a correct solution. Each of the submissions should include the pr...
3
while 1: s1 = input().split('"') if s1 == ['.']: break s2 = input().split('"') if len(s1) != len(s2): print("DIFFERENT") continue r = [0]*2 for i in range(len(s1)): if s1[i] != s2[i]: r[i%2] += 1 if [0,1]<r: print("DIFFERENT") else: ...
Ann has recently started commuting by subway. We know that a one ride subway ticket costs a rubles. Besides, Ann found out that she can buy a special ticket for m rides (she can buy it several times). It costs b rubles. Ann did the math; she will need to use subway n times. Help Ann, tell her what is the minimum sum of...
1
Viajes,BoletoM,PrecioUno,PrecioM = [int(x) for x in raw_input().split() ] P1=Viajes*PrecioUno if(Viajes/BoletoM==0): P2=PrecioM else: if(Viajes%BoletoM==0): P2=(Viajes/BoletoM)*PrecioM else: P2=((Viajes/BoletoM)+1)*PrecioM if(Viajes%BoletoM!=0): P3=((Viajes/BoletoM)*PrecioM)+((Viajes%Bol...
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...
1
x=input() s=raw_input() c=[] a=s[0] k=0 for i in range(len(s)): if(i==0): c.append(s[i]) if(s[i]!=a): c.append(s[i]) a=s[i] else: k=k+1 print k-1
"Night gathers, and now my watch begins. It shall not end until my death. I shall take no wife, hold no lands, father no children. I shall wear no crowns and win no glory. I shall live and die at my post. I am the sword in the darkness. I am the watcher on the walls. I am the shield that guards the realms of men. I ple...
3
n = int(input()) A = list(map(int, input().split())) ans = 0 x = max(A) y = min(A) for i in range(len(A)): if A[i] > y and A[i] < x: ans += 1 print(ans)
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th...
3
a=input() s=0 b=0 for i in range(len(a)): if(a[i]>='A' and a[i]<='Z'): b+=1 else: s+=1 if(b>s): print(a.upper()) else: print(a.lower())
Vasya has a string s of length n. He decides to make the following modification to the string: 1. Pick an integer k, (1 ≤ k ≤ n). 2. For i from 1 to n-k+1, reverse the substring s[i:i+k-1] of s. For example, if string s is qwer and k = 2, below is the series of transformations the string goes through: * qwe...
3
t = int(input()) while t: t -= 1 n = int(input()) s = input() if len(set(s)) == 1: print(s) print(1) continue s = ' ' + s ans, ansk = s, 1 for k in range(2, n + 1): st = " " + s[k:] + (s[1:k] if n % 2 != k % 2 else s[1:k][::-1]) if (st == ans and (k < ...
There are N boxes arranged in a circle. The i-th box contains A_i stones. Determine whether it is possible to remove all the stones from the boxes by repeatedly performing the following operation: * Select one box. Let the box be the i-th box. Then, for each j from 1 through N, remove exactly j stones from the (i+j)-...
3
n = int(input()) a = list(map(int, input().split())) if sum(a) % (n * (n + 1) // 2) != 0: print("NO") else: k = sum(a) // (n * (n + 1) // 2) ok = True for i in range(n - 1): if (a[i] + k) % n != a[i + 1] % n or a[i] + k < a[i + 1]: ok = False break if (a[-1] + k) % n != a[0] % n or a[-1] + k < a[0]: ok =...
You have been blessed as a child of Omkar. To express your gratitude, please solve this problem for Omkar! An array a of length n is called complete if all elements are positive and don't exceed 1000, and for all indices x,y,z (1 ≤ x,y,z ≤ n), a_{x}+a_{y} ≠ a_{z} (not necessarily distinct). You are given one integer ...
3
for k in range(int(input())): n = int(input()) f=[n]*n print(*f)
You went to the store, selling n types of chocolates. There are a_i chocolates of type i in stock. You have unlimited amount of cash (so you are not restricted by any prices) and want to buy as many chocolates as possible. However if you buy x_i chocolates of type i (clearly, 0 ≤ x_i ≤ a_i), then for all 1 ≤ j < i at ...
1
import sys,math from fractions import gcd from collections import defaultdict from io import BytesIO sys.stdin = BytesIO(sys.stdin.read()) input = lambda: sys.stdin.readline().rstrip('\r\n') n = int(input()) arr = [int(x) for x in input().split(' ')] res = 0 cur = arr[-1]+1 for i in range(n-1, -1, -1): cur = max(m...
Let's consider equation: x2 + s(x)·x - n = 0, where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots. Input A sing...
1
from sys import stdin, stdout def f(x): s = 0 y = x while y: s += y % 10 y /= 10 return x*(x + s) def bsearch(l, r): while (l < r - 1): m = (l + r) / 2 if (f(m * 100000) < n): l = m else: r = m return l n = int(stdin.readline().spli...
Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead. A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,...
3
n, m = map(int, input().split()) for i in range(n): if(i % 2 == 0): for j in range(m): print("#", end="") else: if(i % 4 == 1): for j in range(m-1): print(".", end="") print("#", end="") else: print("#", end="") ...
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
count = 0 times = int(input()) while times > 0: x = input() if "--" in x: count -= 1 else: count += 1 times -= 1 print(count)
There are n cities and n - 1 roads in the Seven Kingdoms, each road connects two cities and we can reach any city from any other by the roads. Theon and Yara Greyjoy are on a horse in the first city, they are starting traveling through the roads. But the weather is foggy, so they can’t see where the horse brings them....
3
from math import sqrt,gcd,ceil,floor,log,factorial from itertools import permutations,combinations from collections import Counter, defaultdict import collections,sys,threading import collections,sys,threading sys.setrecursionlimit(10**9) threading.stack_size(10**8) def ii(): return int(input()) def si(): return input...
Alice's hair is growing by leaps and bounds. Maybe the cause of it is the excess of vitamins, or maybe it is some black magic... To prevent this, Alice decided to go to the hairdresser. She wants for her hair length to be at most l centimeters after haircut, where l is her favorite number. Suppose, that the Alice's he...
3
n, m, l = map(int, input().split(' ')) a = list(map(int, input().split(' '))) g = [a[k] > l for k in range(n)] res = [] curr_res = sum([g[0]] + [v for j, v in enumerate(g[1:]) if v != g[j]]) for i in range(m): req = list(map(int, input().split(' '))) if req[0]: req, p, q = req new_len = a[p -...
Allen has a LOT of money. He has n dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are 1, 5, 10, 20, 100. What is the minimum number of bills Allen could receive after withdrawing his entire balance? Input The first...
3
n=int(input()) m=0 while n!=0: if n in range(100,1000000001): m = int(n / 100) n=int(n%100) elif n in range(20,100): n=n-20 m=m+1 elif n in range(10,20): n=n-10 m=m+1 elif n in range(5,10): n=n-5 m=m+1 elif n in range(1,5): n=n...
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
T = int(input()) for _ in range(T): n = int(input()) ls = list(map(int, input().split())) ls.sort() ans = 'Yes' for i in range(1, n): if abs(ls[i] - ls[i-1]) > 1: ans = 'No' break print(ans)
You are given a integer n (n > 0). Find any integer s which satisfies these conditions, or report that there are no such numbers: In the decimal representation of s: * s > 0, * s consists of n digits, * no digit in s equals 0, * s is not divisible by any of it's digits. Input The input consists of mult...
3
A = [] T = int(input()) for i in range (T): A.append(int(input())) for n in A: if n == 1: print(-1) else: print(2, end = '') for j in range (n - 2): print(3, end = '') print(3)
Marina loves Sasha. But she keeps wondering whether Sasha loves her. Of course, the best way to know it is fortune telling. There are many ways of telling fortune, but Marina has picked the easiest one. She takes in her hand one or several camomiles and tears off the petals one by one. After each petal she pronounces a...
3
dontcare=input() a=[int(i) for i in input().split()] sum=0 for i in a:sum+=i if sum%2==1:print(sum) else: max=sum for i in a: if i%2==1: max-=i break for i in a: if i%2==1 and sum-i>max:max=sum-i if max%2==1:print(max) else:print(0)
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...
3
# 96A. Football st = input() if "0000000" in st or "1111111" in st: print("YES") else: print("NO")
A string is called a k-string if it can be represented as k concatenated copies of some string. For example, the string "aabaabaabaab" is at the same time a 1-string, a 2-string and a 4-string, but it is not a 3-string, a 5-string, or a 6-string and so on. Obviously any string is a 1-string. You are given a string s, ...
3
import math from functools import reduce k=int(input()) s=input() d={} for i in s: if i not in d: d[i]=1 else: d[i]+=1 a=[*d.values()] w=reduce(lambda x,y:math.gcd(x,y),a) if(w%k==0): q="" for key,value in d.items(): p=value//k r=key*p q+=r print(q*k) else: ...
We have a permutation of the integers from 1 through N, p_1, p_2, .., p_N. We also have M pairs of two integers between 1 and N (inclusive), represented as (x_1,y_1), (x_2,y_2), .., (x_M,y_M). AtCoDeer the deer is going to perform the following operation on p as many times as desired so that the number of i (1 ≤ i ≤ N)...
3
n, m = map(int, input().split()) p = list(map(int, input().split())) xy = [list(map(int, input().split())) for _ in range(m)] from collections import defaultdict g = defaultdict(list) for x, y in xy: x, y = x - 1, y - 1 g[x].append(y) g[y].append(x) visited = [0] * n ans = 0 for i in range(n): if vis...
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
3
t = int(input()) while(t>0): d = int(input()) n = input() if(d==1): if(int(n)%2==0): print("2") else: print("1") elif(d%2==0): l = [int(n[i]) for i in range(len(n)) if(i%2!=0 and int(n[i])%2!=0)] if(len(l)<d//2): print("2") ...
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()) count = 0 for i in range(1,W+1): count += K*i if count-N <= 0: print('0') else: print(count-N)
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 ...
1
n,a,b=map(int,raw_input().split()) m=n-a if m>b: print(b+1) else: print(m)
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
def cost(bananas, k): cost = 0 for i in range(bananas): cost = cost + k * (i + 1) return cost numbers = input().split() if(cost(int(numbers[2]), int(numbers[0])) <= int(numbers[1])): print(0) else: print (cost(int(numbers[2]), int(numbers[0])) - int(numbers[1]))
Phoenix has a string s consisting of lowercase Latin letters. He wants to distribute all the letters of his string into k non-empty strings a_1, a_2, ..., a_k such that every letter of s goes to exactly one of the strings a_i. The strings a_i do not need to be substrings of s. Phoenix can distribute letters of s and re...
3
for t in range(int(input())): n, k = map(int, input().split()) ss = sorted(input().strip()) diff = -1 for i in range(k-1): if ss[i] != ss[i+1]: diff = i break if diff != -1 or n == k: print(ss[k-1]) elif ss[k] == ss[-1]: print(ss[k-1] + ss[k] * ((n...
wHAT DO WE NEED cAPS LOCK FOR? Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage. Let's consider that a word has been typed with the Caps lock key accidentall...
3
word = input() if len(word) == 1: if word.isupper(): word = word.lower() else: word = word.upper() elif word[1:].isupper(): word = word[0] + word[1:].lower() if word[0].isupper(): word = word[0].lower() + word[1:] else: word = word[0].upper() + word[1:] print(word)
Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the...
3
o = input() e = input() oe = "".join([i + j for i, j in zip(o,e+"\n")]) print(oe)
Try guessing the statement from this picture <http://tiny.cc/ogyoiz>. You are given two integers A and B, calculate the number of pairs (a, b) such that 1 ≤ a ≤ A, 1 ≤ b ≤ B, and the equation a ⋅ b + a + b = conc(a, b) is true; conc(a, b) is the concatenation of a and b (for example, conc(12, 23) = 1223, conc(100, 11)...
3
for i in range(int(input())): a, b = map(int, input().split()) cnt = len(str(b)) - (1 if str(b).count('9') != len(str(b)) else 0) print(a * cnt)
One Sunday Petr went to a bookshop and bought a new book on sports programming. The book had exactly n pages. Petr decided to start reading it starting from the next day, that is, from Monday. Petr's got a very tight schedule and for each day of the week he knows how many pages he will be able to read on that day. Som...
3
def read(n,x): pages = n while pages > 0: for i in range(0,len(x)): pages -= x[i] if pages <= 0: return i+1 if __name__ == "__main__": n = int(input()) x = list(map(int,input().split())) print(read(n,x))
There are n piranhas with sizes a_1, a_2, …, a_n in the aquarium. Piranhas are numbered from left to right in order they live in the aquarium. Scientists of the Berland State University want to find if there is dominant piranha in the aquarium. The piranha is called dominant if it can eat all the other piranhas in the...
3
for _ in range(int(input())): n=int(input()) a=[int(i) for i in input().split()] m=max(a) if(a.count(m)==n): print(-1) continue ans=[] for i in range(n): if(a[i]==m): ans.append(i) x=0 for i in ans: if(i+1<n and a[i]>a[i+1]) or (i-1>=0 and a[i...
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place. To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t...
1
import sys cases=sys.stdin.readlines() n=int(cases[0])+1 fingers=sum(map(int,cases[1].split())) #print n,fingers ans=0 for x in range(1,6): tot=fingers+x sol=(tot%n)-1 if sol!=0: ans+=1 print ans
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm: * if the last digit of the number is non-zero, she decreases the number by one; * if the last digit of the number is ze...
3
one,two=input().split(' ') n=int(one) k=int(two) for i in range(k): if n%10==0: n/=10 else: n-=1 print(int(n))
Alice and Bob are playing yet another card game. This time the rules are the following. There are n cards lying in a row in front of them. The i-th card has value a_i. First, Alice chooses a non-empty consecutive segment of cards [l; r] (l ≤ r). After that Bob removes a single card j from that segment (l ≤ j ≤ r). Th...
3
import io,os input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys def main(): n=int(input()) A=tuple(map(int,input().split())) DP=[[-float('inf')]*61 for _ in range(n+1)] DP[0][30]=0 for i,a in enumerate(A): DP[i+1][a+30]=0 #print(i+1,a+30) #print(DP[i+1][a+3...
Lunar New Year is approaching, and Bob is struggling with his homework – a number division problem. There are n positive integers a_1, a_2, …, a_n on Bob's homework paper, where n is always an even number. Bob is asked to divide those numbers into groups, where each group must contain at least 2 numbers. Suppose the n...
1
"Template made by : https://codeforces.com/profile/c1729 , github repo : https://github.com/cheran-senthil/PyRival" from __future__ import division, print_function import bisect import math import itertools import sys from atexit import register if sys.version_info[0] < 3: from io import BytesIO as stream else: ...
Let's denote d(n) as the number of divisors of a positive integer n. You are given three integers a, b and c. Your task is to calculate the following sum: <image> Find the sum modulo 1073741824 (230). Input The first line contains three space-separated integers a, b and c (1 ≤ a, b, c ≤ 100). Output Print a singl...
3
#NTFS: neharika_shah from collections import defaultdict mod = 1073741824 a,b,c = map(int,input().split()) def primeFactors(n): dic = defaultdict(int) factors = [] while n % 2 == 0: dic[2] += 1 n = n // 2 i = 3 while i * i <= n: while n % i == 0: dic[i] += 1 n = n // i i += 2 if n > 2: dic[n]...
Two players play a game. Initially there are n integers a_1, a_2, …, a_n written on the board. Each turn a player selects one number and erases it from the board. This continues until there is only one number left on the board, i. e. n - 1 turns are made. The first player makes the first move, then players alternate t...
3
n = int(input()) a = [int(x) for x in input().split()] a.sort() if n % 2: print(a[n // 2]) else: print(a[n // 2 - 1])
It’s still hot every day, but September has already come. It’s autumn according to the calendar. Looking around, I see two red dragonflies at rest on the wall in front of me. It’s autumn indeed. When two red dragonflies’ positional information as measured from the end of the wall is given, make a program to calculate ...
3
x, y = input().split(' ') print(abs(int(x) - int(y)))
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following. Iahub wants to draw n distinct points and m segme...
1
#Author: squiggly_lines #Date: 31/05/2014 #Problem: 430A.py def main(): n,m = map(int, raw_input().split()) x = map(int, raw_input().split()) x2 = [(x[i],i) for i in xrange(n)] segments = [] for i in xrange(m): l,r = map(int, raw_input().split()) segments.append((l,r)) ...
The next lecture in a high school requires two topics to be discussed. The i-th topic is interesting by a_i units for the teacher and by b_i units for the students. The pair of topics i and j (i < j) is called good if a_i + a_j > b_i + b_j (i.e. it is more interesting for the teacher). Your task is to find the number...
3
#! /usr/bin/python3 import sys from collections import deque def main(): input_list = get_input() input_list = parse_input(input_list) print(solve(input_list)) def get_input(): input_list = [] for line in sys.stdin: input_list.append(line.rstrip("\n")) return input_list def parse_inpu...
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...
3
n = int(input()) receiver = [int(x) for x in input().split()] giver = [0]*n m = 0 for i in range(n): m = receiver[i] giver[m-1] = i+1 for s in giver: print(s, end=" ")
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
x=int(input()) l=[] b={} lo=[] for __ in range(x): a=input() b[len(a)]=a lo.append(a) l.append(len(a)) l.sort() f=0 k=[b[l[0]]] for i in range(1,len(l)): if b[l[i-1]] not in b[l[i]]: f=1 else: k.append(b[l[i]]) if len(list(set(k)))!=len(list(set(lo))): f=1 if f==0: pr...
You are given an array a consisting of n positive integers, numbered from 1 to n. You can perform the following operation no more than 3n times: 1. choose three integers i, j and x (1 ≤ i, j ≤ n; 0 ≤ x ≤ 10^9); 2. assign a_i := a_i - x ⋅ i, a_j := a_j + x ⋅ i. After each operation, all elements of the array s...
3
# import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline PI = 3.141592653589793238460 INF = float('inf') MOD = 1000000007 # MOD = 998244353 def bin32(num): return '{0:032b}'.format(num) def add(x,y): return (x+y)%MOD def sub(x,y): return (x-y+MOD)%MOD def mul(x,y): retur...
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second. One day in 230 AD Shapur was trying to find out if any one can possibly do...
3
a = [[str(x) for x in input()] for x in range(2)] b = [] for i in range(len(a[0])): if a[0][i] == a[1][i]: b.append('0') else: b.append('1') print(''.join(b))
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W. Output the list...
3
import math for i in range(int(input())): a = [int(j) for j in input().split()] n = a[0] w = a[1] check=0 b=[] sum=0 len=0 x=math.ceil(w/2) a = [int(j) for j in input().split()] for j in range(n): if a[j]<x: b.append(j+1) sum+=a[j] len+...
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem. Allen's future parking lot can be repre...
3
n,k = map(int,input().split()) grid = [list(map(int,input().split())) for _ in range(4)] def it(): for i in range(1,n): yield (1,i),(1,i-1),(0,i) yield (2,n-1),(1,n-1),(3,n-1) for i in reversed(range(n-1)): yield (2,i),(2,i+1),(3,i) yield (1,0),(2,0),(0,0) # check for (cx,cy),_,(px,py) in it(): if ...
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
for i in range(int(input())): n=int(input()) a=list(map(int,input().split())) length=0 if(n==3): if(a==a[::-1]): print("YES") else: print("NO") else: for j in range(n): if(a.count(a[j])>2): print("YES") lengt...
Takahashi is a member of a programming competition site, ButCoder. Each member of ButCoder is assigned two values: Inner Rating and Displayed Rating. The Displayed Rating of a member is equal to their Inner Rating if the member has participated in 10 or more contests. Otherwise, the Displayed Rating will be their Inn...
3
n,r=map(int,input().split()); print(r+100*max(10-n,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...
3
n,k=map(int,input().split()) l=list(map(int,input().split())) ans=0 for i in range(1,n): if l[i]+l[i-1]<k: ans=ans+k-l[i]-l[i-1] l[i]=l[i]+k-(l[i]+l[i-1]) print(ans) print(*l)
Denis was very sad after Nastya rejected him. So he decided to walk through the gateways to have some fun. And luck smiled at him! When he entered the first courtyard, he met a strange man who was selling something. Denis bought a mysterious item and it was... Random permutation generator! Denis could not believed hi...
3
for _ in range(int(input())): n = int(input()) a = list(map(int,input().split())) d = dict() arr = [False]*(n) for i in range(n): d[a[i]] = i now = d[1] arr[now] = True flag = 0 for i in range(2,n+1): pos = d[i] if now+1<n and arr[now+1]==False: if pos==now+1: arr[now+1]=True else: fl...
Santa has n candies and he wants to gift them to k kids. He wants to divide as many candies as possible between all k kids. Santa can't divide one candy into parts but he is allowed to not use some candies at all. Suppose the kid who recieves the minimum number of candies has a candies and the kid who recieves the max...
3
t=int(input()) for w in range(t): a=input().split(' ') n=int(a[0]) k=int(a[1]) c=(n//k)*k n-=c if n<=k//2: print(n+c) else: print(c+k//2)