problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
An elephant decided to visit his friend. It turned out that the elephant's house is located at point 0 and his friend's house is located at point x(x > 0) of the coordinate line. In one step the elephant can move 1, 2, 3, 4 or 5 positions forward. Determine, what is the minimum number of steps he need to make in order ...
3
print(((int(input())+4) // 5))
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times. The ...
3
n, k = map(int, input().split()) k = 6 - k l = map(int, input().split()) c = 0 for i in l: if i < k: c += 1 print(c//3)
AtCoDeer the deer has found two positive integers, a and b. Determine whether the concatenation of a and b in this order is a square number. Constraints * 1 ≀ a,b ≀ 100 * a and b are integers. Input Input is given from Standard Input in the following format: a b Output If the concatenation of a and b in this o...
3
n=int(input().replace(" ","")) print(("No","Yes")[(n ** .5).is_integer()])
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c...
3
a = input().split() a.sort() if a[0] == a[1] == a[2]: print(0) elif (int(a[0][0]) + 1 == int(a[1][0]) == int(a[2][0]) - 1) and a[0][1] == a[1][1] == a[2][1]: print(0) elif (a[0] == a[1] or a[0] == a[2] or a[1]==a[2]): print(1) elif (int(a[0][0]) + 1 == int(a[1][0]) and a[0][1] == a[1][1]) or (int(a[0][0]) +...
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same. Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way ...
3
input() L=list(map(int,input().split())) res={0:0} for i in L: if i in res.keys(): res[i]+=1 else: res[i]=1 print(max(res.values()),len(set(L)))
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=map(int,raw_input().split()) b1,b2,b3=map(int,raw_input().split()) n=int(input()) x=a1+a2+a3 import math x=math.ceil(x/5.0) y=b1+b2+b3 y=math.ceil(y/10.0) if(x+y<=n): print "YES" else: print "NO"
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
3
n = int(input()); L = input().split(); a = list(map(int,L)); suma = 0; sumb = 0; for i in range(n): if (a[i]>0): suma = suma+a[i]; else: suma = suma-a[i]; print (suma);
Polycarp wants to buy exactly n shovels. The shop sells packages with shovels. The store has k types of packages: the package of the i-th type consists of exactly i shovels (1 ≀ i ≀ k). The store has an infinite number of packages of each type. Polycarp wants to choose one type of packages and then buy several (one or...
1
##################################### import atexit, io, sys, collections, math, heapq,fractions buffer = io.BytesIO() sys.stdout = buffer @atexit.register def write(): sys.__stdout__.write(buffer.getvalue()) ##################################### def f(cc,ais): if cc[1] % 2 == cc[0] % 2 == 0: return True ...
Kolya Gerasimov loves kefir very much. He lives in year 1984 and knows all the details of buying this delicious drink. One day, as you probably know, he found himself in year 2084, and buying kefir there is much more complicated. Kolya is hungry, so he went to the nearest milk shop. In 2084 you may buy kefir in a plas...
1
N = int(raw_input()) a = int(raw_input()) b = int(raw_input()) c = int(raw_input()) ans1, ans2 = N/a, 0 # calculating for plastic bottles N -= b # calculate remaining money after buying 1 glass bottle if N > b - c: # checking - still we can buy more glass bottles, if YES then ans2 = N / (b - c) # calculating total ...
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
def main(): v = list(map(int, input().split())) x = 1 while True: i = 1 - (x % 2) v[i] -= x if v[i] < 0: break x += 1 print('Vladik' if x % 2 == 1 else 'Valera') main()
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
3
n = int(input()) laptops = [] for i in range(n): ai, bi = map(int, input().split()) laptops.append((bi, ai)) laptops = sorted(laptops, reverse=True) price = 0x3f3f3f3f for c in laptops: if c[1] > price: print('Happy Alex') quit() else: price = c[1] print('Poor Alex')
In this problem you have to simulate the workflow of one-thread server. There are n queries to process, the i-th will be received at moment ti and needs to be processed for di units of time. All ti are guaranteed to be distinct. When a query appears server may react in three possible ways: 1. If server is free and...
3
import queue q = queue.Queue() ans = [0] * 200000 n, b = map(int, input().split()) tmp = 0 ans[0] = tmp for i in range(n): t, d = map(int, input().split()) while q.empty() == False and q.queue[0] <= t: q.get() if q.qsize() > b: ans[i] = -1 else: tmp = max(tmp, t) + d ans...
In an embassy of a well-known kingdom an electronic queue is organised. Every person who comes to the embassy, needs to make the following three actions: show the ID, pay money to the cashier and be fingerprinted. Besides, the actions should be performed in the given order. For each action several separate windows are...
1
#! /usr/bin/env python k1, k2, k3 = map(int, raw_input().split()) t1, t2, t3 = map(int, raw_input().split()) n = input() oq = map(int, raw_input().split()) def gen_new_que(r, k, t): q = [] ft = 0 nt = 0 for x in r: while ft < len(q) and q[ft] <= x: ft += 1 k += 1 ...
Every person likes prime numbers. Alice is a person, thus she also shares the love for them. Bob wanted to give her an affectionate gift but couldn't think of anything inventive. Hence, he will be giving her a graph. How original, Bob! Alice will surely be thrilled! When building the graph, he needs four conditions to...
3
n=int(input()) def prime(n): for i in range(2,int(n**(1/2))+1): if n%i==0: return 0 return 1 ans=n # print(prime(11)) while prime(ans)==0: ans+=1 print(ans) for i in range(1,n): print(i,i+1) print(1,n) for i in range(1,ans-n+1): print(i,i+n//2)
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...
1
def main(): x = int(input()) line = list(map(int, raw_input().split())) result = sum(line) if result % 2 == 0: line = list(filter(filt, line)) line.sort() if len(line) == 0: result = 0 else: result = result - line[0] print(result) def filt(x):...
Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N. Constraints * 1\leq N \leq 10^{16} * N is an integer. Input Input is given from Standard Input in the following format: N Output Print the maximum possible sum of the digits (in base 10) of a positive integer not...
3
n = input() if n[1:] == '9'*(len(n)-1): print(int(n[0]) + (len(n)-1)*9) else: print(int(n[0])-1 + (len(n)-1)*9)
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of a...
3
#!/usr/bin/env python3 n = int(input()) ls = list(map(int,input().split())) xs, ys, zs = [], [], [] for a in ls: if a < 0: if len(xs) == 0: xs.append(a) elif len(ys) == 0 or (len(ys) == 1 and ys[0] < 0): ys.append(a) else: zs.append(a) elif 0 < a: ...
The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a Γ— b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is,...
3
n,a,b=list(map(int,input().split())) if a*b>=6*n: print(a*b) print(a,b) else: sq,ansx,ansy,ar=round(((6*n)**0.5)),1e9,1e9,1e18 for i in range(1,sq+6): p,q=i,(6*n+i-1)//i if max(p,q)>=max(a,b) and min(p,q)>=min(a,b): if ar>p*q: ar=p*q ansx,ansy=...
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
import sys,math,string input=sys.stdin.readline L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) d="RBG" n=int(input()) s=list(input().strip()) i=0 c=0 if(n==1): print(0) print("".join(s)) else: while(i<n-2): if(s[i]==s[i+1]): ...
Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to ...
1
def leave_number(lr, h): l, u = 1, 2 ** (h + 1) - 1 rev = 1 for d in lr: mid = (l + u) / 2 if rev == 1: if d == "0": u = mid l += 1 rev *= -1 else: l = mid + 1 else: if d == "0": ...
Takahashi is meeting up with Aoki. They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now. Takahashi will leave his house now and go straight to the place at a speed of S meters per minute. Will he arrive in time? Constraints * 1 \leq D \leq 10000 * 1 \leq T \leq 10...
3
d, t, s = map(int, input().split()) print(("No", "Yes")[d / s <= t])
John Smith knows that his son, Thomas Smith, is among the best students in his class and even in his school. After the students of the school took the exams in English, German, Math, and History, a table of results was formed. There are n students, each of them has a unique id (from 1 to n). Thomas's id is 1. Every st...
3
n = int(input()) x = [] for i in range(n): x.append([sum(list(map(int, input().split()))), -i]) x.sort(reverse = True) i = 0 while x[i][1] != 0: i += 1 print(i + 1)
You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset. Both the given array and required subset may contain equal values. Input The first line contains a single integer t (1 ≀ t ≀...
3
from sys import stdin,stdout import bisect import math def st(): return list(stdin.readline().strip()) def inp(): return int(stdin.readline()) def li(): return list(map(int,stdin.readline().split())) def mp(): return map(int,stdin.readline().split()) def pr(n): stdout.write(str(n)+"\n") def...
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
import collections count = input() resultsData = input() results = collections.Counter(resultsData) if results['A'] > results['D']: print('Anton') elif results['A'] == results['D']: print('Friendship') else: print('Danik')
On February 14 Denis decided to give Valentine to Nastya and did not come up with anything better than to draw a huge red heart on the door of the length k (k β‰₯ 3). Nastya was very confused by this present, so she decided to break the door, throwing it on the mountains. Mountains are described by a sequence of heights...
3
from collections import deque def main(): for _ in range(int(input())): n, k = map(int, input().split()) a = list(map(int, input().split())) peaks = [0] * (n+1) for i in range(1, n-1): if a[i] > a[i-1] and a[i] > a[i+1]: peaks[i+1] = 1 lvalue = [0...
There are n students standing in a row. Two coaches are forming two teams β€” the first coach chooses the first team and the second coach chooses the second team. The i-th student has integer programming skill a_i. All programming skills are distinct and between 1 and n, inclusive. Firstly, the first coach will choose ...
3
import heapq n,k=map(int,input().split()) if n==1 or n==2: print('1'*n) exit() arr=list(map(int,input().split())) ll=[] q=[] for i in range(n): heapq.heappush(q,(-arr[i],i)) if i==0: ll.append([-1,1]) elif i==n-1: ll.append([n-2,-1]) else: ll.append([i-1,i+1]) ans=[0]*n s...
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
m,n=[int(x)for x in input().split()] if(m<=n): A=m*n T=A//2 print(T)
There is a robot staying at X=0 on the Ox axis. He has to walk to X=n. You are controlling this robot and controlling how he goes. The robot has a battery and an accumulator with a solar panel. The i-th segment of the path (from X=i-1 to X=i) can be exposed to sunlight or not. The array s denotes which segments are ex...
3
n,b,a= list(map(int, input().split())) maxa=a d= list(map(int, input().split())) count=0 for i in d: if i==1 and a!=maxa and b!=0: b-=1 a+=1 count+=1 elif i==1 and a!=0: a-=1 count+=1 elif i==0: if a!=0: a-=1 count+=1 elif b!=0:...
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array). For a positive integer n, we call a...
3
for test in range(0,int(input())): n=int(input()) arr=[] for i in range(1,n+1,2): arr.append(i) for j in range(2,n+1,2): arr.append(j) print(*arr)
There is a staircase with N steps. Takahashi is now standing at the foot of the stairs, that is, on the 0-th step. He can climb up one or two steps at a time. However, the treads of the a_1-th, a_2-th, a_3-th, \ldots, a_M-th steps are broken, so it is dangerous to set foot on those steps. How many are there to climb ...
3
n, m = map(int, input().split()) a=[True]*(n+1) for i in range(m): a[int(input())]=False r=[0]*(n+1) r[0]=1 for i in range(1,n+1): if not a[i]: continue r[i]=(r[i-1]+r[i-2])%1000000007 print(r[n])
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()) i=0 p=0 while i<n : o=0 i+=1 b=input() c=b.split() d=int(c[0]) e=int(c[1]) f=int(c[2]) if d==1: o+=1 if e==1: o+=1 if f==1: o+=1 if o>=2: p+=1 print(p)
You are given a simple connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge connects Vertex A_i and Vertex B_i. Takahashi will assign one of the two possible directions to each of the edges in the graph to make a directed graph. Determine if it is possible to make ...
3
import sys from collections import deque sys.setrecursionlimit(10 ** 5) def solve(n, m, links): if m % 2 == 1: print(-1) return tree = [set() for _ in range(n)] parents = [-1] * n q = deque([0]) while q: v = q.popleft() for u in links[v]: if parents[u]...
There are 3N participants in AtCoder Group Contest. The strength of the i-th participant is represented by an integer a_i. They will form N teams, each consisting of three participants. No participant may belong to multiple teams. The strength of a team is defined as the second largest strength among its members. For ...
3
n = int(input()) li = list(map(int, input().split())) li.sort() v = sum(li[n::2]) print(v)
You are given a string s of length n, which consists only of the first k letters of the Latin alphabet. All letters in string s are uppercase. A subsequence of string s is a string that can be derived from s by deleting some of its symbols without changing the order of the remaining symbols. For example, "ADE" and "BD...
3
n,k=map(int,input().split()) s=input() a=[0]*k for i in s: a[ord(i)-65]+=1 print(min(a)*k)
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way... The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s). In one move he can choose two consecutive characters s_i and s_{i...
3
for _ in range(int(input())): n=int(input()) st = input() ans = "" for i in range(n): if st[i]=='0': ans+=st[i] else: i=i-1 break for j in range(n-1,-1,-1): if st[j]=='1': continue else: break if i == j: ...
Every Codeforces user has rating, described with one integer, possibly negative or zero. Users are divided into two divisions. The first division is for users with rating 1900 or higher. Those with rating 1899 or lower belong to the second division. In every contest, according to one's performance, his or her rating ch...
1
if __name__ == "__main__": n = int(raw_input()) chg = [] div = [] mx = 1<<30 mn = -1<<30 inf = 1 for j in xrange(0, n): s = raw_input().split(" ") chg.append(int(s[0])) div.append(int(s[1])) if div[j] == 1 and mn < 1900: mn = 1900 if div...
You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction <image> whose denominator is no more than n. Formally, you should find such pair of integers a, b (1 ≀ b ≀ n; 0 ≀ a) that the value <image> is as minimal as possible. If there are multiple "nearest" fractions, choose...
3
from fractions import Fraction x, y, n = map(int, input().split()) v = Fraction(x, y).limit_denominator(n) print(v.numerator, v.denominator,sep="/")
Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, t...
3
x, y = [int(i) for i in input().split()] if x >= 0: if y > x: zone = 3 elif y <= x and y > -x+1: zone = 2 else: zone = 1 else: if y >= -x: zone = 3 elif y < -x and y >= x: zone = 4 else: zone = 1 if zone == 1: ans = -y*4 elif zone == 2...
Write a program which reads a rectangle and a circle, and determines whether the circle is arranged inside the rectangle. As shown in the following figures, the upper right coordinate $(W, H)$ of the rectangle and the central coordinate $(x, y)$ and radius $r$ of the circle are given. Circle inside a rectangle Cons...
1
W, H, x, y, r = map(int, raw_input().split()) if r <= x and x + r <= W and r <= y and y + r <= H: print 'Yes' else: print 'No'
Ashish has an array a of consisting of 2n positive integers. He wants to compress a into an array b of size n-1. To do this, he first discards exactly 2 (any two) elements from a. He then performs the following operation until there are no elements left in a: * Remove any two elements from a and append their sum to...
3
t = int(input()) while t: n = int(input()) a = [int(i) for i in input().split()] e = set() o= set() for i in range(2*n): if a[i]%2 == 0: e.add(i) else: o.add(i) ev = len(e) od = len(o) #print(e,o) if ev%2 == 1 and od%2 == 1: ...
You are given a string t consisting of n lowercase Latin letters and an integer number k. Let's define a substring of some string s with indices from l to r as s[l ... r]. Your task is to construct such string s of minimum possible length that there are exactly k positions i such that s[i ... i + n - 1] = t. In other...
3
tmp=input() n=int(tmp.split()[0]) k=int(tmp.split()[1]) str=input() ans = 0 for i in range(1,len(str)): if str[:i]==str[-i:]: ans = i print(str,end='') cnt = 1 while cnt<k : print(str[-(len(str)-ans):],end='') cnt = cnt + 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
x = 0 n = int(input()) operate = { "++X" : 1, "--X" : 2, "X++" : 3, "X--" : 4, } for i in range(n): a = input() b = operate[a] if b==1 or b==3: x+=1 else: x-=1 print(x)
Carol is currently curling. She has n disks each with radius r on the 2D plane. Initially she has all these disks above the line y = 10100. She then will slide the disks towards the line y = 0 one by one in order from 1 to n. When she slides the i-th disk, she will place its center at the point (xi, 10100). She w...
1
reshte = raw_input().split() n = int(reshte[0]) r = int(reshte[1]) positions = [r] reshte = raw_input().split() x = [int(reshte[0])] for i in range(1,n): x.append(int(reshte[i])) maxy=r for j in range(0,i): if(abs(x[j]-x[i]) <= 2*r): pos = (4*(r*r) -(x[i]-x[j])**2 )**0.5 +positions[j] ...
Determine if there exists a sequence obtained by permuting 1,2,...,N that satisfies the following conditions: * The length of its longest increasing subsequence is A. * The length of its longest decreasing subsequence is B. If it exists, construct one such sequence. Constraints * 1 \leq N,A,B \leq 3\times 10^5 * ...
3
r,p=range,print n,a,b=map(int,input().split()) if a+b>n+1or a*b<n:exit(p(-1)) l=[[]for i in r(b-1)]+[list(r(1,a+1))] for i in r(a+1,n+1):l[-2-(i-a-1)%(b-1)]+=[i] for i in l:p(*i,end=" ")
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute: * move north from cell (i, j) to (i, j + 1); * move east from cell (i, j) to (i + 1, j); * move south from cell (i, j) to (i, j - 1); * move wes...
3
import sys import math import bisect from math import floor,sqrt,log from collections import defaultdict scanf=lambda n: [int(i) for i in sys.stdin.readline().split()][:n] cin=lambda : map(int,sys.stdin.readline().split()) read_int=lambda : int(sys.stdin.readline()) read_string=lambda : sys.stdin.readline() cout=lambda...
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
money = int(input()) bills = 0 while(True): if money>=100: bills += money//100 money = money%100 continue elif money>=20: bills += money//20 money = money%20 continue elif money>=10: bills += money//10 money = money%10 continue elif...
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 ...
3
n=int(input()) p=[*map(int,input().split()),0] p.reverse() sum=0 tc=2100000000 for i in range(1,n+1): tc=min(max(tc-1,0),p[i]) sum+=tc print(sum)
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line. Unfortunately, from time to ti...
3
s=input() list=[] i=1 while i<len(s): x='' while (s[i]!=',')and(s[i]!='}')and(s[i]!=' ')and(i<len(s)): x+=s[i] i+=1 if (x!='')and(not x in list): list.append(x) else: i+=1 print(len(list))
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order. You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as...
3
n=int(input()) arr=list(map(int,input().split()))[::-1] markings=[0 for i in range(n)] #print(arr) for i in range(n): if markings[i]==0: markings[i]+=1 curr=1 for j in range(i,n-1): #print(j,markings,arr[i]) if markings[j+1]!=0: curr+=1 e...
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
for _ in range(int(input())): atual = 1 n = int(input()) soma = 0 elemento = 1 while atual < n: prox = atual+2 soma = soma + (prox**2 - atual**2)*elemento atual += 2 elemento += 1 print(soma)
One day Vasya was sitting on a not so interesting Maths lesson and making an origami from a rectangular a mm Γ— b mm sheet of paper (a > b). Usually the first step in making an origami is making a square piece of paper from the rectangular sheet by folding the sheet along the bisector of the right angle, and cutting t...
3
__author__ = 'catman' a,b = map(int, input().split()) count = 0 while True: #print(a,b) if a>b: t = a//b a = a-t*b else: t = b//a b = b-t*a count += t if a == 0 or b==0: break elif a == 1 or b == 1: if a == 1: count += b else: count += a ...
Nastya came to her informatics lesson, and her teacher who is, by the way, a little bit famous here gave her the following task. Two matrices A and B are given, each of them has size n Γ— m. Nastya can perform the following operation to matrix A unlimited number of times: * take any square square submatrix of A and...
3
from sys import stdin,stdout # input = stdin.readline from math import * # print = stdout.write n,m=map(int,input().split()) m1=[] for i in range(n): r=list(map(int,input().split())) m1.append(r) m2=[] for i in range(n): r=list(map(int,input().split())) m2.append(r) d=[0]*(n-1+m) for i in range(n-1+m): d[i]={} ...
You are given a string S. Takahashi can insert the character `A` at any position in this string any number of times. Can he change S into `AKIHABARA`? Constraints * 1 \leq |S| \leq 50 * S consists of uppercase English letters. Input Input is given from Standard Input in the following format: S Output If it i...
3
s=input() l=['AKIHABARA','KIHABARA','AKIHBARA','AKIHABRA','AKIHABAR', 'KIHBARA','AKIHBRA','AKIHABR','KIHABRA', 'AKIHBAR','KIHABAR', 'KIHBRA','AKIHBR','KIHABR','KIHBAR','KIHBR'] if s in l: print("YES") else: print("NO")
You are given two integers a and b. You may perform any number of operations on them (possibly zero). During each operation you should choose any positive integer x and set a := a - x, b := b - 2x or a := a - 2x, b := b - x. Note that you may choose different values of x in different operations. Is it possible to mak...
3
import sys input = sys.stdin.readline N = int(input()) AB = [list(map(int, input().split())) for _ in range(N)] for a, b in AB: L = [a, b] m = min(L) l = max(L) if (a+b)%3 == 0 and l <= m*2: print("YES") else: print("NO")
An adult game master and N children are playing a game on an ice rink. The game consists of K rounds. In the i-th round, the game master announces: * Form groups consisting of A_i children each! Then the children who are still in the game form as many groups of A_i children as possible. One child may belong to at m...
3
K=int(input()) s=input().split(' ') a=[int(s[i]) for i in range(len(s))] n=len(s) def solve(): x,y=2,2 for i in range(n-1,-1,-1): u=(x+a[i]-1)//a[i] v=y//a[i] if (a[i]*v<x): return -1,-1 x=a[i]*u y=a[i]*(v+1)-1 return x,y x,y=solve() if (x==-1): print(-1) else: print('%d %d'%(x,y))
Karl likes Codeforces and subsequences. He wants to find a string of lowercase English letters that contains at least k subsequences codeforces. Out of all possible strings, Karl wants to find a shortest one. Formally, a codeforces subsequence of a string s is a subset of ten characters of s that read codeforces from ...
3
from functools import reduce k = int(input()) a = [1] * 10 id = 0 while True: if reduce(lambda x, y: x * y, a) >= k: break a[id] += 1 id = (id + 1) % 10 print (''.join(map(lambda x: x[1] * x[0], zip(a, 'codeforces'))))
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other. He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ...
3
t=int(input()) for _ in range(t): x,y,a,b=map(int,input().split()) t=(y-x)/(a+b) if t.is_integer(): print(int(t)) 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
import math n = int(input()) from collections import defaultdict d = defaultdict(list) s = set() zc = 0 for i in range(n): a,b = map(int, input().split()) g = math.gcd(a,b) if g!=0: a //= g; b //= g if a<0: a,b = -a, -b elif a==0 and b<0: b *= -1 d[a,b...
Little Shino loves to play with coins. In the city she lives, there are 26 different types of coins. Each coin is represented with a lowercase letter a, b, c, ... , y, z. Shino has some number of coins and she placed them in some random sequence, S, on the table. She is wondering how many pairs (i, j) are there, where...
1
k = int(raw_input()) s = raw_input() ans = 0 for l in xrange(len(s)): d = {} for r in xrange(l,len(s)): if s[r] in d: d[s[r]] += 1 else: d[s[r]] = 1 if len(d) == k: ans += 1 print ans
Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture: <image> Petr ...
1
a = [int(i) for i in raw_input().split()] b=[31,28,31,30,31,30,31,31,30,31,30,31] x=b[a[0]-1]-28 if x+a[1]-1==0: print 4 elif x+a[1]-1<=7: print 5 else: print 6
You are given string S and T consisting of lowercase English letters. Determine if S equals T after rotation. That is, determine if S equals T after the following operation is performed some number of times: Operation: Let S = S_1 S_2 ... S_{|S|}. Change S to S_{|S|} S_1 S_2 ... S_{|S|-1}. Here, |X| denotes the len...
1
#!/usr/bin/env python #_*_coding:utf-8_*_ s = raw_input() t = raw_input() lens = len(s) if lens != len(t): print 'No' exit(0) elif s == t: print 'Yes' exit(0) else: for i in range(1, lens): if s[i:] + s[:i] == t: print 'Yes' exit(0) print 'No'
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >...
3
n = int(input()) for i in range(n): k = int(input()) for i in range(2, k): x = (k/((2**i)-1)) if x == int(x): print(int(x)) break
In Omkar's last class of math, he learned about the least common multiple, or LCM. LCM(a, b) is the smallest positive integer x which is divisible by both a and b. Omkar, having a laudably curious mind, immediately thought of a problem involving the LCM operation: given an integer n, find positive integers a and b suc...
3
t=int(input()) for q in range(t): n=int(input()) champ=n if n%2==0: print(n//2,n//2) else: for i in range(2,int(n**0.5)+2): if n%i==0: champ=i break print(n//champ,n-n//champ)
Kate has a set S of n integers \{1, ..., n\} . She thinks that imperfection of a subset M βŠ† S is equal to the maximum of gcd(a, b) over all pairs (a, b) such that both a and b are in M and a β‰  b. Kate is a very neat girl and for each k ∈ \{2, ..., n\} she wants to find a subset that has the smallest imperfection am...
3
n = int(input()) x = [0, 1] + [0] * (n-1) for i in range(2, n+1): if x[i]: continue for j in range(i, n + 1, i): if x[j]: continue x[j] = j//i print(*sorted(x[2:]))
Given is a string S. Replace every character in S with `x` and print the result. Constraints * S is a string consisting of lowercase English letters. * The length of S is between 1 and 100 (inclusive). Input Input is given from Standard Input in the following format: S Output Replace every character in S with ...
1
s = raw_input() print("x"*len(s))
The police department of your city has just started its journey. Initially, they don’t have any manpower. So, they started hiring new recruits in groups. Meanwhile, crimes keeps occurring within the city. One member of the police force can investigate only one crime during his/her lifetime. If there is no police offi...
3
k=input() str=input().split() count=0 p=0 a=0 k=0 for n in str: m=int(n) if m>=0: p=p+m elif m<0: if p>0: p=p-1 elif p==0: k=k+1 print(k)
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation. The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe...
3
string = str(input()) i = 0 Num_1 = 0 Num_2 = 0 Num_3 = 0 while i < len(string): if string[i] == '1': Num_1 += 1 elif string[i] == '2': Num_2 += 1 else: Num_3 += 1 i += 2 string = ('1+'*Num_1)+('2+'*Num_2)+('3+'*Num_3) print(string[0:-1])
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word s. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if...
3
s = input() hello = "hello" s = s.lower() i = 0 for l in s: if i == 5: break if l == hello[i]: i += 1 if i == 5: print("YES") else: print("NO")
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...
3
n = int(input()) str = input() str = list(str) li = ['a','e','i','o','u','y'] l = len(str) i=1 while i<len(str): if str[i-1] in li and str[i] in li: str.pop(i) else: i+=1 # # for i in range(len(str)): # for j in range(i,len(str)): # if str[i] in li and str[j] in li: # str...
You are playing a very popular game called Cubecraft. Initially, you have one stick and want to craft k torches. One torch can be crafted using one stick and one coal. Hopefully, you've met a very handsome wandering trader who has two trade offers: * exchange 1 stick for x sticks (you lose 1 stick and gain x sticks...
3
from sys import stdin, stdout import math,sys from itertools import permutations, combinations from collections import defaultdict,deque,OrderedDict,Counter from os import path import bisect as bi import heapq mod=10**9+7 def yes():print('YES') def no():print('NO') if (path.exists('input.txt')): #----------------...
Vasiliy lives at point (a, b) of the coordinate plane. He is hurrying up to work so he wants to get out of his house as soon as possible. New app suggested n available Beru-taxi nearby. The i-th taxi is located at point (xi, yi) and moves with a speed vi. Consider that each of n drivers will move directly to Vasiliy ...
1
import math l=lambda:map(int,raw_input().split()) a,b=l() n=input() mint=1000 for i in range(n): x,y,v=l() t=math.sqrt((x-a)**2 + (y-b)**2)/v mint=min(mint,t) print '%.20f' %mint
Yesterday, Benny decided to buy something from a television shop. She created a list that consisted of small description of N orders. The description for an order number i is a string Si. The description may consist of uppercase/lowercase Latin letters, digits and a '$' sign. But, every time after the sign '$', Benny...
1
def process(x): pos = x.index("$") answer = "" for i in xrange(pos+1, len(x)): if x[i].isalpha(): break answer += x[i] new = int(answer.replace(" ", "")) print "$" + `new`.strip("L") T = input() for i in xrange(T): x = raw_input() process(x)
User ainta has a stack of n red and blue balls. He can apply a certain operation which changes the colors of the balls inside the stack. * While the top ball inside the stack is red, pop the ball from the top of the stack. * Then replace the blue ball on the top with a red ball. * And finally push some blue ba...
1
input() s=raw_input()[::-1] s=s.replace('R','0') s=s.replace('B','1') print int(s,2)
A binary string is a string where each character is either 0 or 1. Two binary strings a and b of equal length are similar, if they have the same character in some position (there exists an integer i such that a_i = b_i). For example: * 10010 and 01111 are similar (they have the same character in position 4); * 10...
3
for _ in range(int(input())): n=int(input()) a=list(input()) b='' for i in range(0,len(a),2): b+=a[i] print(b)
Let us call a pair of integer numbers m-perfect, if at least one number in the pair is greater than or equal to m. Thus, the pairs (3, 3) and (0, 2) are 2-perfect while the pair (-1, 1) is not. Two integers x, y are written on the blackboard. It is allowed to erase one of them and replace it with the sum of the number...
3
x,y,m = list(map(int,input().split())) if x<=0 and y<=0: if max(x,y)>=m: print(0) else: print(-1) else: if m<=0: print(0) else: if max(x,y)>=m: print(0) else: res = 0 x,y=min(x,y),max(x,y) if x<=0 and y>0: ...
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
3
a,b=map(int,input().split()) k=0 x=min(a,b) if a>b: k=a-b else: k=b-a l=k//2 print(x,l)
Valera the Horse is going to the party with friends. He has been following the fashion trends for a while, and he knows that it is very popular to wear all horseshoes of different color. Valera has got four horseshoes left from the last year, but maybe some of them have the same color. In this case he needs to go to th...
3
uniques = set(map(int, input().split())) print(4 - len(uniques))
A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not. A string is called a substring of another string, if it can be obtained from that string by dropping some (possi...
3
n = int(input().strip()) s = input().strip() print("".join(sorted(s)))
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y): * point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y * point (x', y') is (x, y)'s left neighb...
3
n=int(input()) l=[] l1=[] for i in range(n): a,b=map(int,input().split()) l.append((a,b)) ans=0 #check for left neighbour for i in range(n): k=[0]*4 for j in range(n): if i==j: continue else: if l[i][1]==l[j][1]: if l[i][0]<l[j][0]: ...
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." β€” an excerpt from contest rules. A total of n participants took part in the contest (n β‰₯ k), and you already know their scores. Calculate how many ...
3
n,k=[int(x) for x in input().split()] a=list(map(int,input().split())) a=list(filter(lambda x:x>0,a)) if a==[]: print(0) else: if len(a)<=k: print(len(a)) else: a=a+[-154] i=k-1 s=i+1 while i+1<len(a): while a[i+1]==a[i]: s=s+1 ...
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
q=int(input()) n=[] for i in range(q): n.append(int(input())) for i in range(q): if n[i]<3:print(4-n[i]) elif n[i]%2==0: print(0) else:print(1)
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya has sequence a consisting of n integers. The subsequence of the sequence a is such subseque...
1
from collections import defaultdict as di import sys range = xrange input = raw_input MOD = 10**9+7 big = 10**5 + 10 modinv = [1]*big for i in range(2,big): modinv[i] = int((-(MOD//i)*modinv[MOD%i])%MOD) fac = [1] for i in range(1,big): fac.append(int(fac[-1]*i%MOD)) invfac = [1] for i in range(1,big): ...
Dreamoon is standing at the position 0 on a number line. Drazil is sending a list of commands through Wi-Fi to Dreamoon's smartphone and Dreamoon follows them. Each command is one of the following two types: 1. Go 1 unit towards the positive direction, denoted as '+' 2. Go 1 unit towards the negative direction, ...
3
import itertools kol1 = {'+': 0, '-': 0, '?': 0} kol2 = {'+': 0, '-': 0, '?': 0} s1 = input() s2 = input() for s in s1: kol1[s] += 1 for s in s2: kol2[s] += 1 if (kol1['+']==kol2['+'] and kol1['-']==kol2['-']): print('1.0') exit() mod1 = kol1['+'] - kol1['-'] mod2 = kol2['+'] - kol2['-'] mod3 = ab...
Today is Tom's Birthday. His Mom gifted him two sets of integers to play with, set Q and set R. R is the transformation of set Q. Both Q and R contains same frequency of numbers. While playing, he accidently drops few of integers of set Q. You have to help him find the numbers that he has dropped in ascending order a...
1
n=input() a=map(int,raw_input().split()) d={} for x in a: if x in d: d[x]+=1 else: d[x]=1 m=input() b=map(int,raw_input().split()) dd={} for x in b: if x in dd: dd[x]+=1 else: dd[x]=1 done=[] for x in dd: if (x not in d): done.append(x) if (dd[x]>d[x]): done.append(x) done=sorted(done) for x in done:...
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
3
n = int(input()) r = dict() for i in range(n): s = input() if s in r: ns = s + str(r[s]) print(ns) r[ns] = 1 r[s] = r[s] + 1 else: print('OK') r[s] = 1
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes. Some examples of beautiful numbers: * 12 (110); * 1102 (610); * 11110002 (12010); * 111110...
3
ans = 1 n = int(input()) for k in range(1,10): p = (2**k-1)*(2**(k-1)) if n%p == 0: ans = max(ans,p) print(ans)
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: * Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. ...
3
import sys # input = sys.stdin.buffer.readline def I(): return(list(map(int,input().split()))) def sieve(n): a=[1]*n for i in range(2,n): if a[i]: for j in range(i*i,n,i): a[j]=0 return a def check(s1,s): c=0 for i in range(n): if s[i]!=s1[i]: c+=1 return c for __ in range(int(inpu...
Vus the [Cossack](https://en.wikipedia.org/wiki/Cossacks) holds a programming competition, in which n people participate. He decided to award them all with pens and notebooks. It is known that Vus has exactly m pens and k notebooks. Determine whether the Cossack can reward all participants, giving each of them at leas...
3
n,a,b = [int(i) for i in input().split()] if(a<n or b<n): print("No") else: print("Yes")
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
n = int(input()) s = input() dcount = 0 acount = 0 for word in s: if word == "D": dcount += 1 else: acount += 1 if dcount > acount: print("Danik") elif dcount < acount: print("Anton") else: print("Friendship")
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is di...
3
x=int(input()) l=[int(i)%2 for i in input().split()] a1=l.count(1) a2=l.count(0) if a1==1: print(l.index(1)+1) else: print(l.index(0)+1)
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct str...
3
# -*- coding: utf-8 -*- import sys from collections import Counter def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for...
Bizon the Champion isn't just a bison. He also is a favorite of the "Bizons" team. At a competition the "Bizons" got the following problem: "You are given two distinct words (strings of English letters), s and t. You need to transform word s into word t". The task looked simple to the guys because they know the suffix...
1
def main(): s = raw_input() t = raw_input() if sorted(s) == sorted(t): print 'array' else: n = len(s) m = len(t) i = 0 j = 0 while i < n and j < m: if s[i] == t[j]: j += 1 i += 1 if j == m: print 'automaton' else: S = {} T = {} for c in s: ...
Recently Oz has found a magical string consisting of single digit "1". After experimenting on the string, Oz found a weird magical property of the string that is whenever he touches the string then each digit "1" of string changed to digit "0" and each digit "0" of string changed to "01". Oz found this property intere...
1
__author__ = 'pjha' import sys def main(): N=input() for i in range(0,N): x=input() Cpre0=0 Cpre1=1 for j in range(0,x): C0=Cpre1+Cpre0 C1=Cpre0 Cpre0=C0 Cpre1=C1 print C1, print C0, print ...
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
3
n, x, y = int(input())-1, 1, 9 while n > x*y : n, x, y = n-x*y, x+1, 10*y print(str(10**(x-1)+n//x)[n%x])
You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time. So the team is considered perfect if it includ...
3
n = input() for i in range(int(n)): k = input() klis = k.split(' ') if int(klis[0]) > int(klis[1]): min = int(klis[1]) else: min = int(klis[0]) sum = int(klis[0]) + int(klis[1]) + int(klis[2]) if sum >= 3 * min: print(min) else: print(sum//3) klis.clea...
You are given a string s. Each character is either 0 or 1. You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met. You may eras...
3
print('\n'.join(str(input().lstrip('0').rstrip('0').count('0')) for i in range(int(input()))))
You are given a sequence a consisting of n integers a_1, a_2, ..., a_n, and an integer x. Your task is to make the sequence a sorted (it is considered sorted if the condition a_1 ≀ a_2 ≀ a_3 ≀ ... ≀ a_n holds). To make the sequence sorted, you may perform the following operation any number of times you want (possibly ...
3
t=int(input()) def solve(): n,x=map(int,input().split()) a=list(map(int,input().split())) xwas = x sor = list(sorted(a)) g = 1 for i in range(n): g = g and sor[i]==a[i] if g: return 0 sor = list(sorted(a+[x])) k =0 b = 1 for i in range(n): if sor[i]!=a[i]: ...
There is a grid with H rows and W columns, where each square is painted black or white. You are given H strings S_1, S_2, ..., S_H, each of length W. If the square at the i-th row from the top and the j-th column from the left is painted black, the j-th character in the string S_i is `#`; if that square is painted whi...
3
h,w = map(int, input().split()) a = [list("*"*(w+2))] for i in range(h): a.append(['*'] + list(input()) + ['*']) a.append(list("*"*(w+2))) b = [[0]*(w+2) for _ in range(h+2)] direction = [(1, 0), (-1, 0), (0, 1), (0, -1)] ans=0 for i in range(1,h+1): for j in range(1,w+1): if a[i][j]=='#' and b[i][j]==0: ...
β€” Hey folks, how do you like this problem? β€” That'll do it. BThero is a powerful magician. He has got n piles of candies, the i-th pile initially contains a_i candies. BThero can cast a copy-paste spell as follows: 1. He chooses two piles (i, j) such that 1 ≀ i, j ≀ n and i β‰  j. 2. All candies from pile i are...
3
# ---------------------------------------------------Import Libraries--------------------------------------------------- import sys import os from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial from copy import copy, deepcopy import bisect from sys import exit, stdin, stdout from...
Let's play Amidakuji. In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines. <image> In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first...
3
w = int(input()) n = int(input()) ans = [i for i in range(w)] for i in range(n): a,b = list(map(int, input().split(","))) temp = ans[a-1] ans[a-1] = ans[b-1] ans[b-1] = temp for i in ans: print(i+1)