problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Tattah is asleep if and only if Tattah is attending a lecture. This is a well-known formula among Tattah's colleagues.
On a Wednesday afternoon, Tattah was attending Professor HH's lecture. At 12:21, right before falling asleep, he was staring at the digital watch around Saher's wrist. He noticed that the digits on th... | 1 | #!/usr/bin/python
def unpack(s):
h1, h2, sep, m1, m2 = s[0], s[1], s[2], s[3], s[4]
h1, h2 = int(h1), int(h2)
m1, m2 = int(m1), int(m2)
M = m1*10 + m2
H = h1*10 + h2
return H, M
def pack(H, M):
h1, h2 = H//10, H % 10
m1, m2 = M//10, M % 10
return str(h1) + str(h2) + ':' ... |
You are given an array a_1, a_2, ... , a_n. Array is good if for each pair of indexes i < j the condition j - a_j ≠ i - a_i holds. Can you shuffle this array so that it becomes good? To shuffle an array means to reorder its elements arbitrarily (leaving the initial order is also an option).
For example, if a = [1, 1, ... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
for i in range(n):
a[i] = int(a[i])
a.sort(reverse = True)
print(*a) |
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they ... | 3 |
def is_repeted(n):
names=dict()
for _ in range(0,n):
name=input()
if name in names:
names[name]+=1
else:
names[name]=0
if names[name]==0:
print('No')
else:
print('YES')
... |
Asya loves animals very much. Recently, she purchased n kittens, enumerated them from 1 and n and then put them into the cage. The cage consists of one row of n cells, enumerated with integers from 1 to n from left to right. Adjacent cells had a partially transparent partition wall between them, hence there were n - 1 ... | 3 | n, = map(int, input().split())
p = [i for i in range(0,n+1)]
def find(i):
if p[i] == i:
return i
par = find(p[i])
p[i] = par
return par
def join(a,b):
p[find(a)] = find(b)
N = [-1 for i in range(0,n+1)]
class List:
def __init__(self, val):
self.front = self
self.va... |
Mishka wants to buy some food in the nearby shop. Initially, he has s burles on his card.
Mishka can perform the following operation any number of times (possibly, zero): choose some positive integer number 1 ≤ x ≤ s, buy food that costs exactly x burles and obtain ⌊x/10⌋ burles as a cashback (in other words, Mishka ... | 3 | t = int(input())
for q in range(t):
s = int(input())
ans = 0
mn = 1e9
while s > 0:
while s < mn:
mn //= 10
ans += mn
s -= mn - mn // 10
print(int(ans)) |
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 | def isPrime(x):
for i in range(2,int(x**.5+1)):
if x%i==0:
return False
return True
n=int(input())
edges = []
for i in range(n-1):
edges.append(str(i+1)+' '+str(i+2))
edges.append(str(n)+' '+str(1))
start = 1
while not isPrime(len(edges)):
edges.append(str(start)+" "+str(n-start))... |
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())
a = [int(x) for x in input().split()]
if a.count(1)>0:
print("HARD")
else:
print("EASY") |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 1 | get = lambda: map(int, raw_input().split())
n,m = get()
f = dict(raw_input().split() for i in range(m))
def b(w):
v = f[w]
if len(v) < len(w): return v
return w
print ' '.join(map(b, raw_input().split())) |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th... | 3 | def time(problems,time):
cnt=0
for i in range(1,problems+1):
time+=5*i
if time<=240:
cnt+=1
return cnt
a,b=map(int,input().strip().split())
print(time(a,b))
|
Anna and Maria are in charge of the math club for junior students. When the club gathers together, the students behave badly. They've brought lots of shoe laces to the club and got tied with each other. Specifically, each string ties together two students. Besides, if two students are tied, then the lace connects the f... | 3 | n, m = map(int, input().split())
shoelaces = [[0] * n for _ in range(n)]
for _ in range(m):
a, b = map(lambda x: int(x) - 1, input().split())
shoelaces[a][b] = 1
shoelaces[b][a] = 1
def can_cut(shoelaces, node):
count = 0
on = None
for other_node, shoelace in enumerate(shoelaces[node]):
... |
Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s... | 1 | n,s=map(int,raw_input().split())
T=0
li=[]
for i in xrange(n):
li+=[map(int,raw_input().split())]
li.sort()
li.reverse()
for f,t in li:
T+=s-f
s=f
if(T<t):
T=t
if(s!=0):
T+=s
print T
|
There are n athletes in front of you. Athletes are numbered from 1 to n from left to right. You know the strength of each athlete — the athlete number i has the strength s_i.
You want to split all athletes into two teams. Each team must have at least one athlete, and each athlete must be exactly in one team.
You want... | 3 | import math
from sys import stdin,stdout
def L():
return list(map(int,stdin.readline().split())) #For array input
def Si():
return sorted(list(map(int,stdin.readline().split()))) #For sorted array
def In():
return map(int,stdin.readline().split()) #For multiple input
def I():
return int(stdin.readline()... |
Alexandra has an even-length array a, consisting of 0s and 1s. The elements of the array are enumerated from 1 to n. She wants to remove at most n/2 elements (where n — length of array) in the way that alternating sum of the array will be equal 0 (i.e. a_1 - a_2 + a_3 - a_4 + ... = 0). In other words, Alexandra wants s... | 3 | T = int(input())
for t in range(T):
n = int(input())
A = list(map(int, input().split()))
res = []
for i in range(0, n, 2):
if A[i] + A[i+1] == 1:
res.append(0)
else:
res += A[i:i+2]
print(len(res))
for x in res:
print(x, end=" ")
print("")
... |
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 1 | import sys
def read_int(): return int(sys.stdin.readline())
def read_ints(): return [int(x) for x in sys.stdin.readline().strip('\n').split(' ')]
def solve_case(n, k, nums, min_num, max_num):
if n == 1:
return [0]
k -= 1
nums = [max_num - x for x in nums]
max_num -= min_num
if k & 1:
... |
— Thanks a lot for today.
— I experienced so many great things.
— You gave me memories like dreams... But I have to leave now...
— One last request, can you...
— Help me solve a Codeforces problem?
— ......
— What?
Chtholly has been thinking about a problem for days:
If a number is palindrome and length of its ... | 3 | k,p=map(int,input().split())
sum=0
for i in range(1,k+1):
sum+=(int(str(i)+str(i)[::-1])%p)
print(sum%p) |
You are given an array a consisting of n integers. You have to find the length of the smallest (shortest) prefix of elements you need to erase from a to make it a good array. Recall that the prefix of the array a=[a_1, a_2, ..., a_n] is a subarray consisting several first elements: the prefix of the array a of length k... | 3 | for _ in range(int(input())):
n = int(input())
l = list(map(int, input().split()))
if sorted(l) == l:
print(0)
continue
for i in range(n-2, -1, -1):
if l[i] < l[i+1]:
break
for j in range(i, -1, -1):
if l[j] < l[j-1]:
break
if j == -1:
... |
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At th... | 3 | s=input()
l=[]
uc=0
lc=0
for i in s:
l.append(i)
for i in range(len(s)):
if ord(l[i]) in range (65,91):
uc+=1
if ord(l[i]) in range (97,123):
lc+=1
if uc>lc:
s=s.upper()
if uc<lc or uc==lc:
s=s.lower()
print(s)
|
Masha works in an advertising agency. In order to promote the new brand, she wants to conclude contracts with some bloggers. In total, Masha has connections of n different bloggers. Blogger numbered i has a_i followers.
Since Masha has a limited budget, she can only sign a contract with k different bloggers. Of course... | 3 | from sys import stdin,stdout
from math import gcd,sqrt,factorial,pi,inf
from collections import deque,defaultdict
from bisect import bisect,bisect_left
from itertools import permutations as per
input=stdin.readline
R=lambda:map(int,input().split())
I=lambda:int(input())
S=lambda:input().rstrip('\n')
L=lambda:list(R())
... |
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | from sys import stdin
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
t, = gil()
for _ in range(t):
n, = gil()
a = ["9"]*n
r = 4
for i in reversed(range(n)):
if n >= r :
a[i] = "... |
There are n candies in a row, they are numbered from left to right from 1 to n. The size of the i-th candy is a_i.
Alice and Bob play an interesting and tasty game: they eat candy. Alice will eat candy from left to right, and Bob — from right to left. The game ends if all the candies are eaten.
The process consists o... | 3 | from collections import deque
t = int(input())
for _ in range(t):
n = int(input())
q = deque(list(map(int,input().split())))
a = 0
b = 0
turn = 0
bef = 0
while True:
count = 0
turn += 1
if turn%2:
while q and count <= bef:
count += q.pople... |
You are given two integers A and B.
Print a grid where each square is painted white or black that satisfies the following conditions, in the format specified in Output section:
* Let the size of the grid be h \times w (h vertical, w horizontal). Both h and w are at most 100.
* The set of the squares painted white is ... | 3 | def main():
white, black = [int(e) for e in input().split()]
w = 100
h = 50
line = [0] * w
field = [list(line) for _ in range(h)]
white -= 1
if white > 0:
black -= 1
for y in range(0, h, 2):
for x in range(0, w, 2):
field[y][x + 1] = field[y +... |
Ivan plays an old action game called Heretic. He's stuck on one of the final levels of this game, so he needs some help with killing the monsters.
The main part of the level is a large corridor (so large and narrow that it can be represented as an infinite coordinate line). The corridor is divided into two parts; let'... | 3 | from collections import defaultdict as DD
from bisect import bisect_left as BL
from bisect import bisect_right as BR
from itertools import combinations as IC
from itertools import permutations as IP
from random import randint as RI
import heapq as HQ
import sys
MOD=pow(10,9)+7
def IN(f=0):
if f==0:
return (... |
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e... | 3 | # Expression: python
a = int(input())
b = int(input())
c = int(input())
answer = a * b * c
temp = a + (b * c)
if temp > answer:
answer = temp
temp = a * (b + c)
if temp > answer:
answer = temp
temp = (a + b) * c
if temp > answer:
answer = temp
temp = (a * b) + c
if temp > answer:
answer = temp
te... |
Arya has n opponents in the school. Each day he will fight with all opponents who are present this day. His opponents have some fighting plan that guarantees they will win, but implementing this plan requires presence of them all. That means if one day at least one of Arya's opponents is absent at the school, then Arya... | 3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
(n, d) = (int(i) for i in input().split())
t = [0 for i in range(d)]
for i in range(d):
t[i] = sum([int(j) for j in list(input())])
start = time.time()
ans = 0
now = 0
for i in range(d):
if t[i] == n:
if now > ans:
ans = n... |
You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | 3 | input()
s = input()
k = int(input()) - 1
print(''.join(c if c == s[k] else '*' for c in s)) |
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 | n = int(input())
for i in range(n):
s = input()
length = len(s)
if (length > 10):
print(s[0] + str(length-2) + s[length - 1])
else:
print(s) |
You are given some Tetris field consisting of n columns. The initial height of the i-th column of the field is a_i blocks. On top of these columns you can place only figures of size 2 × 1 (i.e. the height of this figure is 2 blocks and the width of this figure is 1 block). Note that you cannot rotate these figures.
Yo... | 3 | t = int(input())
for i in range(t):
n_columns = int(input())
columns = [int(x) for x in input().split()]
even = False
odd = False
for column in columns:
if column % 2 == 0:
even = True
else:
odd = True
if even ^ odd:
print("YES")
else:
... |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t = int(input())
while(t):
t-=1
n = int(input())
a = list(map(int,input().split()))
a.sort()
f=1
for i in range(n-1):
if(a[i+1]-a[i] > 1):
f=0
break
else:
f=1
if(f):
print("YES")
else:
print("NO")
|
How many hours do we have until New Year at M o'clock (24-hour notation) on 30th, December?
Constraints
* 1≤M≤23
* M is an integer.
Input
Input is given from Standard Input in the following format:
M
Output
If we have x hours until New Year at M o'clock on 30th, December, print x.
Examples
Input
21
Output... | 3 | print(abs(24-int(input()))+24) |
The preferred way to generate user login in Polygon is to concatenate a prefix of the user's first name and a prefix of their last name, in that order. Each prefix must be non-empty, and any of the prefixes can be the full name. Typically there are multiple possible logins for each person.
You are given the first and ... | 1 | firs,las=raw_input().split()
ans=firs[0]
for a in firs[1:]:
if a<las[0]:
ans+=a
else:
break
ans+=las[0]
print ans
|
After a long party Petya decided to return home, but he turned out to be at the opposite end of the town from his home. There are n crossroads in the line in the town, and there is either the bus or the tram station at each crossroad.
The crossroads are represented as a string s of length n, where s_i = A, if there is... | 3 | I=input
for _ in[0]*int(I()):
*a,p=map(int,I().split());s=I();s='AB'[s[0]<'B']+s;i=len(s)-2;j=s[-2]>'A'
while i and p>=a[j]:p-=a[j];j^=1;i=s.rfind('AB'[j],0,i)
print(i+1) |
You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.
A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the r... | 3 | import time,math as mt,bisect as bs,sys
from sys import stdin,stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi=3.14159265358979323846264338327950
def II(): # to take integer input
return int(stdin.readline())
def IP(): # to ta... |
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 1 | #!/usr/bin/python
def R(): return map(int, raw_input().split())
n, k = R()
P = [raw_input() for i in range(n)]
pw = raw_input()
def get(P):
time = 0
misses = 0
for g in P:
time += 1
if g != pw:
misses += 1
if misses == k:
time += 5
misses = 0
else:
return time
# best
P.sort(key = lambd... |
Print the circumference of a circle of radius R.
Constraints
* 1 \leq R \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
R
Output
Print the circumference of the circle. Your output is considered correct if and only if its absolute or relative error ... | 3 | print(int(input())*3.141592*2) |
You are given a non-decreasing array of non-negative integers a_1, a_2, …, a_n. Also you are given a positive integer k.
You want to find m non-decreasing arrays of non-negative integers b_1, b_2, …, b_m, such that:
* The size of b_i is equal to n for all 1 ≤ i ≤ m.
* For all 1 ≤ j ≤ n, a_j = b_{1, j} + b_{2, j}... | 3 | # -*- coding: utf-8 -*-
"""
Created on Fri Nov 20 20:19:51 2020
@author: 章斯岚
"""
import math
for i in range(int(input())):
n,k=map(int,input().split())
a=len(set(input().split()))
if k==1:
if a>1:
print(-1)
else:
print(1)
else:
print(math.ceil((a-1)/(k-1)... |
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 | n=int(input())
list=[5,4,3,2,1]
out=0
i=0
while n!=0:
if n>= list[i]:
n=n-list[i]
out+=1
else:
i+=1
print(out) |
After his wife's tragic death, Eurydice, Orpheus descended to the realm of death to see her. Reaching its gates was uneasy, but passing through them proved to be even more challenging. Mostly because of Cerberus, the three-headed hound of Hades.
Orpheus, a famous poet, and musician plans to calm Cerberus with his poe... | 3 | def diversity(s,n):
if n==0 or n==1:
return 0
if n==2:
if s[0]==s[1]:
return 1
else:
return 0
count=0
a=['n']*n
for i in range(n-2):
# print(count)
if s[i]==s[i+1] and a[i]=='n' and a[i+1]=='n':
count+=1
a[i+1]='c'
if s[i]==s[i+2] an... |
"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 = map( int, input().split() )
a = list( map( int, input().split() ) )
print( len( list( filter( None, a[:k] + list( filter( lambda n: n == a[k - 1], a[k:] ) ) ) ) ) ) |
Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw n distinct points and m segme... | 1 | import sys
dbg = False
def solve(n, m, points, lines):
res = []
for ind, point in enumerate(points):
res.append([point, ind])
res.sort(key = lambda x: x[0])
if dbg:
print res
for i in xrange(len(res)):
res[i] = [i%2, res[i][1]]
if dbg:
print res
res.sort(key =... |
A new airplane SuperPuperJet has an infinite number of rows, numbered with positive integers starting with 1 from cockpit to tail. There are six seats in each row, denoted with letters from 'a' to 'f'. Seats 'a', 'b' and 'c' are located to the left of an aisle (if one looks in the direction of the cockpit), while seats... | 1 | def letter_index(letter):
if letter=='f':
return 1
elif letter=='e':
return 2
elif letter=='d':
return 3
elif letter=='a':
return 4
elif letter=='b':
return 5
elif letter=='c':
return 6
seat = raw_input()
row = int(seat[:-1])
letter = seat[-1:]
i... |
Write a program which computes the digit number of sum of two integers a and b.
Constraints
* 0 ≤ a, b ≤ 1,000,000
* The number of datasets ≤ 200
Input
There are several test cases. Each test case consists of two non-negative integers a and b which are separeted by a space in a line. The input terminates with EOF.
... | 1 | import sys
for i in sys.stdin.readlines():
a,b = map(int,i.split())
print len(str(a+b)) |
The number 105 is quite special - it is odd but still it has eight divisors. Now, your task is this: how many odd numbers with exactly eight positive divisors are there between 1 and N (inclusive)?
Constraints
* N is an integer between 1 and 200 (inclusive).
Input
Input is given from Standard Input in the following... | 3 | n=int(input())
print(len([a for a in [105,135,165,189,195] if a<=n])) |
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()
c = len(b) -2
if len(b) <= 10:
print(b)
else:
print(b[0],c,b[len(b)-1],sep="") |
Takahashi has a string S consisting of lowercase English letters.
Starting with this string, he will produce a new one in the procedure given as follows.
The procedure consists of Q operations. In Operation i (1 \leq i \leq Q), an integer T_i is provided, which means the following:
* If T_i = 1: reverse the string S... | 3 | s=input()
q=int(input())
head=''
foot=''
a=0
for i in range(q):
t=input()
if t=='1':
a=a^1
else:
t, f, c = map(str, t.split())
f=int(f)
if (f^a)&1==0:
foot+=c
else:
head+=c
s=head[::-1]+s+foot
if a==1:
s=s[::-1]
print(s) |
On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size.
There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, r... | 3 | def resolve():
import sys
input = sys.stdin.readline
import heapq
def dijkstra_heap(s,g,edge):
#始点sから各頂点への最短距離
d = [10**20] * (n+2)
used = [True] * (n+2) #True:未確定
d[s] = 0
used[s] = False
edgelist = []
sx,sy,sr=edge[s][0],edge[s][1],edge[s][2]
... |
You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | 3 | import math
x, s = list(map(int, input().strip().split()))
print(math.ceil(s/x)) |
Given are N integers A_1,\ldots,A_N.
Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).
Constraints
* 2 \leq N \leq 2\times 10^5
* 0 \leq A_i \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_1 \ldot... | 3 | a=s=0
for x in map(int,[*open(0)][1].split()):a+=s*x;s+=x
print(a%(10**9+7)) |
One day student Vasya was sitting on a lecture and mentioned a string s1s2... sn, consisting of letters "a", "b" and "c" that was written on his desk. As the lecture was boring, Vasya decided to complete the picture by composing a graph G with the following properties:
* G has exactly n vertices, numbered from 1 to... | 1 | n,m = map(int,raw_input().split())
store = [set() for _ in range(n+1)]
deg = [0] * (n+1)
ans = [0] * (n+1)
for _ in range(m):
x = map(int,raw_input().split())
store[x[0]].add(x[1])
store[x[1]].add(x[0])
deg[x[0]] += 1
deg[x[1]] += 1
if m == n * (n-1) / 2:
print "Yes"
print "a" * n
elif... |
Try guessing the statement from this picture:
<image>
You are given a non-negative integer d. You have to find two non-negative real numbers a and b such that a + b = d and a ⋅ b = d.
Input
The first line contains t (1 ≤ t ≤ 10^3) — the number of test cases.
Each test case contains one integer d (0 ≤ d ≤ 10^3).
... | 3 | for _ in range(int(input())):
d=int(input())
if d==0:
print("Y",0.0,0.0)
elif d==4:
print("Y",2.0,2.0)
elif d>4:
a=(d+(d**2-4*d)**0.5)/2
b=(d-(d**2-4*d)**0.5)/2
print("Y",a,b)
else:
print("N")
|
Polygon is not only the best platform for developing problems but also a square matrix with side n, initially filled with the character 0.
On the polygon, military training was held. The soldiers placed a cannon above each cell in the first row and a cannon to the left of each cell in the first column. Thus, exactly 2... | 3 | import sys
input=sys.stdin.readline
t=int(input())
for r in range(t):
n=int(input())
mat=[]
for i in range(n):
s=input().strip("\n")
temp=[]
for k in s:
temp.append(k)
mat.append(temp)
flag=True
# print(mat)
for i in range(n):
for j in range(n)... |
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()
h=s.find('h')
e=s[h+1:].find('e')
l=s[h+e+2:].find('l')
l2=s[h+e+l+3:].find('l')
o=s[h+e+l+l2+4:].find('o')
if h>=0 and e>=0 and l>=0 and l2>=0 and o>=0:
print('YES')
else:
print('NO')
|
You have array of n numbers a_{1}, a_{2}, …, a_{n}.
Rearrange these numbers to satisfy |a_{1} - a_{2}| ≤ |a_{2} - a_{3}| ≤ … ≤ |a_{n-1} - a_{n}|, where |x| denotes absolute value of x. It's always possible to find such rearrangement.
Note that all numbers in a are not necessarily different. In other words, some numb... | 3 | def solve():
N = int(input())
arr = [int(i) for i in input().split()]
arr.sort()
l, r = 0, len(arr) - 1
new_arr = []
while l <= r:
if r >= l:
new_arr.append(arr[r])
r -= 1
if l <= r:
new_arr.append(arr[l])
l += 1
print(' '.join(... |
Reforms continue entering Berland. For example, during yesterday sitting the Berland Parliament approved as much as n laws (each law has been assigned a unique number from 1 to n). Today all these laws were put on the table of the President of Berland, G.W. Boosch, to be signed.
This time mr. Boosch plans to sign 2k l... | 3 | from sys import stdin,stdout
from itertools import accumulate
nmbr=lambda:int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
n,k=lst();mx=mxlr=mxrl=0
a=lst()
ps=list(accumulate(a))
lr=[0]*n
mxlr=[0]*n
rl=[0]*(1+n)
mxrl=[0]*(1+n)
for i ... |
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 | x,y,z=input().split()
n=int(x)
m=int(y)
k=int(z)
if m>=n and k>=n:
print("Yes")
else:
print("No") |
Ivan has number b. He is sorting through the numbers a from 1 to 10^{18}, and for every a writes ([a, b])/(a) on blackboard. Here [a, b] stands for least common multiple of a and b. Ivan is very lazy, that's why this task bored him soon. But he is interested in how many different numbers he would write on the boa... | 3 | import math
b = int(input())
ans = 0
krai = math.ceil(math.sqrt(b))
for i in range(1, krai):
if b % i == 0:
ans += 1
if krai * krai == b:
print(2*ans + 1)
else:
print(ans*2)
|
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 |
def odejmij(t):
for i in range(t):
a, b = map(int, input().split())
if a == b:
print(0)
elif a > b:
x = a - b
if x % 2 == 0:
print(1)
else:
print(2)
else:
x = b - a
if x % 2 != 0:... |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | x = int(input())
for _ in range(x):
n, x = [int(num) for num in input().split(' ')]
arr = input().split(' ')
even = 0
for ele in arr:
if int(ele)%2 == 0:
even +=1
is_valid = 0
for i in range(0, even+1):
if (x - i)%2 !=0 and x-i <= len(arr) - even and x-i > 0:
is_valid = 1
if is_valid:
print("Yes")
... |
There are N integers written on a blackboard. The i-th integer is A_i.
Takahashi will repeatedly perform the following operation on these numbers:
* Select a pair of integers, A_i and A_j, that have the same parity (that is, both are even or both are odd) and erase them.
* Then, write a new integer on the blackboard ... | 3 | N=int(input())
A=list(map(int,input().split()))
B=[n for n in A if n%2==1]
ans='YES'
if len(B)%2==1:
ans='NO'
print(ans) |
You are given a sequence a_1, a_2, ..., a_n consisting of n non-zero integers (i.e. a_i ≠ 0).
You have to calculate two following values:
1. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a_{l + 1} ... a_{r - 1} ⋅ a_r is negative;
2. the number of pairs of indices (l, r) (l ≤ r) such that a_l ⋅ a... | 3 | n=int(input())
x=list(map(int,input().split()))
dp,dp2,r=[0]*200000,[0]*200000,[0]*200000
for i in range(n):
if i==0:
r[0]=x[0]/abs(x[0])
if r[0]>0:
dp[0]=1
else:
dp2[0]=1
else:
r[i]=r[i-1]*x[i]/abs(x[i])
if r[i]>0:
dp[i]=dp[i-1]+1
... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | import sys
n = int(input())
examples = [4,6,8,9]
simples = [2,3,5,7]
stop = False
for number_1 in examples:
for simple_number in simples:
diff = (n-number_1)
if(diff % simple_number == 0 and (diff // simple_number) >1):
answer= str(number_1)+' '+str(diff)
stop = True
break
if(stop):
br... |
You are given an array a consisting of n integers a_1, a_2, ... , a_n.
In one operation you can choose two elements of the array and replace them with the element equal to their sum (it does not matter where you insert the new element). For example, from the array [2, 1, 4] you can obtain the following arrays: [3, 4],... | 3 | def f():
l=[int(k)%3 for k in input().split()]
a=sum([k==1 for k in l])
b=sum([k==2 for k in l])
a,b=sorted((a,b))
c=len(l)-a-b
return (a+c+(b-a)//3)
for k in range(int(input())):
input()
print(f())
|
Gottfried learned about binary number representation. He then came up with this task and presented it to you.
You are given a collection of n non-negative integers a_1, …, a_n. You are allowed to perform the following operation: choose two distinct indices 1 ≤ i, j ≤ n. If before the operation a_i = x, a_j = y, then a... | 3 | import sys
inputr = lambda: sys.stdin.readline().rstrip('\n')
input = sys.stdin.readline
from collections import deque
n = int(input())
A = sorted(map(int, input().split()))
avail = [deque() for _ in range(20)]
for i in range(n):
v = A[i]
for j in range(20):
if v & (1 << j) == 0:
if avail[j]:
k = avail[j]... |
Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | 1 | last = None
count = 1
for p in raw_input().strip():
if last is None:
last = p
elif p == last:
count += 1
if count == 7:
print 'YES'
break
else:
last = p
count = 1
else:
print 'NO'
|
Old timers of Summer Informatics School can remember previous camps in which each student was given a drink of his choice on the vechorka (late-evening meal). Or may be the story was more complicated?
There are n students living in a building, and for each of them the favorite drink a_i is known. So you know n integer... | 3 | n, k = map(int, input().split())
d = [0]*(k+1)
for i in range(n): d[int(input())] += 1
print(n - sum([i%2 for i in d]) + (n//2 + (n%2 != 0)) - (n - sum([i%2 for i in d]))//2) |
Recently, on the course of algorithms and data structures, Valeriy learned how to use a deque. He built a deque filled with n elements. The i-th element is a_i (i = 1, 2, …, n). He gradually takes the first two leftmost elements from the deque (let's call them A and B, respectively), and then does the following: if A >... | 3 | from collections import deque
q=deque()
n,qq=map(int,input().split())
a=list(map(int,input().split()))
for i in range(n):
q.append(a[i])
ans = []
ind = a.index(max(a))
for i in range(ind):
A = q[0]
B = q[1]
ans.append([A,B])
if A>B :
t=q[1]
q[1] = q[0]
q[0] = t
... |
Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tr... | 3 | def leaf(f,u):
if len(m[u])==1:
return u
else:
for v in m[u]:
if v!=f:
ans=leaf(u,v)
if ans:return ans
def cut():
stack=[]
stack.append([0,-1,leaf(-1,0)])
while len(stack):
a,*b=stack.pop()
f,u=b
if... |
A wise king declared a new calendar. "Tomorrow shall be the first day of the calendar, that is, the day 1 of the month 1 of the year 1. Each year consists of 10 months, from month 1 through month 10, and starts from a big month. A common year shall start with a big month, followed by small months and big months one aft... | 1 | import sys
if sys.version_info[0]>=3: raw_input=input
n=int(raw_input())
for i in range(0,n):
a=map(int,raw_input().split())
a[0]-=1;a[1]-=1
print(196471-a[0]*195-a[0]/3*5-a[1]*20+(a[1]/2 if a[0]%3!=2 else 0)-a[2]) |
We have an N \times N square grid.
We will paint each square in the grid either black or white.
If we paint exactly A squares white, how many squares will be painted black?
Constraints
* 1 \leq N \leq 100
* 0 \leq A \leq N^2
Inputs
Input is given from Standard Input in the following format:
N
A
Outputs
Print... | 3 | N = int(input())
x = int(input())
print(N*N-x) |
Bessie has way too many friends because she is everyone's favorite cow! Her new friend Rabbit is trying to hop over so they can play!
More specifically, he wants to get from (0,0) to (x,0) by making multiple hops. He is only willing to hop from one point to another point on the 2D plane if the Euclidean distance betw... | 3 | import math
for _ in range(int(input())):
n,x=map(int,input().split())
a=list(map(int,input().split()))
if x in a: print(1)
else:
a.sort(reverse=True)
if a[0]>x: print(2)
else:
l1=[]
for item in a:
l1.append(math.ceil(x/item))
p... |
You are given two segments [l_1; r_1] and [l_2; r_2] on the x-axis. It is guaranteed that l_1 < r_1 and l_2 < r_2. Segments may intersect, overlap or even coincide with each other.
<image> The example of two segments on the x-axis.
Your problem is to find two integers a and b such that l_1 ≤ a ≤ r_1, l_2 ≤ b ≤ r_2 an... | 3 | t=int(input())
for _ in range(t):
a,b,c,d=map(int,input().split())
if(a!=c):
print(a,c)
if(a==c):
print(a,d)
|
Once again, Boris needs the help of Anton in creating a task. This time Anton needs to solve the following problem:
There are two arrays of integers a and b of length n. It turned out that array a contains only elements from the set \{-1, 0, 1\}.
Anton can perform the following sequence of operations any number of ti... | 3 | t= int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
br = 0
ha = [0]*3
for i in range(n):
if a[i] != b[i]:
br = 1
break
else:
ha[a[i]+1] += 1
if br == 0:
print... |
Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
* Cat A changes its napping place in order: n, n - 1, n - 2, ..., 3, 2, 1, n, n - 1, ... In other words, a... | 3 | import os
import sys
from io import BytesIO, IOBase
import math
BUFSIZE = 8192
from collections import Counter
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
... |
For an array a of integers let's denote its maximal element as max(a), and minimal as min(a). We will call an array a of k integers interesting if max(a) - min(a) ≥ k. For example, array [1, 3, 4, 3] isn't interesting as max(a) - min(a) = 4 - 1 = 3 < 4 while array [7, 3, 0, 4, 3] is as max(a) - min(a) = 7 - 0 = 7 ≥ 5.
... | 3 | t = int(input())
v1,v2=0,0
for i in range(t):
n=int(input())
flag="NO"
a=list(map(int,input().split()))
for j in range(len(a)-1):
if abs(a[j+1]-a[j])>=2:
flag="YES"
v1=j
v2=j+1
break
if flag=="NO":
print("NO")
else:
print("Y... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | A = list(map(int, input().split()))
m = A[0]
n = A[1]
a = A[2]
b=m//a
c=n//a
if m%a!=0 and a!=1:
b+=1
if n%a!=0 and a!=1:
c+=1
if b==0:
b=1
if c==0:
c=1
print(b*c) |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | def is_prime(n):
if n % 2 == 0:
return False
for i in range(3,n//2+1,2):
if n % i == 0:
return False
return True
n = int(input())
if n % 2 == 0:
x1,x2 = n//2 -1, n//2 +1
else:
x1, x2 = n//2, n//2 +1
while is_prime(x1) or is_prime(x2):
x1 -= 1; x2 += 1
print(f'{x1} {x2}')
|
It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai ... | 3 | from math import ceil
N, S = input().split()
N, S = int(N), int(S)
C = 0
pC = 0
nC = 0
cArr = []
for i in range(N):
s, a, b = input().split()
s, a, b = int(s), int(a), int(b)
C += s * b
cArr.append((a - b, s))
if a > b:
pC += s
else:
nC += s
cArr.sort(key=lambda k: -k[0])
tP... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | import sys
n=int(input())
ans=1
s=input()
for i in range(1,n):
m=sys.stdin.readline().strip()
if s!=m:ans+=1
s=m
print(ans)
|
You are given two arrays a and b, both of length n. All elements of both arrays are from 0 to n-1.
You can reorder elements of the array b (if you want, you may leave the order of elements as it is). After that, let array c be the array of length n, the i-th element of this array is c_i = (a_i + b_i) \% n, where x \% ... | 1 | #!/usr/bin/env python
from __future__ import division, print_function
import os
import random
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
else:
_str = str
str = lambda x=b"":... |
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Bi... | 3 | a = input("")
if int(a)%2 == 0 and int(a)>2 :
print('YES')
else :
print('NO') |
Two polar bears Menshykov and Uslada from the St.Petersburg zoo and elephant Horace from the Kiev zoo got six sticks to play with and assess the animals' creativity. Menshykov, Uslada and Horace decided to make either an elephant or a bear from those sticks. They can make an animal from sticks in the following way:
... | 1 | seq=map(int,raw_input().split())
num=set([seq.count(i) for i in set(seq)])
if num==set([6]) or num==set([4,2]):
print 'Elephant'
elif num==set([5,1]) or num==set([4,1,1]):
print 'Bear'
else:
print 'Alien' |
This is the hard version of the problem. The only difference is that in this version n ≤ 200000. You can make hacks only if both versions of the problem are solved.
There are n potions in a line, with potion 1 on the far left and potion n on the far right. Each potion will increase your health by a_i when drunk. a_i c... | 1 | #####################################
import atexit, io, sys, collections, math, heapq, fractions
buffer = io.BytesIO()
sys.stdout = buffer
@atexit.register
def write(): sys.__stdout__.write(buffer.getvalue())
#####################################
n = int(raw_input())
ais = map(int, raw_input().split())
heap = []
a... |
You are given an array a. Some element of this array ai is a local minimum iff it is strictly less than both of its neighbours (that is, ai < ai - 1 and ai < ai + 1). Also the element can be called local maximum iff it is strictly greater than its neighbours (that is, ai > ai - 1 and ai > ai + 1). Since a1 and an have ... | 1 | n = int(raw_input())
a = map(int, raw_input().split())
ans = 0
for i in range(1, n - 1):
ans += (a[i + 1] - a[i]) * (a[i - 1] - a[i]) > 0
print ans
|
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... | 1 | import sys
import collections
n = int(sys.stdin.readline())
trees = []
for line in sys.stdin:
trees.append(int(line.strip()))
height = trees[0]
cost = height + 1
for t in trees[1:]:
# print height, cost
diff = abs(t - height)
height = t
cost += diff + 2
print cost
|
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | n=str(input().lower())
y=str(input().lower())
if n>y:
print('1')
if n==y:
print('0')
if n<y:
print('-1')
|
Asterix, Obelix and their temporary buddies Suffix and Prefix has finally found the Harmony temple. However, its doors were firmly locked and even Obelix had no luck opening them.
A little later they found a string s, carved on a rock below the temple's gates. Asterix supposed that that's the password that opens the t... | 3 | def prefixfunction(txt,m,lps):
l = 0
lps[0] = 0
i = 1
while i<m:
if txt[i]==txt[l]:
l+=1
lps[i] = l
i += 1
else:
if l!=0:
l = lps[l-1]
else:
lps[i] = 0
i += 1
if __name__ == '__main__':
s = input().strip()
longitud = len(s)
if longitud==1 or longitud==2:... |
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves... | 3 | def dfs(x,y,b1,s):
b1[s]=True
for i in range(n):
if b1[i]==False and (x[s]==x[i] or y[s]==y[i]):
dfs(x,y,b1,i)
n=int(input())
x=[]
y=[]
c=-1
b1=[False]*n;
for i in range(n):
a,b=map(int,input().split())
x.append(a)
y.append(b)
for j in range(n):
if b1[j]==False:
dfs(x,y,b1,j)
c=c+1
print(c) |
A bracket sequence is a string that is one of the following:
1. An empty string;
2. The concatenation of `(`, A, and `)` in this order, for some bracket sequence A ;
3. The concatenation of A and B in this order, for some non-empty bracket sequences A and B /
Given are N strings S_i. Can a bracket sequence be forme... | 3 | def main():
import sys
def input(): return sys.stdin.readline().rstrip()
n = int(input())
lx = []
rx = []
for i in range(n):
a = 0
cnt = 0
for j in input():
if j == '(':
cnt += 1
else:
cnt -= 1
a = min(a,... |
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 | n=int(input())
if n<=5:
print(0,min(n,2))
elif n==6:
print(1,2)
else:
c=n%7
min1=(2*(n//7)+max(0,n%7-5))
max1=2*(n//7)+min(2,c)
print(min1,max1) |
Because of budget cuts one IT company established new non-financial reward system instead of bonuses.
Two kinds of actions are rewarded: fixing critical bugs and suggesting new interesting features. A man who fixed a critical bug gets "I fixed a critical bug" pennant on his table. A man who suggested a new interesting... | 3 | n = int(input())
a = (n + 4) * (n + 3) * (n + 2) * (n + 1) * n // 2 // 3 // 4 // 5
b = (n + 2) * (n + 1) * n // 2 // 3
print(a * b) |
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after x is the smallest prime number greater than x. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that ... | 3 | n,m=map(int,input().split())
check=1
for i in range(n+1,m):
for j in range(2,i):
if(i%j==0):
break
else:
check=0
for i in range(2,m):
if(m%i==0):
check=0
if(check==0):
print("NO")
else:
print("YES") |
Chef recently saw the movie Matrix. He loved the movie overall but he didn't agree with some things in it. Particularly he didn't agree with the bald boy when he declared - There is no spoon. Being a chef, he understands the importance of the spoon and realizes that the universe can't survive without it. Furthermore, h... | 1 | for i in range(int(raw_input())):
a,b = [int(x) for x in raw_input().split()]
ver = ['']*b
hori = []
big = ''
for j in range(a):
t = (str(raw_input())).lower()
hori.append(t)
big += t
for word in hori:
i = 0
for ch in word:
ver[i] += ch
... |
A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two r... | 3 | n, k = list(map(int, input().split()))
arr = [k for k in range(1, n+1)]
arr2 = arr.copy()
for _ in range(k):
a, b = list(map(int, input().split()))
if a in arr:
arr.remove(a)
if b in arr:
arr.remove(b)
z = arr[0]
arr2.remove(z)
print(n - 1)
for kk in arr2:
print(z, kk)
|
For a positive integer n let's define a function f:
f(n) = - 1 + 2 - 3 + .. + ( - 1)nn
Your task is to calculate f(n) for a given integer n.
Input
The single line contains the positive integer n (1 ≤ n ≤ 1015).
Output
Print f(n) in a single line.
Examples
Input
4
Output
2
Input
5
Output
-3
Note
f(4)... | 1 | n = int(raw_input())
print n / 2 - n if n % 2 else n / 2
|
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 | """
Oh, Grantors of Dark Disgrace,
Do Not Wake Me Again.
"""
# import stackprinter
# stackprinter.set_excepthook(style='color')
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
si = lambda: input()
n, t = mi()
q = si()
while t>0:
q = q.replace("BG", "GB")
t -= 1
pri... |
Polycarp is working on a new project called "Polychat". Following modern tendencies in IT, he decided, that this project should contain chat as well. To achieve this goal, Polycarp has spent several hours in front of his laptop and implemented a chat server that can process three types of commands:
* Include a perso... | 3 | members = 0
size = 0
while 1 > 0:
try:
a = input ()
if a[0] == '+':
members = members + 1
if a[0] == '-':
members = members - 1
for i in range ( len( a ) ):
if a[i] == ':':
break
message = len(a) - i - 1
size += mess... |
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!).
<image> illustration by 猫屋 https://twitter.com/nekoy... | 3 | #!/usr/bin/env python3
# O(n) approach
S = input()
n = len(S)
QL = [0]*n
for i in range(n):
QL[i] = (QL[i-1] if i>0 else 0) + int(S[i]=='Q')
QR = [0]*n
for i in range(n-1,-1,-1):
QR[i] = (QR[i+1] if i<n-1 else 0) + int(S[i]=='Q')
print(sum(QL[i]*QR[i] for i in range(n) if S[i]=='A'))
|
We have a sequence of N integers A~=~A_0,~A_1,~...,~A_{N - 1}.
Let B be a sequence of K \times N integers obtained by concatenating K copies of A. For example, if A~=~1,~3,~2 and K~=~2, B~=~1,~3,~2,~1,~3,~2.
Find the inversion number of B, modulo 10^9 + 7.
Here the inversion number of B is defined as the number of o... | 3 | n,k=map(int,input().split())
A=[int(i) for i in input().split()]
import bisect
mod=10**9+7
AA=[]
ans1=0
for i in range(n):
ans1+=i-bisect.bisect_right(AA,A[i])
AA.append(A[i])
AA.sort()
ans2=0
for i in range(n-1):
ans2+=n-bisect.bisect_right(AA,AA[i])
ans=(ans1*k)%mod
ans=(ans+ans2*k*(k-1)//2)%mod
print(ans) |
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | import sys
input = sys.stdin.readline
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
tests = inp()
testcount = 0
while testcount < tests:
a,b,c,d = invr()
p... |
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 |
from math import *
for _ in range(int(input())):
n=int(input())
i=0
ls=[]
while(n>0):
p=n%10
n//=10
x=10**i
ls.append(p*x)
i+=1
l=[]
for i in ls:
if i!=0:l.append(i)
print(len(l))
print(*l) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input())
s = input()
ans = 0
for i in range(1, n):
if s[i] == s[i - 1]:
ans += 1
print(ans) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.