problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students. You can change each student's score as long as the following conditions are satisfied: * All scores are integers ...
3
test = int(input()) for times in range(test): n_m = list(map(int,input().split())) max_score = n_m[1] scores = list(map(int,input().split())) total = sum(scores) if total>= max_score : result = max_score if total < max_score : result = total print(result)
There are 100 houses located on a straight line. The first house is numbered 1 and the last one is numbered 100. Some M houses out of these 100 are occupied by cops. Thief Devu has just stolen PeePee's bag and is looking for a house to hide in. PeePee uses fast 4G Internet and sends the message to all the cops that a t...
1
# your code goes here t = int(raw_input()) for X in range(t): s = map(int, raw_input().split()) m=s[0] x = s[1] y = s[2] s= map(int, raw_input().split()) arr=[0]*101; arr[0] = 1 for i in s: min = 1 if x*y >= i else i-(x*y) max = 100 if x*y >= 100-i else i+(x*y) for j in range(min, max+1): arr[j] += 1 ...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
3
vow=['a','i','e','y','o','u'] s=input().lower() re="" for x in s: if x in vow: continue else : re=re+"."+x print(re)
Kitahara Haruki has bought n apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends. Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equal ...
3
# जय श्री राम import sys; import math; from collections import * # sys.setrecursionlimit(10**6) def get_ints(): return map(int, input().split()) def get_list(): return list(get_ints()) def printspx(*args): return print(*args, end="") def printsp(*args): return print(*args, end=" ") UGLYMOD ...
The Berland Armed Forces System consists of n ranks that are numbered using natural numbers from 1 to n, where 1 is the lowest rank and n is the highest rank. One needs exactly di years to rise from rank i to rank i + 1. Reaching a certain rank i having not reached all the previous i - 1 ranks is impossible. Vasya ha...
1
n, ds, (a, b) = [map(int, raw_input().split()) for _ in range(3)] print sum(ds[a - 1:b - 1]) # a starts at 1
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
3
import math t = int(input()) while t: a,b,c,d,k = map(int,input().split()) x= math.ceil(a/c) y = math.ceil(b/d) if x+y<=k: print(x,y) else: print("-1") t-=1
Young boy Artem tries to paint a picture, and he asks his mother Medina to help him. Medina is very busy, that's why she asked for your help. Artem wants to paint an n × m board. Each cell of the board should be colored in white or black. Lets B be the number of black cells that have at least one white neighbor adja...
3
for _ in range(int(input())): n,m = map(int,input().split()) Matrix = [["B" for i in range(m)] for j in range(n)] Matrix[0][0] = "W" for i in range(n): print("".join(Matrix[i]))
Takahashi wants to print a document with N pages double-sided, where two pages of data can be printed on one sheet of paper. At least how many sheets of paper does he need? Constraints * N is an integer. * 1 \leq N \leq 100 Input Input is given from Standard Input in the following format: N Output Print the a...
3
n=int(input()) pages=n//2+n%2 print(pages)
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
3
# -*- coding: utf-8 -*- """ Created on Mon May 25 13:17:08 2020 @author: default """ def comp(a, b): ca = 0 while a % 2 == 0: a = a // 2 ca += 1 cb = 0 while b % 2 == 0: b = b // 2 cb += 1 if a == b: if cb >= ca: m = (cb - ca) // 3 n...
HQ9+ is a joke programming language which has only four one-character instructions: * "H" prints "Hello, World!", * "Q" prints the source code of the program itself, * "9" prints the lyrics of "99 Bottles of Beer" song, * "+" increments the value stored in the internal accumulator. Instructions "H" and "Q"...
3
print(('NO','YES')[bool(set('HQ9')&set(input()))])
You are both a shop keeper and a shop assistant at a small nearby shop. You have n goods, the i-th good costs a_i coins. You got tired of remembering the price of each product when customers ask for it, thus you decided to simplify your life. More precisely you decided to set the same price for all n goods you have. ...
3
# 1234A.py from math import ceil q = int(input()) while(q): n = int(input()) a = [int(x) for x in input().split()] print(ceil(sum(a)/n)) # a.sort() # originalSum = sum(a) # newSum = 0 # i=0 # while(newSum<originalSum): # newSum = a[i]*n # i+=1 # print(a[i-1],end="\n") q-=1
The Bitlandians are quite weird people. They have very peculiar customs. As is customary, Uncle J. wants to have n eggs painted for Bitruz (an ancient Bitland festival). He has asked G. and A. to do the work. The kids are excited because just as is customary, they're going to be paid for the job! Overall uncle J. h...
3
a=0 g=0 out='' for _ in range(int(input())): x,y=map(int,input().split()) if abs(a+x-g)>500: g+=y out+='G' else: #print('yo',a,g) a+=x out+='A' #print(a,g) if abs(a-g)>500: print(-1) else: print(out)
It has been decided that a programming contest sponsored by company A will be held, so we will post the notice on a bulletin board. The bulletin board is in the form of a grid with N rows and N columns, and the notice will occupy a rectangular region with H rows and W columns. How many ways are there to choose where ...
3
n,h,w=map(int, [input() for i in range(3)]) print( (n - h + 1) * (n - w + 1))
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
3
t = int(input()) for _ in range(t): n = int(input()) s = input() if n % 2 == 0: for i in range(1, n, 2): if int(s[i]) % 2 == 0: print(2) break else: print(1) else: for i in range(0, n, 2): if int(s[i]) % 2 == 1: ...
RJ Freight, a Japanese railroad company for freight operations has recently constructed exchange lines at Hazawa, Yokohama. The layout of the lines is shown in Figure B-1. <image> Figure B-1: Layout of the exchange lines A freight train consists of 2 to 72 freight cars. There are 26 types of freight cars, which are d...
3
m = int(input()) for i in range(m): d = input() trains = [d] for j in range(1, len(d)): trains.extend([d[:j][::-1] + d[j:], d[:j] + d[j:][::-1], d[:j][::-1] + d[j:][::-1], d[j:] + d[:j], d[j:][::-1] + d[:j], d[j:] + d[:j][::-1], d[j:][::-1] + d[:j][::-1]]) print(len(set(trains)))
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
row, col = 0, 0 x, y = 2, 2 for i in range(5): arr = input().split() for j in range(5): if int(arr[j]) == 1: row = i col = j result = abs(x - row) + abs(y - col) print(result)
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
3
from math import ceil t = int(input()) for _ in range(t): a,b,c,d,k = map(int, input().split()) a1 = ceil(a/c) a2 = ceil(b/d) if (a1 + a2 <= k): print(a1, a2) else: print("-1")
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
# -*- coding: utf-8 -*- """ Created on Tue Dec 3 16:14:01 2019 @author: gsq """ n,m=map(int,input().split()) s=[int(x) for x in input().split()] a=s[0]-1 for i in range(1,m): if s[i]>=s[i-1]: a+=s[i]-s[i-1] elif s[i]<s[i-1]: a+=n-s[i-1]+s[i] print(a)
You are given three integers x, y and n. Your task is to find the maximum integer k such that 0 ≤ k ≤ n that k mod x = y, where mod is modulo operation. Many programming languages use percent operator % to implement it. In other words, with given x, y and n you need to find the maximum possible integer from 0 to n tha...
3
import sys, math input = sys.stdin.readline def getInts(): return [int(s) for s in input().split()] def getInt(): return int(input()) def getStrs(): return [s for s in input().split()] def getStr(): return input().strip() def listStr(): return list(input().strip()) import collections as col im...
You are given a huge decimal number consisting of n digits. It is guaranteed that this number has no leading zeros. Each digit of this number is either 0 or 1. You may perform several (possibly zero) operations with this number. During each operation you are allowed to change any digit of your number; you may change 0...
3
inp = lambda cast=int: list(map(cast, input().split())) printf = lambda s='', *args, **kwargs: print(str(s).format(*args), flush=True, **kwargs) n, x, y = inp() n, = inp(str) n = n[-x:] if n[-y-1] == '1': r = n.count('1') - 1 else: r = n.count('1') + 1 print(r)
Have you ever used the chat application QQ? Well, in a chat group of QQ, administrators can muzzle a user for days. In Boboniu's chat group, there's a person called Du Yi who likes to make fun of Boboniu every day. Du will chat in the group for n days. On the i-th day: * If Du can speak, he'll make fun of Boboniu ...
3
n, d, m = map(int, input().split()) u = list(map(int, input().split())) a = [] b = [] for i in range(n): if u[i] > m: a.append(u[i]) else: b.append(u[i]) if len(a) == 0: print(sum(b)) exit() La = len(a) Lb = len(b) a.sort(reverse=1) b.sort(reverse=1) a.append(0) b.append(0) for i in rang...
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it: * deletes all the vowels, * inserts a character "." before each consonant, * repl...
1
from __future__ import division import math def rl(): return [int(i) for i in raw_input().split()] def rm(): n = input() return [raw_input() for i in range(n)] vowels = 'aeiouy' s = raw_input().lower() for i in vowels: s = s.replace(i, '') print ''.join('.'+i for i in s)
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings. Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco...
3
# Date : 30-Sep-2020 By Jatin Sharma n = int(input()) for i in range(1, n): if i % 2 == 1: print("I hate that", end=" ") else: print("I love that", end=" ") if n % 2 == 1: print("I hate it") if n % 2 == 0: print("I love it")
We have a pyramid with N steps, built with blocks. The steps are numbered 1 through N from top to bottom. For each 1≤i≤N, step i consists of 2i-1 blocks aligned horizontally. The pyramid is built so that the blocks at the centers of the steps are aligned vertically. <image> A pyramid with N=4 steps Snuke wrote a per...
3
import sys if __name__ == '__main__': N,x = list(map(int,input().split())) if 1 < x < 2*N - 1: print('Yes') for i in range(2*N - 1): print(1+ ((x-N+i)%(2*N - 1))) else: print('No')
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 math t=int(input()) for i in range(t): s=input() n=len(s) minimum=n a=[0]*n b=[0]*n current=0 for j in range(n): if s[j]=='1': current+=1 a[j]=current current=0 for j in range(n): if s[n-1-j]=='0': current+=1 b[n-1-j]=cur...
A new agent called Killjoy invented a virus COVID-2069 that infects accounts on Codeforces. Each account has a rating, described by an integer (it can possibly be negative or very large). Killjoy's account is already infected and has a rating equal to x. Its rating is constant. There are n accounts except hers, number...
3
for j in range(int(input())): n,x=list(map(int,input().split())) l=list(map(int,input().split())) cnt=0 s=0 for i in l: if i==x: cnt+=1 s+=i-x if cnt==n: print(0) elif cnt>0: print(1) else: if s==0: print(1) ...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n=int(input()) opinion=list(map(int,input().split())) result="EASY" if 1 in opinion: result="HARD" print(result)
Mahmoud and Ehab play a game called the even-odd game. Ehab chooses his favorite integer n and then they take turns, starting from Mahmoud. In each player's turn, he has to choose an integer a and subtract it from n such that: * 1 ≤ a ≤ n. * If it's Mahmoud's turn, a has to be even, but if it's Ehab's turn, a has...
3
n = int(input()) if n%2 != 0 or n==0: print("Ehab") else: print("Mahmoud")
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n = int(input()) cnt = [] cntmi = 0 cntmax = 0 for i in range(n): a, b = map(int, input().split()) c = b - a cnt.append(c) for i in cnt: cntmi += i if cntmi > cntmax: cntmax = cntmi print(cntmax)
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...
1
a=raw_input().split() a.sort() ans=0 for i in range(0,3): if a[i]==a[i+1]: ans=ans+1 print(ans)
A sequence a_1,a_2,... ,a_n is said to be /\/\/\/ when the following conditions are satisfied: * For each i = 1,2,..., n-2, a_i = a_{i+2}. * Exactly two different numbers appear in the sequence. You are given a sequence v_1,v_2,...,v_n whose length is even. We would like to make this sequence /\/\/\/ by replacing s...
3
from collections import Counter iN = int(input()) aV = [int(_) for _ in input().split()] oV0 = Counter(aV[0::2]).most_common() oV1 = Counter(aV[1::2]).most_common() oV0 += [(0,0)] oV1 += [(0,0)] if oV0[0][0] != oV1[0][0] : print(iN - oV0[0][1] - oV1[0][1]) else: print(iN - max(oV0[0][1],oV1[0][1]) - max(oV0[...
We start with a string s consisting only of the digits 1, 2, or 3. The length of s is denoted by |s|. For each i from 1 to |s|, the i-th character of s is denoted by s_i. There is one cursor. The cursor's location ℓ is denoted by an integer in \{0, …, |s|\}, with the following meaning: * If ℓ = 0, then the cursor...
3
for _ in range(int(input())): x=int(input()) a=input() l=len(a) a=[i for i in a] ans=l p=0 m=10**9+7 while ans<x: for j in range(int(a[p])-1): for i in range(p+1,ans): a.append(a[i]) ans+=(int(a[p])-1)*((ans-p-1+m)%m) p+=1 for j in ...
Chokudai made a rectangular cake for contestants in DDCC 2020 Finals. The cake has H - 1 horizontal notches and W - 1 vertical notches, which divide the cake into H \times W equal sections. K of these sections has a strawberry on top of each of them. The positions of the strawberries are given to you as H \times W ch...
3
p, *q = open(0) h, w, k = map(int, p.split()) s = [list(i.strip()) for i in q] c = 1 r = range for y in r(h): # 番号 for x in r(w): if s[y][x] == "#": s[y][x] = c c += 1 else: s[y][x] = 0 # 左から右 for x in r(w): if s[y][x] == 0 and x: s...
Let quasi-palindromic number be such number that adding some leading zeros (possible none) to it produces a palindromic string. String t is called a palindrome, if it reads the same from left to right and from right to left. For example, numbers 131 and 2010200 are quasi-palindromic, they can be transformed to strin...
3
number = input() if number[-1] == "0": index = len(number) - 1 while number[index] == "0": index -= 1 number = number[0:index + 1] s = "" for i in range(0, len(number)): s = number[i] + s if s == number: print('YES') else: print('NO')
Vasya has got an undirected graph consisting of n vertices and m edges. This graph doesn't contain any self-loops or multiple edges. Self-loop is an edge connecting a vertex to itself. Multiple edges are a pair of edges such that they connect the same pair of vertices. Since the graph is undirected, the pair of edges (...
1
from fractions import gcd from math import factorial, ceil, sqrt, atan2, log, pi, e, asin,acos, cos, sin, floor from itertools import * from fractions import Fraction import string import copy import random import bisect from decimal import * from collections import deque from sys import * digs = string.digits + string...
PandeyG, a brilliant tennis player, decided to start a tournament in his colony. Now, since PandeyG is overly optimistic and ambitious - he tries to lure in as many people as he can from his colony for them to participate in his very own knockout type tennis tournament. What he fails to realize that, to have a knockout...
1
''' # Read input from stdin and provide input before running code name = raw_input('What is your name?\n') print 'Hi, %s.' % name ''' def find_tournaments(number): exponent = 0 while 2 ** exponent <= number: exponent = exponent + 1 diff = 2 ** exponent - number matches = number - diff print matches if __name_...
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars. Input The first line of the input contains a ...
3
import math n=int(input()) if(n==1): print(0,1) elif(n%7==1): min=math.floor(n/7) max=math.ceil(n/7) print(min*2,max+(n//7)) elif(n%7==6): min=math.floor(n/7) max=math.ceil(n/7) print(min+(n//7)+1,max*2) else: min=math.floor(n/7) max=math.ceil(n/7) print(min*2,max*2)
Gerald has n younger brothers and their number happens to be even. One day he bought n2 candy bags. One bag has one candy, one bag has two candies, one bag has three candies and so on. In fact, for each integer k from 1 to n2 he has exactly one bag with k candies. Help him give n bags of candies to each brother so th...
1
N = int(raw_input()) for i in xrange(1,N+1): j = i for k in xrange(N): print N*k+j, j = (j + 1) % N or N print
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
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 28 23:08:59 2020 @author: apple """ for i in range(0,5): a=list(map(int,input().split(' '))) if 1 in a: r=i for j in range(0,5): if a[j]==1: c=j outcome=abs(r-2)+abs(c-2) print(outcome)
You are given several queries. In the i-th query you are given a single positive integer ni. You are to represent ni as a sum of maximum possible number of composite summands and print this maximum number, or print -1, if there are no such splittings. An integer greater than 1 is composite, if it is not prime, i.e. if...
3
def f(x): if x%4==0: return x/4 else:return 1+(x-6)/4 a=int(input()) while a: a-=1 b=int(input()) if b==1 or b==2 or b==3 or b==5 or b==7 or b==11: print(-1) else : if b%2==0: print(int(f(b))) else : print(int(f(b-9)+1))
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ...
1
import sys origin = sys.stdin.readline() origin = origin.strip() target = "CODEFORCES" i = 0 j = 0 for k in range(0, 10): if k < len(origin) and origin[k] == target[k]: i += 1 else: break for k in range(-1, -11, -1): if len(origin) + k >= 0 and origin[k] == targ...
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 = list(input()) Rnum = C.count('R') print(C[:Rnum].count('W'))
For given two lines s1 and s2, print "2" if they are parallel, "1" if they are orthogonal, or "0" otherwise. s1 crosses points p0 and p1, and s2 crosses points p2 and p3. Constraints * 1 ≤ q ≤ 1000 * -10000 ≤ xpi, ypi ≤ 10000 * p0 ≠ p1 and p2 ≠ p3. Input The entire input looks like: q (the number of queries) 1st...
3
class Point: def __init__(self, x, y): self.x = x self.y = y def __sub__(self, other): return Point(self.x - other.x, self.y - other.y) def __repr__(self): return f"({self.x},{self.y})" class Segment: def __init__(self, x: Point, y: Point): self.pt1 = x ...
And while Mishka is enjoying her trip... Chris is a little brown bear. No one knows, where and when he met Mishka, but for a long time they are together (excluding her current trip). However, best friends are important too. John is Chris' best friend. Once walking with his friend, John gave Chris the following proble...
1
line = raw_input().split() n = int(line[0]) w,v,u = map(float, line[1:]) x,y = map(int, raw_input().split()) x_up = x_down = x - v*y/u for i in xrange(n-1): x,y = map(int, raw_input().split()) new_x = x - v*y/u if new_x > x_down: x_down = new_x elif new_x < x_up: x_up = new_x if x_up < 0 and x_down > 0: pr...
You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis...
3
T=int(input()) for _ in range(T): n=int(input()) a="" if(n%2==0): a='1'*(n//2) else: a='7'+'1'*((n-3)//2) print(int(a))
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
3
n = int(input()) happy_digit = [4, 44, 444, 7, 77, 777, 47, 447, 477, 74, 744, 774] ans = "NO" for x in happy_digit: if n % x == 0: ans = "YES" print(ans)
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
check = int(input().replace(" ","")) print("Yes" if (check**0.5)%1==0 else "No" )
You are given two integers x and y. You can perform two types of operations: 1. Pay a dollars and increase or decrease any of these integers by 1. For example, if x = 0 and y = 7 there are four possible outcomes after this operation: * x = 0, y = 6; * x = 0, y = 8; * x = -1, y = 7; * x = 1, y = ...
3
t = int(input()) for i in range(0, t): x, y = map(int, input().split()) a, b = map(int, input().split()) ans1 = x * a + y * a ans2 = 0 if x < y: ans2 = b * x ans2 += a * (y - x) else: ans2 = b * y ans2 += a * (x - y) print(min(ans1, ans2))
Two famous competing companies ChemForces and TopChemist decided to show their sets of recently discovered chemical elements on an exhibition. However they know that no element should be present in the sets of both companies. In order to avoid this representatives of both companies decided to make an agreement on the ...
3
n = int(input()) a = [[int(e) for e in input().split()] for i in range(n)] + [[2000000000, 0]] m = int(input()) b = [[int(e) for e in input().split()] for i in range(m)] + [[2000000000, 0]] a.sort() b.sort() i1 = 0 i2 = 0 ans = 0 while i1 + i2 < n + m: if i1 < n and (i2 >= m or a[i1][0] < b[i2][0]): ans += ...
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
#!/usr/bin/env python a = list(input()) l = [] for i in a: if not i in l: l.append(i) if len(l)%2 == 0: print("CHAT WITH HER!") else: print("IGNORE HIM!")
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
from sys import stdin,stdout from collections import Counter from itertools import permutations import bisect import math I=lambda: map(int,stdin.readline().split()) I1=lambda: stdin.readline() #(a/b)%m =((a%m)*pow(b,m-2)%m)%m for _ in range(int(I1())): n,x=I() a=list(I()) b=[0]*(202) for i in a: ...
Vivek has encountered a problem. He has a maze that can be represented as an n × m grid. Each of the grid cells may represent the following: * Empty — '.' * Wall — '#' * Good person — 'G' * Bad person — 'B' The only escape from the maze is at cell (n, m). A person can move to a cell only if it shares a...
1
import sys import collections input = sys.stdin.readline def block(n, m, maze, i, j): if i-1 >= 0: if maze[i-1][j] == 'G': return False elif maze[i-1][j] == '.': maze[i-1][j] = '#' if i+1 < n: if maze[i+1][j] == 'G': return False elif maze[i+1][j] == '.': maze[i+1][j] = '#' if j-1 >= 0: if m...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
for _ in range(int(input())): n=int(input()) if n%2!=0: print(((n-1)//2)+1) else: print(n//2)
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut...
3
testCase = int(input()) for i in range(testCase): n,m = [int(x) for x in input().split(" ")] if n == 1: print(0) elif n == 2: print(m) else: print(m*2)
You have a coins of value n and b coins of value 1. You always pay in exact change, so you want to know if there exist such x and y that if you take x (0 ≤ x ≤ a) coins of value n and y (0 ≤ y ≤ b) coins of value 1, then the total value of taken coins will be S. You have to answer q independent test cases. Input The...
3
q = int(input()) for c in range(q): a, b, n, S = [int(i) for i in input().split()] if S % n <= b and a*n + b >= S: print("YES") else: print("NO")
Everybody knows that the m-coder Tournament will happen soon. m schools participate in the tournament, and only one student from each school participates. There are a total of n students in those schools. Before the tournament, all students put their names and the names of their schools into the Technogoblet of Fire. ...
3
import sys n,m,k = map(int, sys.stdin.readline().split()) power = list(map(int, sys.stdin.readline().split())) school = list(map(int, sys.stdin.readline().split())) candidiate = list(map(int, sys.stdin.readline().split())) daejang = [0] * (m + 1) temp = [] for x in range(k): for y in range(n): if y == cand...
Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples. For example, tripl...
1
n=input() if n < 3: print -1 elif n&1: n *= n print (n+1)/2, (n-1)/2 else: n*=n print (n+4)/4, (n-4)/4
Squirrel Liss loves nuts. There are n trees (numbered 1 to n from west to east) along a street and there is a delicious nut on the top of each tree. The height of the tree i is hi. Liss wants to eat all nuts. Now Liss is on the root of the tree with the number 1. In one second Liss can perform one of the following act...
3
k=[] for i in range(int(input())): k.append(int(input())) c=k[0]+len(k) for i in range(1,len(k)): c+=abs(k[i]-k[i-1])+1 print(c)
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
3
st = input() n = len(st) c1=0 p1=0 ans=0 for i in range (n) : if (st[i] == 'C' ) : if p1!=0 : ans+=1 p1=0 if c1>=5 : c1=0 ans+=1 c1+=1 else : if c1!=0 : ans+=1 c1=0 if p1>=5 : p1=0 an...
Alice got an array of length n as a birthday present once again! This is the third year in a row! And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice. Bob has chosen m changes of the following form. For some integer...
3
len, que = [int(x) for x in input().split(" ")] total = 0 full = (len*(len-1))//2 if(len%2!=0): half = len//2 half = (half*(half+1)) else: half = len//2 half = half*half for i in range(que): curr = [int(x) for x in input().split(" ")] total+=(curr[0]*len) if(curr[1]>=0): total+=cur...
You are given two positive integers a and b. In one move you can increase a by 1 (replace a with a+1). Your task is to find the minimum number of moves you need to do in order to make a divisible by b. It is possible, that you have to make 0 moves, as a is already divisible by b. You have to answer t independent test c...
3
for _ in range(int(input())): a, b = map(int, input().split()) if a % b == 0: print(0) else: print(b - (a % b))
Mishka got an integer array a of length n as a birthday present (what a surprise!). Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps: * Replace each occurre...
3
n = int(input()) arr = list(map(int,input().split())) s = '' for i in range(n): if arr[i]%2==0: arr[i] = arr[i]-1 s = s + str(arr[i]) + " " print(s)
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed som...
3
t = int(input()) for i in range(t): s = str(input()) a = len(s) A = [] for i in range(a): A.append(s[i]) B = [] for i in range(a-1): if A[i] == A[i+1]: A[i] = ' ' A[i+1] = ' ' for i in range(a): if A[i] != ' ' and (A[i] not in B): B...
This is the easy version of this problem. The only difference is the constraint on k — the number of gifts in the offer. In this version: k=2. Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer "k of goods for the price of one" is held in store...
3
t = int(input()) for T in range(t): n, p, k = [int(x) for x in input().split()] l = [int(x) for x in input().split()] l.sort() l1 = [0] for i in range(k - 1): ## print(l1) l1.append(l1[-1] + l[i]) for i in range(k - 1, n): ## print(l1) l1.append(l1[i - k + 1] + l[i...
You are given an array a consisting of n integers. Each a_i is one of the six following numbers: 4, 8, 15, 16, 23, 42. Your task is to remove the minimum number of elements to make this array good. An array of length k is called good if k is divisible by 6 and it is possible to split it into k/6 subsequences 4, 8, 15...
3
n=int(input()) l=list(map(int,input().split())) d=[0]*7 ans=0 for i in range(n): if l[i]==4: d[1]+=1 elif l[i]==8 and d[1]>d[2]: d[2]+=1 elif l[i]==15 and d[2]>d[3]: d[3]+=1 elif l[i]==16 and d[3]>d[4]: d[4]+=1 elif l[i]==23 and d[4]>d[5]: d[5]+=1 elif l[i...
You are given an array of n integers a_1,a_2,...,a_n. You have to create an array of n integers b_1,b_2,...,b_n such that: * The array b is a rearrangement of the array a, that is, it contains the same values and each value appears the same number of times in the two arrays. In other words, the multisets \\{a_1,a_...
3
from sys import * from math import * from bisect import * t=int(stdin.readline()) for _ in range(t): n=int(stdin.readline()) a=list(map(int,stdin.readline().split())) b=[] rem=[] s=0 for i in range(n): if a[i]>0: b.append(a[i]) s+=a[i] else: re...
You are given an array a consisting of n integer numbers. You have to color this array in k colors in such a way that: * Each element of the array should be colored in some color; * For each i from 1 to k there should be at least one element colored in the i-th color in the array; * For each i from 1 to k al...
3
from collections import defaultdict from sys import stdin, stdout input = stdin.readline listin = lambda : list(map(int, input().split())) mapin = lambda : map(int, input().split()) n, k = mapin() a = listin() d = defaultdict(int) for i in a: d[i]+=1 if k < max(d.values()): print('NO') else: print('YES') ...
You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it. If there are several answers, you can print any. You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100)...
3
import functools import heapq as hp import collections import bisect import math def unpack(func=int): return map(func, input().split()) def l_unpack(func=int): """list unpack""" return list(map(func, input().split())) def s_unpack(func=int, rev=False): """sorted list unpack""" return sorted(m...
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf...
3
x = int(input()) s= input() l= "" for i in range(x): if (x-(i))%2 == 1: l= l + s[i] else: l = s[i] + l print(l)
Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them. No...
1
# CF212 # Problem B def jump(n, m, dirty): if (m == 0): return "YES" if (n == 1): if (m == 0): return "YES" return "NO" if (m == 1): if (n == 2): return "NO" if ((sorted(dirty))[0] == 1 or (sorted(dirty))[-1] == n): return "NO" ...
You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is ...
3
import sys; input = sys.stdin.buffer.readline sys.setrecursionlimit(10**7) from collections import defaultdict mod = 10 ** 9 + 7; INF = float("inf") def getlist(): return list(map(int, input().split())) class UnionFind: def __init__(self, n): self.par = [i for i in range(n + 1)] self.rank = [0] * (n + 1) self...
A string is called diverse if it contains consecutive (adjacent) letters of the Latin alphabet and each letter occurs exactly once. For example, the following strings are diverse: "fced", "xyz", "r" and "dabcef". The following string are not diverse: "az", "aa", "bad" and "babc". Note that the letters 'a' and 'z' are n...
3
for _ in range(int(input())): n=input() ar=[];count=0 for i in n: if i in ar: count=1 break else: ar.append(ord(i)) ar=sorted(ar) if count==0: for i in range(len(ar)-1): if ar[i]+1==ar[i+1]: count=0 ...
E869120 is initially standing at the origin (0, 0) in a two-dimensional plane. He has N engines, which can be used as follows: * When E869120 uses the i-th engine, his X- and Y-coordinate change by x_i and y_i, respectively. In other words, if E869120 uses the i-th engine from coordinates (X, Y), he will move to the ...
3
import sys from operator import itemgetter import math sys.setrecursionlimit(10 ** 8) input = sys.stdin.readline def main(): N = int(input()) XY = [[int(x) for x in input().split()] for _ in range(N)] txy = [] for x, y in XY: t = math.atan2(x, y) txy.append([t, x, y]) txy.sort(...
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() cA=0 cD=0 for i in range(n): if(s[i]=='A'): cA+=1 else: cD+=1 if(cA > cD): print("Anton") elif(cD > cA): print("Danik") else: print("Friendship")
There is a house with n flats situated on the main street of Berlatov. Vova is watching this house every night. The house can be represented as an array of n integer numbers a_1, a_2, ..., a_n, where a_i = 1 if in the i-th flat the light is on and a_i = 0 otherwise. Vova thinks that people in the i-th flats are distur...
3
n = int(input()) lst = list(map(int, input().split())) ans = 0 for i in range(1, n - 1): if lst[i - 1] == lst[i + 1] == 1 and lst[i] == 0: lst[i + 1] = 0 ans += 1 print(ans)
Petya is having a party soon, and he has decided to invite his n friends. He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co...
3
import math n, k = map(int,input().split()) rne = n*2 gne = n*5 bne = n*8 if rne >= k: r = (rne/k) elif rne < k: r = 1 if gne >= k: rr = gne/k elif gne < k: rr = 1 if bne >= k: rrr = bne/k elif bne < k: rrr = 1 bb = math.ceil(r) +math.ceil(rr)+math.ceil(rrr) print(bb) ...
You are given a complete directed graph K_n with n vertices: each pair of vertices u ≠ v in K_n have both directed edges (u, v) and (v, u); there are no self-loops. You should find such a cycle in K_n that visits every directed edge exactly once (allowing for revisiting vertices). We can write such cycle as a list of...
1
import sys range = xrange input = raw_input t = int(input()) for _ in range(t): n,l,r = [int(x) for x in input().split()] l -= 1 ind = l val = 1 ans = [] while len(ans) < r - l: while ind >= 2 * (n - val) and val < n: ind -= 2 * (n - val) val += 1 if...
Polycarp is playing a new computer game. This game has n stones in a row. The stone on the position i has integer power a_i. The powers of all stones are distinct. Each turn Polycarp can destroy either stone on the first position or stone on the last position (in other words, either the leftmost or the rightmost stone...
3
t=int(input()) for i in range(t): n=int(input()) lst=list(map(int,input().split(' '))) mx=max(lst) mn=min(lst) mni=0 mnx=0 for i in range(n): if lst[i]==mn: mni=i if lst[i]==mx: mnx=i if mni<mnx: print(min(mnx+1,n-mni,mni+1+n-mnx)) else...
Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws eac...
3
def go(): n = int(input()) a = [int(i) for i in input().split(' ')] m = int(input()) o = '' for i in range(m): w, h = [int(i) for i in input().split(' ')] m = max(a[0], a[w - 1]) a[0] = m + h o += '{}\n'.format(m) return o print(go()) #0000 #0000 #0000 # ## #0 ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
a = int(input()) for i in range(1, a + 1): b = input() if len(b)>10: print(b[0], end='') print(len(b) - 2, end='') print(b[len(b)-1]) else: print(b)
We just discovered a new data structure in our research group: a suffix three! It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in. It's super simple, 100% accurate, and doesn't involve advanced machine learni...
3
t=int(input()) for i in range(t): s=str(input()) s='1111'+s if s[-2]+s[-1]=='po': print('FILIPINO') elif s[len(s)-5:len(s)]=='mnida': print('KOREAN') else: print('JAPANESE')
At the beginning of the school year Berland State University starts two city school programming groups, for beginners and for intermediate coders. The children were tested in order to sort them into groups. According to the results, each student got some score from 1 to m points. We know that c1 schoolchildren got 1 po...
3
m=int(input()) x=list(map(int,input().split())) s=sum(x) a,b=map(int,input().split()) c=0 k=0 for i,j in enumerate(x): c+=j if c>=a and c<=b and s-c>=a and s-c<=b: k=i+2 break print(k)
We have N points numbered 1 to N arranged in a line in this order. Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows: * The operation uses integers L_i ...
3
import sys stdin = sys.stdin sys.setrecursionlimit(10 ** 7) def li(): return map(int, stdin.readline().split()) def li_(): return map(lambda x: int(x) - 1, stdin.readline().split()) def lf(): return map(float, stdin.readline().split()) def ls(): return stdin.readline().split() def ns(): return stdin.readline().rstrip...
Anna is a girl so brave that she is loved by everyone in the city and citizens love her cookies. She is planning to hold a party with cookies. Now she has a vanilla cookies and b chocolate cookies for the party. She invited n guests of the first type and m guests of the second type to the party. They will come to the ...
3
for i in range(int(input())): a, b, n, m = map(int, input().split()) flag = True if (a+b)<(n+m): flag = False elif (m>min(a,b)): flag = False if flag: print('Yes') else: print('No')
Dreamoon is a big fan of the Codeforces contests. One day, he claimed that he will collect all the places from 1 to 54 after two more rated contests. It's amazing! Based on this, you come up with the following problem: There is a person who participated in n Codeforces rounds. His place in the first round is a_1, hi...
3
t=int(input()) for you in range(t): l=input().split() n=int(l[0]) x=int(l[1]) l=input().split() li=[int(i) for i in l] li.append(10**9) li.append(0) li.sort() for i in range(n+1): if(li[i+1]-li[i]==0): continue k=li[i+1]-li[i]-1 if(x>=k): ...
Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000. a + b + c + d = n Create a program that outputs the number of combinations that satisfy the conditions. Input Given multiple datasets. Each dataset is given n on one row. Please process until the end of the inpu...
1
import sys n=1001 a=range(1,n) a+=[n]+a[::-1] for n in map(int,sys.stdin): x=0 for i in range(max(0,n-2000),min(n,2000)+1): x+=a[i]*a[n-i] print x
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
t = int(input()) for each_t in range(t): n = int(input()) l = [3, 7, 15, 31, 63, 127, 255, 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535, 131071, 262143, 524287, 1048575, 2097151, 4194303, 8388607, 16777215, 33554431, 67108863, 134217727, 268435455, 536870911, 1073741823, 2147483647] m = 0 for i in l...
Today we will be playing a red and white colouring game (no, this is not the Russian Civil War; these are just the colours of the Canadian flag). You are given an n × m grid of "R", "W", and "." characters. "R" is red, "W" is white and "." is blank. The neighbours of a cell are those that share an edge with it (those ...
1
I=lambda: map(int, raw_input().split()) t = input() for _ in xrange(t): n, m = I() fCol = None ok = True for j in xrange(n): a = list(raw_input()) if not ok: continue for i in xrange(m): k = (i+j)%2 if a[i] == 'W': if k == 0: if fCol == 'R': if ok: ok = False break el...
JATC and his friend Giraffe are currently in their room, solving some problems. Giraffe has written on the board an array a_1, a_2, ..., a_n of integers, such that 1 ≤ a_1 < a_2 < … < a_n ≤ 10^3, and then went to the bathroom. JATC decided to prank his friend by erasing some consecutive elements in the array. Since he...
3
n = int(input()) arr = list(map(int, input().split())) if n == 1: print(0) exit(0) elif n == 2: if arr[1] == 2 or arr[-2] == 999: print(1) exit(0) else: print(0) exit(0) idx = ans = 0 while idx + 1 < n: cnt = 0 if arr[idx] == 1 and arr[idx + 1] == 2: ...
I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me. It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h...
1
arr=[] for i in range(27): s="" if i>0: s=chr(96+i) for j in range(27): y=s if j>0: y=s+chr(96+j) for k in range(1,27): x=y+chr(96+k) arr.append(x) if len(arr)>26*(10**3): break if len(arr)>26*(10**3): ...
An n × n table a is defined as follows: * The first row and the first column contain ones, that is: ai, 1 = a1, i = 1 for all i = 1, 2, ..., n. * Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the remaining elements are defin...
3
n = int(input()); a = [[1 for _ in range(n)] for __ in range(n)]; for i in range(1, n): for j in range(1, n): a[i][j] = a[i - 1][j] + a[i][j - 1]; print(a[n - 1][n - 1]);
There is a game called "I Wanna Be the Guy", consisting of n levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game. Little X can pass only p levels of the game. And Little Y can pass only q levels of the game. You are given the indices of levels Little X can pass ...
3
n = int(input()) a = set(map(int, input().split()[1:])) b = set(map(int, input().split()[1:])) if len(a | b) == n: print("I become the guy.") else: print("Oh, my keyboard!")
Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets: * the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different), * the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different). Kuro...
3
t = int(input()) for i in range(t): n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) a.sort() b.sort() [print(i, end = " ") for i in a] print() [print(i, end = " ") for i in b] print()
Alica and Bob are playing a game. Initially they have a binary string s consisting of only characters 0 and 1. Alice and Bob make alternating moves: Alice makes the first move, Bob makes the second move, Alice makes the third one, and so on. During each move, the current player must choose two different adjacent char...
3
import sys input = sys.stdin.readline # Input Functions # Take integer input def inp(): return(int(input())) # Take list input def inlt(): return(list(map(int, input().split()))) # Take string as list of characters def insr(): s = input() return(s[:len(s) - 1]) # Take space separated integer variable ...
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
n,t = map(int,input().split()) s = list(input()) length = len(s) l = [] for i in range(length-1): if s[i] == 'B': l.append(i) len1 = len(l) for __ in range(t): for i in range(len1): if l[i] >= length-1: continue else: if s[l[i]+1] == 'G': ...
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not. You are given string s consisting of lowercase Latin letters. At once you can choose any position in th...
1
# coding: utf-8 # In[2]: def making_base_for_polydroms(d): dr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] drr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v...
[THE SxPLAY & KIVΛ - 漂流](https://soundcloud.com/kivawu/hyouryu) [KIVΛ & Nikki Simmons - Perspectives](https://soundcloud.com/kivawu/perspectives) With a new body, our idol Aroma White (or should we call her Kaori Minamiya?) begins to uncover her lost past through the OS space. The space can be considered a 2D plane,...
3
MAX = 70 x0, y0, ax, ay, bx, by = map(int, input().split()) xs, ys, t = map(int, input().split()) p = [(x0, y0)] for i in range(1, MAX): x, y = p[i-1] x = ax * x + bx y = ay * y + by p.append((x, y)) def dist(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) res = 0 for st in range(0, MAX): ...
Ilya the Lion wants to help all his friends with passing exams. They need to solve the following problem to pass the IT exam. You've got string s = s1s2... sn (n is the length of the string), consisting only of characters "." and "#" and m queries. Each query is described by a pair of integers li, ri (1 ≤ li < ri ≤ n)...
1
import sys def main(): s = raw_input() n = len(s) a = [0 for i in xrange(n+1)] for i in range(2,n+1): a[i]+=a[i-1] if s[i-2] == s[i-1]: a[i]+=1 q = int(raw_input()) for j in range(q): bd = raw_input().split() l = int(bd[0]) r = int(bd[1]) print a[r]-a[l] return 0 if __name__ == '__main__': m...
Kefa decided to celebrate his first big salary by going to the restaurant. He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the ver...
3
from collections import defaultdict import sys input = __import__('sys').stdin.readline n,m = map(int,input().split()) c = list(map(int,input().split())) adj = defaultdict(list) for i in range(n-1): u,v = map(int,input().split()) u -= 1 v -= 1 adj[u].append(v) adj[v].append(u) vis = [0] ...
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x. As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it. It's guaranteed that the solution always exists. If ther...
3
n=int(input()) for i in range(n): n=int(input()) print("1 ",n-1)