problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
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.... | 1 | import math
s = []
for x in range(5):
s.append(raw_input().split())
c = 0
r = 0
for x in s:
if '1' in x:
c = x.index('1')
r = s.index(x)
break
#print r,c
if r!= 2 or c!=2:
w = abs(2-r)+ abs(2-c)
else:
w = 0
print w
|
Write a program which reads a $n \times m$ matrix $A$ and a $m \times l$ matrix $B$, and prints their product, a $n \times l$ matrix $C$. An element of matrix $C$ is obtained by the following formula:
\\[ c_{ij} = \sum_{k=1}^m a_{ik}b_{kj} \\]
where $a_{ij}$, $b_{ij}$ and $c_{ij}$ are elements of $A$, $B$ and $C$ res... | 3 | n,m,l=map(int,input().split())
A=[list(map(int,input().split())) for i in range(n)]
B=[list(map(int,input().split())) for i in range(m)]
#print(A)
#print(B)
for i in range(n):
for j in range(l):
youso=0
for k in range(m):
youso+=A[i][k]*B[k][j]
if j==0:
print(youso,end="")
else:
pri... |
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 | i= int(input())
i= int((i+1)/2)
print(i) |
Divide and rule
Taro, Hanako, and Jiro rule the JAG Kingdom together. There are N cities in the JAG Kingdom, some of which are connected by two-way roads. You can always reach all the other cities from any city via one or more roads.
One day, Taro and Hanako finally made a mistake and decided to share the city and go... | 3 | #!usr/bin/env python3
from collections import defaultdict
from collections import deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS():return list(map(list, sys.stdin.... |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | 3 | from sys import stdin
input = stdin.readline
for _ in range(int(input())):
n = int(input())
l = sorted(list(map(int,input().split())))
ans=0
cntr = [0]*(2*n+1)
for i in l:
cntr[i]+=1
for s in range(2,2*n+1):
temp = 0
for i in range(1,s):
temp += min(cntr[i],cn... |
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2).
In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar... | 3 | N = int(input())
for _ in range(N):
n, k = map(int, input().split())
wow = 'NO'
if k>n:
pass
elif n%2==1:
if k%2==1:
output = [1]*(k-1) + [n-k+1]
wow = 'YES'
else:
if k<=n//2:
output = [2]*(k-1) + [n-2*k+2]
wow = 'YE... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n = int(input())
t = 0;
for i in range(0, n):
p, q = map(int, input().split())
if(q - p >= 2): t += 1;
print(t) |
In a far away dystopian world, the measure of the quality of a person’s life is the numbers of likes he gets for an article about their life. For a person to stay alive, he has to acquire at least L number of likes before D days pass.
People in this world employ various techniques to increase the number of likes.... | 1 | t = int(raw_input())
for _ in xrange(t):
l,d,s,c = map(int,raw_input().split())
for i in xrange(d-1):
s+=(c*s)
if s>=l:
break
if s>=l:
print "ALIVE AND KICKING"
else:
print "DEAD AND ROTTING" |
You are given a positive integer n, it is guaranteed that n is even (i.e. divisible by 2).
You want to construct the array a of length n such that:
* The first n/2 elements of a are even (divisible by 2);
* the second n/2 elements of a are odd (not divisible by 2);
* all elements of a are distinct and positi... | 3 | for _ in range(int(input())):
n = int(input())
if(n%4!=0):
print("NO")
else:
print("YES")
for i in range(n//2):
print(2+2*i,end=" ")
for i in range(n//2-1):
print(1+2*i,end=" ")
print(1+3*n//2-2) |
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 | n = input()
p = []
for i in n:
if i not in p:
p.append(i)
if len(p) % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
|
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn... | 1 | from itertools import permutations as perm
def f(p):
res = 0
for i in range(len(p)):
for j in range(i, len(p)):
res += min(p[i:j+1])
return res
n, m = map(int, raw_input().split())
mm = 0
for p in perm(range(1, n + 1), n):
mm = max(mm, f(p))
cnt = 0
for p in perm(range(1, n + 1... |
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | 3 | import sys
input = sys.stdin.readline
def read_i():
return list(map(int, input().split()))
class Combinations:
def __init__(self, max_num, mod):
self.mod = mod
self.factorials = [1]
for i in range(1, max_num + 1):
self.factorials.append((self.factorials[-1] * i) % mod)
... |
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken ... | 1 | x = input()
c = 0
if x == 12:
s = list(raw_input())
if int(s[3]) >= 6:
c+=1
s[3] = '0'
if s[0] == '1':
if (s[1] != '1' and s[1] != '0' and s[1] != '2'):
c+=1
s[1] = '0'
elif s[0] == '0':
if s[1] == '0':
s[0] = '1'
c+=1
else:
if s[1] == '0':
s[0] = '1'
c+=1
else:
s[0] =... |
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.
Unfortunately, an adversa... | 3 | #: Author - Soumya Saurav
import sys,io,os,time
from collections import defaultdict
from collections import OrderedDict
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect,math,heapq
alphabet = "abcdefghijklmnopqrstuvwxyz"
input = sys.stdin.readline
######... |
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 | if __name__ == "__main__":
for _ in range(int(input())):
n, p, k = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
pref = [0]
for i in a[ : k - 1]:
pref.append(pref[-1] + i)
ans = 0
for i, num in enumerate(pref):
... |
Where do odds begin, and where do they end? Where does hope emerge, and will they ever break?
Given an integer sequence a1, a2, ..., an of length n. Decide whether it is possible to divide it into an odd number of non-empty subsegments, the each of which has an odd length and begins and ends with odd numbers.
A subse... | 3 | n = int(input())
a = list(map(int, input().split()))
if len(a) % 2 == 0:
#if a[0] % 2 == 0 or a[-1] % 2 == 0:
print('no')
elif len(a) % 2 == 1:
if a[0] % 2 == 1 and a[-1] % 2 == 1:
print('yes')
else:
print('no')
|
Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).
Consider a sequence A satisfying the following conditions:
* A is a sequence of N positive integers.
* 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.
Let us define a score of this sequence as follows:
* The score is the ... | 3 | import itertools
n, m, q = map(int, input().split())
abcd = [list(map(int, input().split())) for _ in range(q)]
v = list(itertools.combinations_with_replacement(range(1, m+1), n))
ans = 0
for i in v:
s = 0
for a, b, c, d in abcd:
if i[b-1] - i[a-1] == c:
s += d
ans = max(ans, s)
print(a... |
We have a grid with H rows and W columns. At first, all cells were painted white.
Snuke painted N of these cells. The i-th ( 1 \leq i \leq N ) cell he painted is the cell at the a_i-th row and b_i-th column.
Compute the following:
* For each integer j ( 0 \leq j \leq 9 ), how many subrectangles of size 3×3 of the gr... | 3 | from collections import defaultdict
H, W, N, *L = map(int, open(0).read().split())
dic = defaultdict(int)
for a, b in zip(*[iter(L)]*2):
for i in range(a-2,a+1):
for j in range(b-2,b+1):
if 0<i and i+2<=H and 0<j and j+2<=W:
dic[(i,j)] += 1
ans = [0]*10
ans[0] = (W-2)*(H-2)
for k in dic.keys():
an... |
You are given a weighted undirected graph. The vertices are enumerated from 1 to n. Your task is to find the shortest path between the vertex 1 and the vertex n.
Input
The first line contains two integers n and m (2 ≤ n ≤ 105, 0 ≤ m ≤ 105), where n is the number of vertices and m is the number of edges. Following m l... | 3 | import heapq
from sys import stdin, stdout
# Dijktra's shortest path algorithm. Prints the path from source to target.
# If no path exists -1 is printed
# dictionary (hash map implementation) is used here instead of an array
def dijkstra(adj, source, target):
INF = ((1<<63) - 1)//2
pred = { x:x for x in adj }... |
A telephone number is a sequence of exactly 11 digits, where the first digit is 8. For example, the sequence 80011223388 is a telephone number, but the sequences 70011223388 and 80000011223388 are not.
You are given a string s of length n, consisting of digits.
In one operation you can delete any character from strin... | 3 | n = int(input())
for i in range(n):
x = int(input())
s = input()
try:
if x - s.index('8') >= 11:
print("YES")
else:
print('NO')
except:
print('NO') |
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 | import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.wri... |
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 | whatever=int(input())
for i in range (whatever) :
n=int(input())
spent=0
while (n>0) :
if n>=10 :
k=n-(n%10)
spent+=k
n=n-k
n=n+(k/10)
else :
... |
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 | import io, sys, atexit, os
import math as ma
from sys import exit
from decimal import Decimal as dec
from itertools import permutations
from itertools import combinations
def li():
return list(map(int, sys.stdin.readline().split()))
def num():
return map(int, sys.stdin.readline().split())
def nu():
re... |
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her n students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddl... | 3 | N, M = map(int, input().split(' '))
puzzles = list(map(int, input().split(' ')))
puzzles.sort()
ans = 100000000000
for i in range(N - 1, M):
ans = min(ans, puzzles[i] - puzzles[i - N + 1])
print(ans)
|
It's a walking tour day in SIS.Winter, so t groups of students are visiting Torzhok. Streets of Torzhok are so narrow that students have to go in a row one after another.
Initially, some students are angry. Let's describe a group of students by a string of capital letters "A" and "P":
* "A" corresponds to an angry... | 3 | t = int(input())
for i in range(t):
maxi = 0
aux = 0
n = int(input())
s = input()
for i in range(n):
if s[i] == "A":
aux = 0
i += 1
if i<n:
while s[i] == "P":
aux +=1
i +=1
if i==n... |
There are two popular keyboard layouts in Berland, they differ only in letters positions. All the other keys are the same. In Berland they use alphabet with 26 letters which coincides with English alphabet.
You are given two strings consisting of 26 distinct letters each: all keys of the first and the second layouts i... | 3 | s1 = input()
s2 = input()
res = input()
str = ""
l = []
l1 = []
for i in s1:
l.append(i)
for i in s2:
l1.append(i)
for i in res:
if i >= '0' and i <= '9':
str = str+i
else:
if i >= 'A' and i <= 'Z':
n = l.index(i.lower())
str = str + l1[n].upper()
else:
n = l... |
"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()))
t = 0
for i in range(n):
if a[i] > 0 and a[i] >= a[k-1]:
t += 1
print(t) |
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 | 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 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26
def split(word):
return [char for char in word]
A = split(input().lower())
B = split(input().lower())
for i in range(len(A)):
if A[i] < B[... |
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 | #111_C
from collections import Counter
n=int(input())
v=list(map(int,input().split()))
v1=[v[2*i] for i in range(n//2)]
v2=[v[2*i+1] for i in range(n//2)]
V1=Counter(v1).most_common()
V2=Counter(v2).most_common()
V1.append((0,0))
V2.append((0,0))
Ans=n-V1[0][1]-V2[0][1]
if V1[0][0]==V2[0][0]:
Ans+=min(V1[0][1]-... |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 | def solve(n):
c = 0
while n != 1:
if n % 2 == 0:
n //= 2
c += 1
elif n % 3 == 0:
n //= 3
c += 2
elif n % 5 == 0:
n //= 5
c += 3
else:
return -1
return c
t = int... |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k dollars for the second one and so on (in other words, he has to pay i·k dollars for the i-th banana).
He has n dollars. How many dollars does he have to borrow from his friend soldier to buy w bananas?
Input
The first lin... | 3 | inp1=str(input())
inp=inp1.split()
k=int(inp[0])
n=int(inp[1])
w=int(inp[2])
add=0
j=1
while(j<=w):
add=add+(k*j)
j+=1
ans=add-n
if(ans>0):
print(ans)
else:
print('0')
|
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | s=int(input())
while True:
s+=1
s1=str(s)
a=set()
for i in s1:
a.add(i)
if len(a)==len(s1):
print(s1)
break
|
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 3 | import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
e = list(map(int, input().split()))
e.sort()
cur = 0
num = 0
for k in range(n):
cur += 1
if cur > 0 and e[k] <= cur:
num += 1
cur = 0
print(num)
|
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob... | 1 | n = int(raw_input())
count = 1
for i in range(5):
count *= n**2
n -= 1
print (int(count/120))
|
A permutation of length n is a sequence of integers from 1 to n of length n containing each number exactly once. For example, [1], [4, 3, 5, 1, 2], [3, 2, 1] are permutations, and [1, 1], [0, 1], [2, 2, 1, 4] are not.
There was a permutation p[1 ... n]. It was merged with itself. In other words, let's take two instanc... | 3 | def solve(n, a):
p = []
for x in a:
if x not in p:
p.append(x)
return p
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
# x, y, z = map(int, input().split())
sol = solve(n, a)
print(' '.join(map(str, sol))) |
You are given an n × m rectangular table consisting of lower case English letters. In one operation you can completely remove one column from the table. The remaining parts are combined forming a new table. For example, after removing the second column from the table
abcd
edfg
hijk
... | 1 | n, m = map(int, raw_input().split())
s = [raw_input() for _ in range(n)]
f = [''] * n
c = 0
for i in range(m):
t = [f[j] + s[j][i] for j in range(n)]
if t == sorted(t):
f = t
else:
c += 1
print c
|
Alicia has an array, a_1, a_2, …, a_n, of non-negative integers. For each 1 ≤ i ≤ n, she has found a non-negative integer x_i = max(0, a_1, …, a_{i-1}). Note that for i=1, x_i = 0.
For example, if Alicia had the array a = \{0, 1, 2, 0, 3\}, then x = \{0, 0, 1, 2, 2\}.
Then, she calculated an array, b_1, b_2, …, b_n: ... | 3 | n = int(input())
a = list(map(int, input().split()))
print(a[0], end = ' ')
sum = a[0]
for i in range(1, n):
temp = a[i]+sum
print(temp, end = ' ')
if temp > sum:
sum = temp |
Vasya likes to solve equations. Today he wants to solve (x~div~k) ⋅ (x mod k) = n, where div and mod stand for integer division and modulo operations (refer to the Notes below for exact definition). In this equation, k and n are positive integer parameters, and x is a positive integer unknown. If there are several solu... | 3 | n, k = map(int, input().split())
j = k-1
while j > 1:
if n%j == 0:
break
j-=1
x = (n//j)*k + j
print(x)
|
12:17 (UTC): The sample input 1 and 2 were swapped. The error is now fixed. We are very sorry for your inconvenience.
There are N children in AtCoder Kindergarten, conveniently numbered 1 through N. Mr. Evi will distribute C indistinguishable candies to the children.
If child i is given a candies, the child's happine... | 3 | import sys
N,C=map(int,input().split())
A=[int(i) for i in input().split()]
B=[int(i) for i in input().split()]
mod=10**9+7
table=[[ pow(j,i,mod) for j in range(405)] for i in range(405)]
ntable=[[0]*405 for i in range(405)]
for i in range(405):
t=0
for j in range(1,405):
t+=table[i][j]
t%=mod
... |
Polycarp has recently created a new level in this cool new game Berlio Maker 85 and uploaded it online. Now players from all over the world can try his level.
All levels in this game have two stats to them: the number of plays and the number of clears. So when a player attempts the level, the number of plays increases... | 3 | t=int(input())
while t:
t-=1
ans='-'
n=int(input())
arr=[]
for i in range(n):
u,v=[int(c) for c in input().split()]
if v > u or v <0 or u <0:
ans="NO"
arr.append((u,v))
if ans!='-':
print(ans)
else:
for i in range(1,n):
if arr[i][0] < arr [i-1][0] or arr[i][1] < arr[i-... |
Petr has just bought a new car. He's just arrived at the most known Petersburg's petrol station to refuel it when he suddenly discovered that the petrol tank is secured with a combination lock! The lock has a scale of 360 degrees and a pointer which initially points at zero:
<image>
Petr called his car dealer, who in... | 3 | from sys import stdin
def recSolve(vec, sum, ptr):
if ptr == len(vec):
if sum % 360 == 0:
return True
else:
return False
if not recSolve(vec, sum + vec[ptr], ptr + 1):
return recSolve(vec, sum - vec[ptr], ptr + 1)
else:
return True
n = int(stdin.r... |
One industrial factory is reforming working plan. The director suggested to set a mythical detail production norm. If at the beginning of the day there were x details in the factory storage, then by the end of the day the factory has to produce <image> (remainder after dividing x by m) more details. Unfortunately, no c... | 3 | n,m=map(int,input().split())
q={-1}
while n%m not in q:q.add(n%m);n+=n%m
print("YNeos"[0not in q::2]) |
This problem is given in two editions, which differ exclusively in the constraints on the number n.
You are given an array of integers a[1], a[2], ..., a[n]. A block is a sequence of contiguous (consecutive) elements a[l], a[l+1], ..., a[r] (1 ≤ l ≤ r ≤ n). Thus, a block is defined by a pair of indices (l, r).
Find a... | 1 | class solution(object):
def __init__(self, a):
self.a = a
def sol(self):
n = len(self.a)
acc = [0]
interval = []
for i in xrange(1, n + 1):
acc.append(acc[i - 1] + self.a[i - 1])
st = set()
for i in xrange(1, n + 1):
for ... |
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. I... | 3 | for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
ans = 0
min_cost = 1e10
if n <= 2:
print(0)
continue
for i in range(n):
if i > 0:
ans += abs(a[i] - a[i-1])
if i == 0:
# change to right
mi... |
DZY has a hash table with p buckets, numbered from 0 to p - 1. He wants to insert n numbers, in the order they are given, into the hash table. For the i-th number xi, DZY will put it into the bucket numbered h(xi), where h(x) is the hash function. In this problem we will assume, that h(x) = x mod p. Operation a mod b d... | 3 | p,n=map(int,input().split())
s=[]
index=-1
for i in range(n):
x=int(input())
yy=(x%p)
if yy in s:
if index==-1:
index=i+1
else:
s.append(yy)
print(index)
|
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 | n=input()
n=int(n)
if n==2 or n%2==1:
print ('NO')
else:
print ('YES')
|
Wabbit is trying to move a box containing food for the rest of the zoo in the coordinate plane from the point (x_1,y_1) to the point (x_2,y_2).
He has a rope, which he can use to pull the box. He can only pull the box if he stands exactly 1 unit away from the box in the direction of one of two coordinate axes. He will... | 3 | t=int(input())
for i in range(t):
x1,y1,x2,y2=map(int,input().split())
ans=0
if x1-x2==0:
ans+=abs(y1-y2)
elif y1-y2==0:
ans+=abs(x1-x2)
else:
ans+=2+abs(x1-x2)+abs(y1-y2)
print(ans) |
Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly gre... | 3 | q = int(input())
for i in range(q):
x = [int(i) for i in input().split()]
k = x[0]
n = x[1]
a = x[2]
b = x[3]
k = k - n*a
if(k>0):
print(n)
else:
k = - k + 1
diff = a-b
turns = (k+diff-1)//diff
if(turns > n):
print(-1)
else:
print(n-turns) |
Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy... | 3 | import math
def main():
n = int(input())
length = int(math.sqrt(n))
if length * length == n:
print(length * 4)
elif length * (length+1) >= n:
print((length * 2 + 1) * 2)
else:
print((length+1) * 4)
if __name__ == '__main__':
main()
|
Polycarp has a checkered sheet of paper of size n × m. Polycarp painted some of cells with black, the others remained white. Inspired by Malevich's "Black Square", Polycarp wants to paint minimum possible number of white cells with black so that all black cells form a square.
You are to determine the minimum possible ... | 3 | n,m = map(int,input().split())
b=0
maxy=maxx=-1
miny=minx=max(m,n)-1
for i in range(n):
s=str(input())
for j in range(m):
if s[j]=='B':
b+=1
minx=min(minx,j); maxx=max(maxx,j)
miny=min(miny,i); maxy=max(maxy,i)
if b==0: print(1)
else:
dx=maxx-minx+1; dy=maxy-miny+... |
Being tired of participating in too many Codeforces rounds, Gildong decided to take some rest in a park. He sat down on a bench, and soon he found two rabbits hopping around. One of the rabbits was taller than the other.
He noticed that the two rabbits were hopping towards each other. The positions of the two rabbits ... | 3 | def judge(t):
return x+a*t<=y-b*t
def binary_search():
l, r = 0, 10**9
while l<=r:
mid = (l+r)//2
if judge(mid):
l = mid+1
else:
r = mid-1
return r
t = int(input())
for _ in range(t):
x, y, a, b = map(int, input().split())
... |
A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all n squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their h... | 1 | n=input()
lst=map(int,raw_input().split())
time=0
k=lst.index(max(lst))
for i in range(k,0,-1):
if lst[i]>lst[i-1]:
temp=lst[i]
lst[i]=lst[i-1]
lst[i-1]=temp
time=time+1
m=min(lst)
for i, v in enumerate(reversed(lst)):
if v == m:
last = len(lst) - i - 1
break
... |
Ashish has n elements arranged in a line.
These elements are represented by two integers a_i — the value of the element and b_i — the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i.
He can perform the following operation any number of t... | 3 | t = int(input())
for t in range(0, t):
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
x = False
if sum(b) == 0 or sum(b) == n:
x = True
y = a[:]
y.sort()
if x and y == a:
print("YES")
else:
one = two = False
... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | def stringtask(n):
x=0
for i in range(n):
op=input()
if op=='X++' or op=='++X':
x+=1
else:
x-=1
print(x)
n=int(input())
stringtask(n) |
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land.
Formally,
* You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ... | 3 | t = int(input())
while t:
a,b = map(int, input().split())
ans = min(max(2*b,a), max(2*a,b))
print(ans*ans)
t-=1 |
Santa Claus has n candies, he dreams to give them as gifts to children.
What is the maximal number of children for whose he can give candies if Santa Claus want each kid should get distinct positive integer number of candies. Santa Class wants to give all n candies he has.
Input
The only line contains positive integ... | 3 | n = int(input())
i = 1
s = []
while(i<=n):
s.append(i)
n -= i
i += 1
s[-1] = s[-1] + n
print(i-1)
print(*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())
List = []
for i in range(int(n)):
List.append(input())
for i in range(int(n)):
t = List[i]
if int(len(t)) <= 10:
print(t)
elif int(len(t)) > 10:
i2 = int(len(t))-2
for j in range(int(len(t))):
i1 = t[0]
i3 = t[len(t)-1]
print(i1... |
problem
JOI Shoji manages the time spent at work by employees with a time card. When an employee arrives at the office, he / she uses a dedicated device to stamp the arrival time on the time card. When leaving the office after work, the time of leaving the office is stamped on the time card. The time is handled in a 2... | 3 | for _ in range(3):
t=list(map(int,input().split()))
tt=(t[3]-t[0])*3600+(t[4]-t[1])*60+t[5]-t[2]
h,tt=divmod(tt,3600)
m,s=divmod(tt,60)
print(h,m,s) |
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n=int(input())
s=input().split()
nd=[1 for i in range(n)]
for i in range(n-2,-1,-1):
if eval(s[i])<=eval(s[i+1]):nd[i]=nd[i+1]+1
nd=sorted(nd,reverse=True)
print(nd[0]) |
Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows:
* Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `888888... | 3 | s = input()
k = int(input())
for i in range(0,k):
if s[i] != '1':
print(s[i])
exit()
print(s[0])
|
After lessons Nastya decided to read a book. The book contains n chapters, going one after another, so that one page of the book belongs to exactly one chapter and each chapter contains at least one page.
Yesterday evening Nastya did not manage to finish reading the book, so she marked the page with number k as the fi... | 3 | N = int(input())
R = []
for _ in range(N):
l, r = map(int, input().split())
R.append(r)
k = int(input())
ans = 0
for i in range(N):
if R[i] >= k:
ans += 1
print(ans)
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | 3 | # http://codeforces.com/problemset/problem/131/A
s = input()
if s[0].islower() and s[1:].isupper():
print(s.capitalize())
elif s.isupper():
print(s.lower())
elif len(s)==1 and s.islower():
print(s.upper())
else:
print(s) |
You are given an array a consisting of n integers.
Your task is to determine if a has some subsequence of length at least 3 that is a palindrome.
Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c... | 3 | # import bisect
# import os
# import io
# from collections import Counter
import bisect
from collections import defaultdict
# import math
# import random
# import heapq as hq
# from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import ... |
You've got array a[1], a[2], ..., a[n], consisting of n integers. Count the number of ways to split all the elements of the array into three contiguous parts so that the sum of elements in each part is the same.
More formally, you need to find the number of such pairs of indices i, j (2 ≤ i ≤ j ≤ n - 1), that <image>... | 3 | import bisect
input()
ls=list(map(int,input().split()))
cum=[0]*len(ls)
cum[0]=ls[0]
for i in range(1, len(cum)):
cum[i]=ls[i]+cum[i-1]
def f(arr,a,b): #inclusive endpoints
if a==0:
return arr[b]
else:
return arr[b]-arr[a-1]
c=0
s=sum(ls)
if not s%3: #can divide
btm=[]
top=[]
tg=s//3
#print(cum... |
Agent OO7 is engaged in a mission to stop the nuclear missile launch. He needs a surveillance team to monitor the progress of the mission. Several men with different type of capabilities assemble in a hall, help OO7 to find out total men with different capabilities. Capability is represented in form of numbers.
Input -... | 1 | for i in range(input()):
n=input()
print len(set(raw_input().split())) |
There are K blue balls and N-K red balls. The balls of the same color cannot be distinguished. Snuke and Takahashi are playing with these balls.
First, Snuke will arrange the N balls in a row from left to right.
Then, Takahashi will collect only the K blue balls. In one move, he can collect any number of consecutive ... | 3 | import math
def comb(n, r):
return math.factorial(n) // (math.factorial(n - r) * math.factorial(r))
N,K=map(int,input().split())
div=10**9+7
for i in range(K):
if N-K<i:
print(0)
else:
print(comb(K-1,i)*comb(N-K+1,i+1)%div) |
Cengiz recently learned Fibonacci numbers and now he is studying different algorithms to find them. After getting bored of reading them, he came with his own new type of numbers that he named XORinacci numbers. He defined them as follows:
* f(0) = a;
* f(1) = b;
* f(n) = f(n-1) ⊕ f(n-2) when n > 1, where ⊕ de... | 3 | #1208A
def XORinacci(a,b,n):
if n==0:
return(a)
if n==1:
return(b)
if n==2:
return(a^b)
return XORinacci(a,b,n%3)
x=[]
t=int(input())
for i in range(t):
s=input()
l=s.split()
a=int(l[0])
b=int(l[1])
n=int(l[2])
x.append(XORinacci(a,b,n))
for i... |
You are given two arrays of integers a_1,…,a_n and b_1,…,b_m.
Your task is to find a non-empty array c_1,…,c_k that is a subsequence of a_1,…,a_n, and also a subsequence of b_1,…,b_m. If there are multiple answers, find one of the smallest possible length. If there are still multiple of the smallest possible length, f... | 3 | t = int(input())
while (t):
line = input().split()
n,m = int(line[0]), int(line[1])
a = input().split()
a = list(map(int,a))
b = input().split()
b = set(list(map(int,b)))
ans = -1
for x in a:
if (x in b):
ans = x
break
if (ans == -1):
print('NO')
else:
print('YES')
print(1,ans)
t -= 1
|
You have an integer variable x. Initially, x=0.
Some person gave you a string S of length N, and using the string you performed the following operation N times. In the i-th operation, you incremented the value of x by 1 if S_i=`I`, and decremented the value of x by 1 if S_i=`D`.
Find the maximum value taken by x duri... | 3 | N =int(input())
S =input()
ans = 0
for i in range(N):
ans = max(S[:i+1].count("I")-S[:i+1].count("D"),ans)
print(ans) |
[3R2 as DJ Mashiro - Happiness Breeze](https://open.spotify.com/track/2qGqK8GRS65Wlf20qUBEak)
[Ice - DJ Mashiro is dead or alive](https://soundcloud.com/iceloki/dj-mashiro-is-dead-or-alive)
NEKO#ΦωΦ has just got a new maze game on her PC!
The game's main puzzle is a maze, in the forms of a 2 × n rectangle grid. NEKO... | 3 | import sys
def build_seg_tree(n):
tree = [False] * (2*n)
return tree
def modify_seg_tree(tree, pos, val):
n = len(tree) // 2
pos += n
tree[pos] = val
while pos > 1:
pos = pos // 2
tree[pos] = tree[2*pos] or tree[(2*pos)+1]
return
def query_seg_tree(tree, lptr, rptr):
... |
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used... | 3 | w1,h1,w2,h2=input().split()
w1,h1,w2,h2=int(w1),int(h1),int(w2),int(h2)
h4=h1+h2
w4=max([w1,w2])
print((h4+2)*(w4+2)-h4*w4) |
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 | s = input()
p = 0
for i in s:
if i in "HQ9":
print("YES")
p = 1
break
if p == 0:
print("NO")
|
We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N.
Determine whether the conditions below can be satisfied by assigning a color - white or black - to each v... | 3 | import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from operator import itemgetter
from collections import defaultdict
N,M = map(int,readline().split())
D = [0] + list(map(int,readline().split()))
m = map(int,read().split())
UV = list(zip(m,m))
graph =... |
Orac is studying number theory, and he is interested in the properties of divisors.
For two positive integers a and b, a is a divisor of b if and only if there exists an integer c, such that a⋅ c=b.
For n ≥ 2, we will denote as f(n) the smallest positive divisor of n, except 1.
For example, f(7)=7,f(10)=2,f(35)=5.
... | 3 | def Prime_Seave(n,arr):
ans = []
arr[0] = False
i = 4
while i < n+1:
arr[i-1] = False
i += 2
i = 3
while i*i < n+1:
for k in range(i*i,n+1,2*i):
arr[k-1] = False
i += 2
i = 1
while i < n:
if arr[i]:
ans.append(i+1)
i... |
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 | s=set(input())
if((len(s)&1)==1):
print("IGNORE HIM!")
else:
print("CHAT WITH HER!")
|
Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a roo... | 1 | def solve(pos, n, m):
x = set()
y = set()
xn = n
yn = n
ans = []
for p in pos:
if p[0] not in x:
x.add(p[0])
xn -= 1
if p[1] not in y:
y.add(p[1])
yn -= 1
ans.append(xn*yn)
return ans
n, m = map(int, raw_input().split())
pos = []
for _ in xrange(m):
x, y = map(int, raw_input().split())
pos... |
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... | 1 | # This python file uses the following encoding: utf-8
''' http://codeforces.com/problemset/problem/750/A
Based on CPP https://harun9009.wordpress.com/2017/08/28/codeforces-solution-750a-new-year-and-hurry/
Python 2.7
https://stackoverflow.com/questions/419163/what-does-if-name-main-do'''
if __name__ == '__main__':
... |
There are N slimes standing on a number line. The i-th slime from the left is at position x_i.
It is guaruanteed that 1 \leq x_1 < x_2 < \ldots < x_N \leq 10^{9}.
Niwango will perform N-1 operations. The i-th operation consists of the following procedures:
* Choose an integer k between 1 and N-i (inclusive) with equ... | 3 | N = int(input())
X = list(map(int, input().split()))
MOD = 10**9+7
S = 0
res = 0
F = 1
for i in range(1,N):
S += pow(i,MOD-2,MOD)
res += (X[i]-X[i-1])*S
res%=MOD
F*=i
F%=MOD
print(res*F%MOD)
|
The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has n students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
The ... | 3 | n,k=input().split()
n=int(n)
k=int(k)
l=list(map(int,input().split()))
l.sort()
while(len(l)%3!=0):
l.append(6)
n=n+1;
count=0
i=2
while (i<n):
if(l[i]+k<=5):
count+=1
i=i+3
print(count) |
You are given string s. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string s=";;" contains three empty words separated by ';'.
You ... | 3 | import re
s = input()
f = s.split(',')
s = []
for i in f:
s += i.split(';')
fir = []
sec = []
reg = re.compile('[1-9]\d*')
for i in s:
if reg.fullmatch(i) == None and i != '0':
sec.append(i)
else:
fir.append(i)
if len(fir) > 0:
print('"' + ','.join(fir) + '"')
else:
print('-')
if len... |
So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | 1 | inp = [raw_input() for i in xrange(3)]
ls = list(inp[0]) + list(inp[1])
s = list(inp[2])
while len(s) > 0:
if s[0] in ls:
del ls[ls.index(s[0])]
del s[0]
else:
print "NO"
break
else:
print "YES" if len(ls) == 0 else "NO"
|
The School №0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti:
* ti = 1, if the i-th child is good at programming,
*... | 3 | import math
from collections import Counter
def get(f):
return map(f, input().split())
def divides(a, b):
return a % b == 0
def main():
n = int(input())
students = list(get(int))
pr = []
ma = []
ph = []
choice = {1: pr, 2: ma, 3: ph}
for i in range(n):
choice[studen... |
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 | n = int(input())
a,g,s=0,0,''
for _ in range(n):
x,y = map(int,input().split())
if abs(a+x - g)<=500:
s+='A'
a+=x
else:
s+='G'
g+=y
print(s) |
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [... | 3 | from sys import stdin
def input():
return stdin.readline()
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
if(n==0 or n==1):
print(sum(a))
continue
else:
su=0
pos=0
neg=-1000000000
fp=0
fn=0
for i in range(... |
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition.
There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont... | 3 | def calc(s):
presum = [0]
for ch in s:
presum.append(presum[-1])
if ch == '1':
presum[-1] += 1
ans = 0
for (l,r) in points:
ans += ((r-l+1) - (presum[r] - presum[l-1])) * (presum[r] - presum[l-1])
return ans
n, m = list(map(int, input().split()))
points = []
for _ in range(m):
points.app... |
Each evening after the dinner the SIS's students gather together to play the game of Sport Mafia.
For the tournament, Alya puts candies into the box, which will serve as a prize for a winner. To do that, she performs n actions. The first action performed is to put a single candy into the box. For each of the remainin... | 3 | import math
n, k = map(int, input().split())
p = int((-3+int(math.sqrt(9+8*(n+k))))/2)
print(int(p*(p+1)/2)-k)
|
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k... | 3 | n=int(input())
A=list(map(int,input().split()))
g=[[]for i in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
a-=1
b-=1
g[a].append(b)
g[b].append(a)
import sys
sys.setrecursionlimit(10**6)
lastdp=[10**9+1]*n
recode=[[10**9+1]for i in range(n)]
ans=[0]*n
from bisect import bisect_left
... |
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... | 3 | def offset(n, m):
if n % 2 == 1:
if (m == 'f'):
return 1
elif (m == 'e'):
return 2
elif (m == 'd'):
return 3
elif (m == 'a'):
return 4
elif (m == 'b'):
return 5
elif (m == 'c'):
return 6
else:... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 1 | import sys,string
L=list(map(int,raw_input().strip().split('+')))
L.sort()
for i in range(len(L)):
L[i]=str(L[i])
for i in range(len(L)-1):
sys.stdout.write(str(L[i])+"+")
sys.stdout.write(str(L[-1])) |
You are given an integer n.
You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:
1. Replace n with n/2 if n is divisible by 2;
2. Replace n with 2n/3 if n is divisible by 3;
3. Replace n with 4n/5 if n is divisible by 5.
For example, you can repl... | 3 | for i in range(int(input())):
k=int(input())
if(k<2):
print(0)
elif(k==2):
print(1)
else:
f=0
c=0
while(k!=2):
if(k%10==0):
k=k//2
c+=1
elif(k%2==0):
k=k//2
c+=1
el... |
Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements ... | 3 | # -*- coding: utf-8 -*-
"""
参考:https://img.atcoder.jp/arc074/editorial.pdf
・優先度付きキュー
"""
import sys
def input(): return sys.stdin.readline().strip()
sys.setrecursionlimit(10 ** 9)
from heapq import heappush, heappushpop
N = int(input())
aN = list(map(int, input().split()))
mids = aN[N:N*2]
L = []
R = []
for i in r... |
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of ope... | 3 | t=int(input())
l=list(input())
B=l.count('B')
W=l.count('W')
ll=[]
c=l.copy()
if t%2==0:
if B%2!=0 or W%2!=0:
print("-1")
else: ... |
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())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
l3=l1[1:]+l2[1:]
flag=0
for i in range(1,n+1):
if(i not in l3):
flag=1
break
if(flag==0):
print("I become the guy.")
else:
print("Oh, my keyboard!") |
We have a sequence of N integers: A_1, A_2, \cdots, A_N.
You can perform the following operation between 0 and K times (inclusive):
* Choose two integers i and j such that i \neq j, each between 1 and N (inclusive). Add 1 to A_i and -1 to A_j, possibly producing a negative element.
Compute the maximum possible pos... | 3 | n, k = map(int, input().split())
a = list(map(int, input().split()))
def ok(d):
m = sorted(a % d for a in a)
s, e, plus, minus = 0, len(m) - 1, 0, 0
while True:
if s > e:
return (plus == minus)
if plus <= minus:
plus += m[s]
if plus > k:
r... |
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())
a=[]
for i in range(n):
x=input()
if len(x)<=10:
a.append(x)
else:
y=x[0] + str(len(x)-2) + x[len(x)-1]
a.append(y)
for i in range(n):
print(a[i]) |
Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 ≤ i ≤ k), such that
1. 1 ≤ k ≤ 3
2. ... | 3 | def pr(x):
if x == 0:
return True
if x == 2:
return True
if x%2 == 0:
return False
for i in range(3,int(x**(1/2))+2,2):
if x % i == 0:
return False
return True
n = int(input())
a = n
while not pr(a):
a -= 1
n -= a
b = 0
c = 0
for i in range(n):
i... |
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones.
In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno... | 3 | # -*- coding: utf-8 -*-
"""
Created on Sun Jul 19 14:25:38 2020
@author: Mridul Garg
"""
w = int(input())
for o in range(w):
n = int(input())
A = list(map(int, input().split(" ")))
dp = [0]*n
dp[-1] = "F"
for i in range(n-2, -1, -1):
if dp[i+1] == "F":
if A[i] == 1:
... |
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | 3 | n=int(input())
#a=map(int,input().split())
a = input()
#print('before split a is', a)
a = a.split()
#print('after split a is: ', a)
a = [int(x) for x in a]
#print('now here a is:', a)
b=sorted(a)
new=list(reversed(b))
s=0
#print(sum(list(a)))
da=sum(a)/2
for i in range(n):
s=s+new[i]
if s>da:
print(i+... |
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 | n = input().lower()
s = ''
for i in n:
if i in 'aouiey':
continue
s += '.' + i
print(s)
|
Vasya has found a strange device. On the front panel of a device there are: a red button, a blue button and a display showing some positive integer. After clicking the red button, device multiplies the displayed number by two. After clicking the blue button, device subtracts one from the number on the display. If at so... | 3 | n, m = (int(x) for x in input().split())
i = 0
while m > n:
if m % 2 == 0:
m = m // 2
else:
m += 1
i += 1
print(i+n-m) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.