problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Despite his bad reputation, Captain Flint is a friendly person (at least, friendly to animals). Now Captain Flint is searching worthy sailors to join his new crew (solely for peaceful purposes). A sailor is considered as worthy if he can solve Flint's task. Recently, out of blue Captain Flint has been interested in ma...
3
a=int(input('')) for i in range(0,a): i=int(input('')) g=i-31 h=i-30 if i <=30: print('NO') elif i==37 or i==41 or i==46 or i==31: print('YES') print(f'6 10 14 {h}') else: print('YES') print(f'6 10 15 {g}')
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
from math import gcd,ceil,log from collections import Counter,deque from heapq import heappush,heappop,heapify def rl(): return list(map(int,input().split())) def arp(arr): return ''.join(arr) for _ in range(int(input())): arr = [] for _ in range(9): s = list(input()) arr.append(s)...
Bizon the Champion is called the Champion for a reason. Bizon the Champion has recently got a present β€” a new glass cupboard with n shelves and he decided to put all his presents there. All the presents can be divided into two types: medals and cups. Bizon the Champion has a1 first prize cups, a2 second prize cups an...
1
a1, a2, a3 = raw_input().split() b1, b2, b3 = raw_input().split() n = input() a1, a2, a3 = [int(a1), int(a2), int(a3)] b1, b2, b3 = [int(b1), int(b2), int(b3)] sum1 = a1+a2+a3 sum2 = b1+b2+b3 if sum1%5==0: ans1 = sum1/5 else: ans1 = sum1/5 + 1 if sum2%10==0: ans2 = sum2/10 else: ans2 = sum2/10 + ...
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles. The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that...
3
t = int(input()) for _ in range(t): n,x = map(int,input().split()) a_L = list(map(int,input().split())) nokori = 0 ans = 0 a_L = list(sorted(a_L,reverse=True)) for i in range(n): if a_L[i] >= x: nokori += a_L[i] - x ans += 1 else: nokori += a...
An altar enshrines N stones arranged in a row from left to right. The color of the i-th stone from the left (1 \leq i \leq N) is given to you as a character c_i; `R` stands for red and `W` stands for white. You can do the following two kinds of operations any number of times in any order: * Choose two stones (not nec...
3
N = int(input()) c = input() x = c.count("R") print(c[x:].count("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%2==0: print("YES"); else: print("NO");
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
inp1=list(map(int,input())) inp2=list(map(int,input())) i=0 a=len(inp1) x=1 list1=[] while i<a : if inp1[i] == inp2[i]: list1.append("0") i=i+1 else: list1.append("1") i=i+1 list1="".join(list1) print(list1)
The programming competition season has already started and it's time to train for ICPC. Sereja coaches his teams for a number of year and he knows that to get ready for the training session it's not enough to prepare only problems and editorial. As the training sessions lasts for several hours, teams become hungry. Thu...
3
col = input() text = input() text = '0 '+text+' 0' z = text.split(' ') z = [int(z[i]) for i in range(len(z))] q = True r = 0 t = False for i in range(len(z)): if z[i] == 0: if r%2==1: q=False t=False r = 0 if z[i]>0 or t: t=True r+=z[i] if q == True: print('YES') else: print('NO')
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≀ i ≀ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it...
3
from sys import stdin, maxsize lines, line_index = stdin.readlines(), -1 def get_line(): global lines, line_index line_index += 1 return lines[line_index] def main(): n = int(get_line()) d = [int(x) for x in get_line().split()] dlen = 1 tlen = 1 for i in range(1, n): if d[i] >= d[i - 1]: ...
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...
1
n = input() a = [] ans = [] d = {} ans = [] for i in range(1,101): d[i] = 0 for i in range(n): a.append(raw_input()) d[len(a[i])] += 1 test = 0 a.sort(key = len) i = 0 while(i<len(a)): if(d[len(a[i])] > 1): j = i #print "first ---" + str(j) + str(d[len(a[j])]) while( i<len(a) and i < j+d[len(a[j])] ): ...
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance. The park is a rectangular table with n rows and m columns, where the cells of the...
3
t = int(input()) for _ in range(t): n, m = map(int, input().split()) b = n*m if b%2 == 0: print(b//2) else: print(b//2+1)
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
3
a = int(input()) b = int(input()) c = int(input()) print(max((a+b*c),(a*c+b),(a*b*c),(a*(b+c)),((a+b)*c),(a+b+c)))
Some country is populated by wizards. They want to organize a demonstration. There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administr...
3
from math import ceil a=list(map(int,input().split())) print(max(0,ceil(a[0]*a[2]/100-a[1])))
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) start = 0 for i in range(n): x = input() if '++' in x: start += 1 elif '--' in x: start -= 1 print(start)
Heisenberg is very fond of mixing various strings together. But he has storage problem. He wants that his strings use as less space as possible. He has N strings right now. He wants to store them together. To reduce space he can use this property of mixing two strings: Suppose he has string A="abcdef" and B="cdefg...
1
from itertools import permutations l=[] o=[] n=input() for i in range(n): a=raw_input() l.append(a) p=permutations(l) for st in p: opt = st[0] for j in range(1,n): indices = [i for i, x in enumerate(opt) if x == st[j][0]] flag = 1 for ind in indices: if opt[ind:] == st[j][0:len(opt[ind:])]: opt = opt...
The city administration of IT City decided to fix up a symbol of scientific and technical progress in the city's main square, namely an indicator board that shows the effect of Moore's law in real time. Moore's law is the observation that the number of transistors in a dense integrated circuit doubles approximately ev...
3
n, t = list(map(int, input().split())) print(n * 1.000000011 ** t)
"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
m,d =map(int,input().split()) participants=input("") participantsList=participants.split() x=0 for c in range(m): if (int(participantsList[c]) >= int(participantsList[d-1])) & (int(participantsList[c]) > 0): x=x+1 print(x)
How Many Divisors? Write a program which reads three integers a, b and c, and prints the number of divisors of c between a and b. Constraints * 1 ≀ a, b, c ≀ 10000 * a ≀ b Input Three integers a, b and c are given in a line separated by a single space. Output Print the number of divisors in a line. Example Inp...
3
a,b,c=map(int, input().split()) print(sum([1 if c%i==0 else 0 for i in range(a,b+1)]))
Certainly, everyone is familiar with tic-tac-toe game. The rules are very simple indeed. Two players take turns marking the cells in a 3 Γ— 3 grid (one player always draws crosses, the other β€” noughts). The player who succeeds first in placing three of his marks in a horizontal, vertical or diagonal line wins, and the g...
1
import sys won1 = won2 = 0 def test(s): global won1,won2 t = sum(s) won1 = won1 or (t == 3) won2 = won2 or (t == 0) if won1 and won2: print 'illegal' sys.exit() pole = [] symb = ['0','X','','','.'] for i in xrange(3): pole +=[symb.index(c) for c in raw_input()] mark = pole.count(...
There are n products in the shop. The price of the i-th product is a_i. The owner of the shop wants to equalize the prices of all products. However, he wants to change prices smoothly. In fact, the owner of the shop can change the price of some product i in such a way that the difference between the old price of this ...
3
n=int(input()) for i in range(n): l,k=map(int, input().split()) a=[int(j) for j in input().split()] if abs(max(a)-min(a)-k)>k: print(-1) else: print(min(a)+k)
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak) [Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive) NEKO#ΦωΦ has just got a new maze game on her PC! The game's main puzzle is a maze, in the forms of a 2 Γ— n rectangle grid. NEKO...
1
n,q=[int(i) for i in raw_input().split()] a=[[0 for i in range(2)]for j in range(n)] flag=0 for i in range(q): y,x=[int(i)-1 for i in raw_input().split()] if a[x][y]==0: a[x][y]=1 if x<n-1 and x>0: if y==0: if a[x-1][y+1]==1: flag+=1 ...
The length of the longest common prefix of two strings s = s_1 s_2 … s_n and t = t_1 t_2 … t_m is defined as the maximum integer k (0 ≀ k ≀ min(n,m)) such that s_1 s_2 … s_k equals t_1 t_2 … t_k. Koa the Koala initially has n+1 strings s_1, s_2, ..., s_{n+1}. For each i (1 ≀ i ≀ n) she calculated a_i β€” the length of ...
3
def prntasstr(l): for i in l: print(i, end='') print(end='\n') t = int(input()) while t: s = ["a"]*200 n = int(input()) prntasstr(s) for i in map(int, input().split()): s[i] = 'b' if s[i] == 'a' else 'a' prntasstr(s) t -= 1
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...
3
l1=list(input().split()) l2=list(input().split()) a=list((l1[0].lower()).split()) b=list((l2[0].lower()).split()) temp=list((l1[0].lower()).split()) if a==b: print(0) else: a.extend(b) a.sort() if a[0]==temp[0]: print(-1) else: print(1)
We have caught N sardines. The deliciousness and fragrantness of the i-th sardine is A_i and B_i, respectively. We will choose one or more of these sardines and put them into a cooler. However, two sardines on bad terms cannot be chosen at the same time. The i-th and j-th sardines (i \neq j) are on bad terms if and o...
3
from collections import defaultdict from math import gcd n = int(input()) ab = [list(map(int, input().split())) for _ in range(n)] mod = 10 ** 9 + 7 p = defaultdict(int) m = defaultdict(int) ab0 = 0 for a, b in ab: if a == 0 and b == 0: ab0 += 1 elif a == 0: m[(0, 1)] += 1 p[(1, 0)] ...
You are given an array a of n integers, where n is odd. You can make the following operation with it: * Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1). You want to make the median of the array the largest possible using at most k operations. The...
3
n, k = input().split() n = int(n) k = int(k) w = input().split() w = [int(i) for i in w] if n == 1: print(w[0] + k) else: w = sorted(w) idx = len(w)//2 + 1 mul = 1 gain = 0 for i in range(idx-1, len(w)-1): d = w[i+1] - w[i] if k > d * mul: #remainder ...
Snuke is conducting an optical experiment using mirrors and his new invention, the rifle of Mysterious Light. Three mirrors of length N are set so that they form an equilateral triangle. Let the vertices of the triangle be a, b and c. Inside the triangle, the rifle is placed at the point p on segment ab such that ap ...
3
n, a = map(int, input().split(' ')) b = n - a if a < b: a, b = b, a ans = n while b: q = a // b ans += 2 * q * b a %= b a, b = b, a ans -= a print(ans)
You are given a rectangular board of M Γ— N squares. Also you are given an unlimited number of standard domino pieces of 2 Γ— 1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions: 1. Each domino completely covers two squa...
3
# -*- coding: utf-8 -*- """ Created on Wed Oct 14 21:35:13 2020 @author: 衡泽华 """ (m,n)=[int(x) for x in input().split()] """ m1=int(m/2) m2=m-m1*2 n1=int(n/2) num=m1*n+m2*n1 """ print(int(m*n/2))
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
n = input() s = map(int, raw_input().split()) s.sort() tot = 0 for i in range(n/ 2): tot += ((s[i] + s[n - 1 - i]) ** 2) print tot
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to n. Let's assume that Misha chose number m, and Andrew chose number a. Then, by using a random generator they choose a random integer c in the range between 1 and n (any integer from 1 to n is chosen w...
3
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time (n, m) = (int(i) for i in input().split()) start = time.time() if n == 1: ans = 1 else: if m-1 >= n-m: ans = m-1 else: ans = m+1 print(ans) finish = time.time() #print(finish - start)
<image> Walking through the streets of Marshmallow City, Slastyona have spotted some merchants selling a kind of useless toy which is very popular nowadays – caramel spinner! Wanting to join the craze, she has immediately bought the strange contraption. Spinners in Sweetland have the form of V-shaped pieces of carame...
3
def main_function(): input_str = [i for i in input().split(" ")] n = int(input()) n = n % 4 d = ["v", "<", "^", ">"] if not n % 2: return "undefined" starting_index = d.index(input_str[0]) ending_index = d.index(input_str[1]) new_index_1 = starting_index + n new_index_2 = sta...
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 i in range (t): n=int(input()) a=set(map(int, input().split())) if max(a)-min(a)<len(a): print('YES') else: print('NO')
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
def answer(): n = int(input()) potato=n c_out=[] while n: s=input().split() s=[int(x) for x in s] n2=s[0] k=s[1] a=input().split() a = [int(x) for x in a] b=input().split() b= [int(x) for x in b] while k: rem=min(a) ...
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a...
3
#import math def removeZeros (a): i = 1 d = 0 while a > 0: if a% 10 != 0: d += (i*(a%10)) i *= 10 a //= 10 #print(d) return d #n, m = input().split() #n = int (n) #m = int (m) #n, m, k = input().split() #n = int (n) #m = int (m) #k = int (k) n = int(input()) m...
You have array of n numbers a_{1}, a_{2}, …, a_{n}. Rearrange these numbers to satisfy |a_{1} - a_{2}| ≀ |a_{2} - a_{3}| ≀ … ≀ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement. Note that all numbers in a are not necessarily different. In other words, some numb...
3
input=__import__('sys').stdin.readline for _ in range(int(input())): n = int(input()) lis = sorted(map(int,input().split())) ans=[0]*n i=0;j=n-1;k=n-1 while k>0: ans[k]=lis[j] ans[k-1]=lis[i] j-=1 i+=1 k-=2 if n%2!=0: ans[0]=lis[n//2] print...
Iahub is a big fan of tourists. He wants to become a tourist himself, so he planned a trip. There are n destinations on a straight road that Iahub wants to visit. Iahub starts the excursion from kilometer 0. The n destinations are described by a non-negative integers sequence a1, a2, ..., an. The number ak represents t...
3
import math n = int(input()) a = list(map(int, input().split())) a.sort(reverse = True) k = 0 s1 = 0 s2 = 0 for i in a: s2 += s1 - k * i s1 += i k += 1 s2 *= 2 s2 += sum(a) gcd = math.gcd(s2, n) print(s2 // gcd, n // gcd)
Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it. He has A_i cards with an integer i. Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1. Snuke wants to create the maximum number of pairs from his card...
3
n = int(input()) A = [int(input()) for _ in range(n)] ans = 0 temp = 0 for i in range(n): ans += (A[i]+temp)//2 if A[i] != 0: temp = (A[i]+temp)%2 else: temp = 0 print(ans)
There are four towns, numbered 1,2,3 and 4. Also, there are three roads. The i-th road connects different towns a_i and b_i bidirectionally. No two roads connect the same pair of towns. Other than these roads, there is no way to travel between these towns, but any town can be reached from any other town using these roa...
3
c = [0]*4 for i in range(3): a,b = map(int,input().split()) c[a-1] += 1 c[b-1] += 1 c.sort() print('YES' if c==[1,1,2,2] else 'NO')
There are N people standing in a row from west to east. Each person is facing east or west. The directions of the people is given as a string S of length N. The i-th person from the west is facing east if S_i = `E`, and west if S_i = `W`. You will appoint one of the N people as the leader, then command the rest of the...
3
from itertools import accumulate n = int(input()) s = [c == 'W' for c in input()] l = accumulate([0] + s[:-1]) r = accumulate([0] + [not c for c in reversed(s[1:])]) print(min(e + w for e, w in zip(l, reversed(list(r)))))
Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin. The world can be represented by the first quadrant of a plane and the wall is built along the identity line (...
3
n=int(input()) s=input() c=0 x=0 y=0 for i in range(len(s)-1): if s[i]=='U': y+=1 if s[i]=='R': x+=1 if x==y: if s[i]==s[i+1]: c+=1 print(c)
Takahashi has N balls with positive integers written on them. The integer written on the i-th ball is A_i. He would like to form some number of pairs such that the sum of the integers written on each pair of balls is a power of 2. Note that a ball cannot belong to multiple pairs. Find the maximum possible number of pai...
3
from bisect import bisect from math import log2 n = int(input()) a = [int(i) for i in input().split()] a,x,ans = sorted(a),[1]*n,0 for i in range(n-1,-1,-1): if x[i]: m = 2**(int(log2(a[i]))+1) b = bisect(a,m-a[i],hi=i)-1 if b+1 and a[b]==m-a[i]: x[b],ans,a[b],a[i] = 0,ans+1,a[b]+0.1,a[i]+0.1 print(ans)
An English booklet has been created for publicizing Aizu to the world. When you read it carefully, you found a misnomer (an error in writing) on the last name of Masayuki Hoshina, the lord of the Aizu domain. The booklet says "Hoshino" not "Hoshina". Your task is to write a program which replace all the words "Hoshino...
3
n = int(input()) for i in range(n): sentence = input() sentence = sentence.replace('Hoshino', 'Hoshina') print(sentence)
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated. The language is that peculiar as it has exactly one variable, called x. Also, there are two operations: * Operation ++ increases the value of variable x by 1. * Operation -- decreases the value of variable x by 1....
3
n = int(input()) ret = 0 for i in range(n): s = input() if '+' in s: ret+=1 else: ret-=1 print(ret)
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
def slv(x,n,m): while x > 20 and n > 0: x = x//2 + 10 n-=1 while x > 0 and m > 0: x-=10 m-=1 return 'YES' if x <= 0 else 'NO' t = int(input()) for _ in range(t): x,n,m=map(int, input().split()) print(slv(x,n,m))
An integer N is a multiple of 9 if and only if the sum of the digits in the decimal representation of N is a multiple of 9. Determine whether N is a multiple of 9. Constraints * 0 \leq N < 10^{200000} * N is an integer. Input Input is given from Standard Input in the following format: N Output If N is a multi...
3
n=input() if sum(map(int, n))%9 ==0: print('Yes') else: print('No')
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....
1
x = 0 for tc in xrange(int(raw_input())): s = raw_input() if '++' in s: x += 1 if '--' in s: x -= 1 print x
Little Susie listens to fairy tales before bed every day. Today's fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below. There are n trees located along the road at points with coordinates x1, x2, ..., xn. Each ...
1
num = int(raw_input()) trees = [] for i in range(num): x, h = map(int, raw_input().split()) trees.append([x, x, h]) # print trees counter = 0 for i, tree in enumerate(trees): can_left = i == 0 or i > 0 and trees[i-1][1] < tree[0] - tree[2] can_right = i == num - 1 or i < num - 1 and trees[i+1][0] > t...
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
q = int(input()) for i in range(q): n, k = map(int, input().split()) d = k // (n - 1) if (k % (n - 1) == 0): print(d * n - 1) else: print(n * d + k % (n - 1))
Little Jhool always wanted to have some psychic powers so that he could showoff his skills, and magic to people and impress them. (Specially, his girlfriend Big Jhool!) But, in spite all his efforts, hardwork, dedication, Googling, watching youtube videos he couldn't garner any psychic abilities! He knew everyone was ...
1
string = raw_input() i = 1 count = 1 n = string[0] flag = 0 while i != len(string) : n1 = string[i] if n1 == n: count += 1 else: n = n1 count = 1 if count >= 6: flag = 1 i += 1 if flag != 1: print 'Good luck!' else: print 'Sorry, sorry!'
Nikolay lives in a two-storied house. There are n rooms on each floor, arranged in a row and numbered from one from left to right. So each room can be represented by the number of the floor and the number of the room on this floor (room number is an integer between 1 and n). If Nikolay is currently in some room, he c...
3
# cook your dish here for _ in range(int(input())): n = int(input()) s = input() a,b = -1,-1 for i in range(n): if s[i] == "1": a = i for i in range(n-1,-1,-1): if s[i] == "1": b = n-1-i if a==-1 and b ==-1: print(n) else: print((ma...
Victor tries to write his own text editor, with word correction included. However, the rules of word correction are really strange. Victor thinks that if a word contains two consecutive vowels, then it's kinda weird and it needs to be replaced. So the word corrector works in such a way: as long as there are two consec...
1
def solution(): n = int(raw_input()) s = raw_input().strip() glasn = ['a', 'e', 'i', 'o', 'u', 'y'] res = [s[0]] for i in range(n)[1:]: if s[i] in glasn: if res[-1] in glasn: continue else: res.append(s[i]) else: res...
You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7. Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resultin...
1
a = [9681, 8961, 6981, 6891, 8691, 9861, 8196] d = [0] * 10 for x in raw_input(): d[ord(x) - 48] += 1 for k in [1, 6 ,8, 9]: d[k] -= 1 ans = '' r = 0 for i in range(9, -1, -1): ans += str(i) * d[i] while d[i]: d[i] -= 1 r = (r * 10 + i) % 7 if ans and ans[0] == '0': print str(a[0]) +...
A boy Bob likes to draw. Not long ago he bought a rectangular graph (checked) sheet with n rows and m columns. Bob shaded some of the squares on the sheet. Having seen his masterpiece, he decided to share it with his elder brother, who lives in Flatland. Now Bob has to send his picture by post, but because of the world...
3
n,m = map(int,input().split()) a = [] for _ in range(n): s = input() a.append(s) mxr = -1 mnr = -1 mxc = -1 mnc = -1 for i in range(n): for j in range(m): if a[i][j] == '*' and (mnr == -1 or j < mnr) : mnr = j if a[i][j] == '*' and (mnc == -1 or i < mnc) : mnc = i ...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n=int(input()) x, y, z=0,0,0 for i in range(n): q, w, e = map(int, input().split()) x+=q y+=w z+=e if x==y==z==0: print("YES") else: print("NO")
Petya is a big fan of mathematics, especially its part related to fractions. Recently he learned that a fraction <image> is called proper iff its numerator is smaller than its denominator (a < b) and that the fraction is called irreducible if its numerator and its denominator are coprime (they do not have positive comm...
3
n=int(input()) def pat(func): def wrap(a,b): if func(a,b)==1: return True else: return False return wrap @pat def dbd(a,b): if min(a,b)==0: return max(a,b) elif min(a,b)==1: return 1 else: return dbd(max(a,b)%min(a,b),min(a,b)) i=0 a=n-...
On the Planet AtCoder, there are four types of bases: `A`, `C`, `G` and `T`. `A` bonds with `T`, and `C` bonds with `G`. You are given a letter b as input, which is `A`, `C`, `G` or `T`. Write a program that prints the letter representing the base that bonds with the base b. Constraints * b is one of the letters `A`...
3
j={'A':'T','T':'A','C':'G','G':'C'} print(j[input()])
There are 2N squares arranged from left to right. You are given a string of length 2N representing the color of each of the squares. The color of the i-th square from the left is black if the i-th character of S is `B`, and white if that character is `W`. You will perform the following operation exactly N times: choo...
3
from math import factorial mod = 10 ** 9 + 7 n = int(input()) inp = list(input()) if inp[0] == 'W' or inp[-1] == 'W': print(0) exit(0) arr = ['L'] swap_dict = {'L': 'R', 'R': 'L'} for i in range(1, 2 * n): arr.append(arr[i - 1] if inp[i] != inp[i - 1] else swap_dict[arr[i - 1]]) if arr.count('L') != arr.cou...
During the break the schoolchildren, boys and girls, formed a queue of n people in the canteen. Initially the children stood in the order they entered the canteen. However, after a while the boys started feeling awkward for standing in front of the girls in the queue and they started letting the girls move forward each...
3
l,s = list(map(int,input().split())) b = input() while s: b = b.replace('BG','GB') s-=1 print(b)
You are given n integers a_1, a_2, ..., a_n, where n is odd. You are allowed to flip the sign of some (possibly all or none) of them. You wish to perform these flips in such a way that the following conditions hold: 1. At least (n - 1)/(2) of the adjacent differences a_{i + 1} - a_i for i = 1, 2, ..., n - 1 are grea...
3
import sys import math import itertools import functools import collections import operator import fileinput import copy ORDA = 97 # a def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return [int(i) for i in input().split()] def lcm(a, b): return abs(a * b) // math.gcd(a, b) def revn...
Sean is trying to save a large file to a USB flash drive. He has n USB flash drives with capacities equal to a1, a2, ..., an megabytes. The file size is equal to m megabytes. Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. Input The first line contai...
3
n = int(input()) m = int(input()) a = [] for i in range(n): a.append(int(input())) a.sort(reverse=True) count = 0 i = 0 while m > 0: m = m - a[i] i += 1 count += 1 print(count)
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 = int(raw_input()) g = [int(i) for i in raw_input().split()] p = [0] * n for i in xrange(n): p[g[i] - 1] = str(i + 1) print ' '.join(p)
Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ...
3
def count (lantern, N, L): max = 0.0 result = 0.0 if(lantern[0] > L - lantern[N - 1]): max = lantern[0] else: max = L - lantern[N - 1] for i in range(0, N-1): result = (lantern[i+1] - lantern[i]) / 2 if(result > max): max = result return max #program...
You are given an array a_1, a_2, ..., a_n where all a_i are integers and greater than 0. In one operation, you can choose two different indices i and j (1 ≀ i, j ≀ n). If gcd(a_i, a_j) is equal to the minimum element of the whole array a, you can swap a_i and a_j. gcd(x, y) denotes the [greatest common divisor (GCD)](...
3
#codeforces - implementation 1300 - 1401 C Mere Array t = int(input()) while t != 0: n = int(input()) arr = list(map(int, input().split())) arrSorted = sorted(arr) min = arrSorted[0] result = "YES" for i in range(n): if arrSorted[i] % min != 0 and arrSorted[i] != arr[i]: resu...
There is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Also, each of these vertices and edges has a specified weight. Vertex i has a weight of X_i; Edge i has a weight of Y_i and connects Vertex A_i and B_i. We would like to remove zero o...
3
from collections import deque import operator N, M = map(int, input().split()) *X, = map(int, input().split()) E = [] for i in range(M): a, b, y = map(int, input().split()) E.append((y, a-1, b-1)) E.sort() *Y, = map(operator.itemgetter(0), E) *p, = range(N) def root(x): if x == p[x]: return x ...
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
3
for i in range(int(input())): n,a,b=map(int,input().split()) p=n//b q=n%b d=[] for i in range(b): d.append(chr(97+i)) d="".join(d) print(d*p+d[:q])
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
from math import* n,m,a=map(int,input().split()) s=ceil(n/a) s1=ceil(m/a) print(s*s1)
You've got a 5 Γ— 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix: 1....
3
for i in range(5): matrix = input().split() if '1' in matrix: distance_row = abs(i-2) distance_column = abs(matrix.index('1')-2) print(distance_row+distance_column)
Recently, a chaotic virus Hexadecimal advanced a new theorem which will shake the Universe. She thinks that each Fibonacci number can be represented as sum of three not necessary different Fibonacci numbers. Let's remember how Fibonacci numbers can be calculated. F0 = 0, F1 = 1, and all the next numbers are Fi = Fi - ...
3
n=int(input()) f1=0; f2=1; s=1 if n==0: print(0,0,0); exit() while s<n: s=f1+f2 f1=f2 f2=s if s!=n: print("I'm too stupid to solve this problem") else: print(0,0,n)
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
3
n,m=map(int,input().split()) l=list(map(int,input().split())) x=1 c=0 for i in l: if(i>x): c=c+(i-x) x=i elif(i<x): c=c+(n-x+i) x=i print(c)
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
weight = int(input()) if (weight % 2 == 0) and (weight / 2 > 1): print("YES") else: print("NO")
The Super Duper Secret Meeting of the Super Duper Secret Military Squad takes place in a Super Duper Secret Place. The place is an infinite plane with introduced Cartesian coordinate system. The meeting table is represented as a rectangle whose sides are parallel to the coordinate axes and whose vertexes are located at...
3
def dis(a,b,c,d): xx=(a-c)*(a-c) yy=(d-b)*(d-b) return xx+yy x1,y1,x2,y2=map(int,input().split()) n=int(input()) x=[] y=[] r=[] for i in range(n): xx,yy,rr=map(int,input().split()) x.append(xx) y.append(yy) r.append(rr) ans=0 for i in range(min(x1,x2),max(x1,x2)+1): a=True b=True for j in range(len(x)): if ...
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 Counter N = int(input()) S = [input() for _ in range(N)] c = Counter(S).most_common() m = c[0][1] print("\n".join(sorted(s[0] for s in c if s[1] == m)))
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues. On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th...
3
h,m=map(int,input().split(":")) for i in range(0,1440): m+=1 if(m>59): m%=60 h+=1 if(h>23): h%=24 if(h==0 and m==0): print("00:00") break if(m<10): if(str(h)==str(m)+"0"): print(str(h)+":0"+str(m)) break elif(h<10): if("0"+str(h)==str(m)[::-1]): print("0"+str(h)+":"+str(m)) break elif(s...
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated....
3
t=int(input()) for i in range(t): s=str(input()) count=0 for i in range(len(s)): if s[i]=='B' and count!=0: count-=1 else: count+=1 print(count)
Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust. The pizza is a circle of radius r and center at the origin. Pizza consists of the main part β€” circle of radius r - d with center at the origin, an...
1
r, d = map(int, raw_input().split()) n = input() ans=0 for i in range(n): x, y, ri = map(int, raw_input().split()) dist = (x*x + y*y) ** 0.5 if dist >= r-d+ri and dist <= r-ri: ans+=1 print ans
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≀ x holds for each i (1 ≀ i ≀ n). Input The first line of input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. t blocks follow, each d...
3
import sys def main(): inp = sys.stdin.read().strip().split('\n') out = [] for i in range(1, len(inp), 4): _, x = map(int, inp[i].split()) a = sorted(map(int, inp[i+1].split())) b = sorted(map(int, inp[i+2].split()), reverse=True) out.append(('NO', 'YES')[all(i + j <= x for ...
Adilbek was assigned to a special project. For Adilbek it means that he has n days to run a special program and provide its results. But there is a problem: the program needs to run for d days to calculate the results. Fortunately, Adilbek can optimize the program. If he spends x (x is a non-negative integer) days opt...
3
T=int(input()) import math for i in range(T): n,d=list(map(int,input().split())) if(n==d): print("YES") else: flag=0 for i in range(1,n+1): if(i+math.ceil(d/(i+1))<=n): flag=1 break if(flag==1): print("YES") else...
The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" β€” the HR manager thought. "Just raise number 5 to the power of n and get last two digits of the number. Yes, of course, n can be rather big, and one cannot find the power using ...
1
print(25)
In Aramic language words can only represent objects. Words in Aramic have special properties: * A word is a root if it does not contain the same letter more than once. * A root and all its permutations represent the same object. * The root x of a word y is the word that contains all letters that appear in y ...
3
n = int(input()) have = [] for word in input().split(): root = set(word) if root not in have: have.append(root) print(len(have))
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each ot...
3
a,b = map(int,input().split()) flag = True for i in range(1,1000000): if(flag==True): flag = False if(a<i): print('Vladik') exit(0) a-=i else: flag = True if(b<i): print('Valera') exit(0) b-=i
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters. In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? In...
3
test = int(input()) for t in range(test): n = int(input()) d = {} for i in range(n): s = input() for j in s: if j in d: d[j]+=1 else: d[j]=1 flag = True for i in d: if d[i]%n==0: continue else: flag = False break if flag: print("YES") else: print("NO")
Once Bob needed to find the second order statistics of a sequence of integer numbers. Lets choose each number from the sequence exactly once and sort them. The value on the second position is the second order statistics of the given sequence. In other words it is the smallest element strictly greater than the minimum. ...
3
n=input();s=sorted(set(map(int, input().split()))) if len(s) >= 2: print(s[1]) else: print("NO")
A few years ago Sajjad left his school and register to another one due to security reasons. Now he wishes to find Amir, one of his schoolmates and good friends. There are n schools numerated from 1 to n. One can travel between each pair of them, to do so, he needs to buy a ticket. The ticker between schools i and j co...
1
n = int(raw_input()) print (n/2-1+n%2)
Theatre Square in the capital city of Berland has a rectangular shape with the size n Γ— m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a Γ— a. What is the least number of flagstones needed to pave the Square? It'...
3
from math import * list=input() n,m,a=list.split() n=int(n) m=int(m) a=int(a) count1=ceil(n/a) count2=ceil(m/a) print(count1*count2)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n=int(input()) cnt=0 for i in range(n): l=list(map(int,input().split())) if(l.count(1)>1): cnt+=1 print(cnt)
Lenny is playing a game on a 3 Γ— 3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be swit...
1
r = []; a = []; for i in range(3): t = map(int, raw_input().split()); r.append(t); a.append([1,1,1]); def add(i, j, val): if 2>=i>=0 and 2>=j>=0: a[i][j]+= val; for i in range(3): for j in range(3): add(i-1,j,r[i][j]); add(i+1,j,r[i][j]); add(i,j-1,r[i][j])...
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not. There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc...
3
import io import os from collections import Counter, defaultdict, deque def solve(N, A): seen = set() ans = [] for x in A: if x not in seen: ans.append(x) seen.add(x) return ' '.join(map(str, ans)) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat...
You are given two integers n and k. You are asked to choose maximum number of distinct integers from 1 to n so that there is no subset of chosen numbers with sum equal to k. A subset of a set is a set that can be obtained from initial one by removing some (possibly all or none) elements of it. Input The first line c...
3
def solve(n,k): ansArr = [] start = 0 if k%2 == 0: start = k//2 else: start = k//2 + 1 for i in range(start, k): ansArr.append(i) for i in range(k+1,n+1): ansArr.append(i) return ansArr T = int(input()) for i in range(T): n, k = map(int,input().split()) ansArr = solve(n, k) print...
An infinitely long railway has a train consisting of n cars, numbered from 1 to n (the numbers of all the cars are distinct) and positioned in arbitrary order. David Blaine wants to sort the railway cars in the order of increasing numbers. In one move he can make one of the cars disappear from its place and teleport it...
3
n = int(input()) a = list(map(int, input().split())) r = [0] + [0] * n for i in range(n): r[a[i]] = i + 1 count = 1 maxcount = 1 for i in range(2, n + 1): if r[i] > r[i - 1]: count += 1 else: if count > maxcount: maxcount = count count = 1 if count > maxcount: ma...
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
x=str(input()) y=0 sum1=1 sum2=0 bigsum=0 while y<len(x)-1: if x[y]==x[y+1] : sum1+=1 else: sum1=1 if sum1>bigsum: bigsum=sum1 y+=1 if bigsum>=7 : print ("YES") else: print ("NO")
You are given an array a consisting of n integer numbers. Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i. You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible...
3
n = int(input()) s = list(map(int, input().split())) M = max(s) m = min(s) if (M == m): print(0) else: m1 = M M1 = m cm = 0 cM = 0 for i in range(n): if (s[i] < m1 and s[i] > m): m1 = s[i] if (s[i] > M1 and s[i] < M): M1 = s[i] if (s[i] == m): cm += 1 if (s[i] == M): cM += 1 if (cm > 1)...
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
# Problem 1A. Theatre Square # SamTheBigWang data=[int(x) for x in raw_input().split()] print int((data[0]-1)/data[2]+1)*int((data[1]-1)/data[2]+1)
You are given two arrays a and b, each consisting of n positive integers, and an integer x. Please determine if one can rearrange the elements of b so that a_i + b_i ≀ x holds for each i (1 ≀ i ≀ n). Input The first line of input contains one integer t (1 ≀ t ≀ 100) β€” the number of test cases. t blocks follow, each d...
3
import sys #from collections import deque #from functools import * #from fractions import Fraction as f from copy import * from bisect import * #from heapq import * from math import gcd,ceil,sqrt from itertools import permutations as prm,product def eprint(*args): print(*args, file=sys.stderr) zz=1 #sys.setrec...
There was a big bank robbery in Tablecity. In order to catch the thief, the President called none other than Albert – Tablecity’s Chief of Police. Albert does not know where the thief is located, but he does know how he moves. Tablecity can be represented as 1000 Γ— 2 grid, where every cell represents one district. Eac...
3
from sys import stdin input = stdin.readline print(2000) for i in range(1, 1001): print(i, 1, i, 2) for i in range(1000, 0, -1): print(i, 1, i, 2)
You have integer n. Calculate how many ways are there to fully cover belt-like area of 4n-2 triangles with diamond shapes. Diamond shape consists of two triangles. You can move, rotate or flip the shape, but you cannot scale it. 2 coverings are different if some 2 triangles are covered by the same diamond shape in ...
3
t = int(input()) for i in range(0, t): n = int(input()) if n == n: print(n)
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges. During one move, you can choose some gift 1 ≀ i ≀ n and do one of the following operations: * eat exactly...
3
t=int(input()) for i in range(t): n=int(input()) l1=list(map(int,input().split())) l2=list(map(int,input().split())) x=min(l1) y=min(l2) c=0 for i in range(n): a=l1[i]-x b=l2[i]-y c+=min(a,b)+abs(a-b) print(c)
You have a garland consisting of n lamps. Each lamp is colored red, green or blue. The color of the i-th lamp is s_i ('R', 'G' and 'B' β€” colors of lamps in the garland). You have to recolor some lamps in this garland (recoloring a lamp means changing its initial color to another) in such a way that the obtained garlan...
3
n = int(input()) s = input() a = ["R G B", "R B G", "G R B", "G B R", "B G R", "B R G"] min = 9999999 minidx=999999 for i in range(0,6,1): c=0 x = a[i].split() q = 0 for j in s: if (j != x[q]): c = c + 1 q = (q + 1) % 3 if (min > c): min = c minidx=i prin...
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
x=int(input()) if x!=2 and x%2==0: print("Yes") else: print("No")
The administration of the Tomsk Region firmly believes that it's time to become a megacity (that is, get population of one million). Instead of improving the demographic situation, they decided to achieve its goal by expanding the boundaries of the city. The city of Tomsk can be represented as point on the plane with ...
3
n, s = map(int, input().split()) d = {} for i in range(n): x, y, k = map(int, input().split()) dist = (x**2 + y**2)**(1/2) if dist not in d: d[dist] = k else: d[dist] += k #print(d) lstKey = sorted(d) #print(new) ans = None for ele in lstKey: #print(ele, d[ele]) #print('sum is ' + str(d[ele] +s)) s += d...
Vasya goes to visit his classmate Petya. Vasya knows that Petya's apartment number is n. There is only one entrance in Petya's house and the distribution of apartments is the following: the first floor contains 2 apartments, every other floor contains x apartments each. Apartments are numbered starting from one, from...
3
import math t = int(input()) arr = [] for i in range(t): arr.append(list(map(int, input().split(" ")))) for i in range(len(arr)): n = arr[i][0] x = arr[i][1] ans = 0 val = n - 2 if(val<=0): ans = 1 else: ans = 1 + math.ceil(val/x) print(ans) ...
Constraints * 1 ≀ |V| ≀ 1000 * 0 ≀ |E| ≀ 2000 * -10000 ≀ di ≀ 10000 * There are no parallel edges * There are no self-loops Input An edge-weighted graph G (V, E) and the source r. |V| |E| r s0 t0 d0 s1 t1 d1 : s|E|-1 t|E|-1 d|E|-1 |V| is the number of vertices and |E| is the number of edges in G. The graph verti...
3
from sys import stdin from collections import deque V, E, R = [int(x) for x in stdin.readline().split()] d = {} tick = False INF = float('inf') for i in range(V): d[i] = INF d[R] = 0 weight = {} st = deque([]) for i in range(1, V+1): for j in range(E): if i == 1: s, t, w = [int(x) for x i...