name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
103_B. Cthulhu | ...Once upon a time a man came to the sea. The sea was stormy and dark. The man started to call for the little mermaid to appear but alas, he only woke up Cthulhu...
Whereas on the other end of the world Pentagon is actively collecting information trying to predict the monster's behavior and preparing the secret super... | ```python
inp = input().split()
n = int(inp[0])
m = int(inp[1])
def dfs(x):
visited.add(x)
for y in e[x]:
if not y in visited:
dfs(y)
if n >= 3 and n == m:
visited = set()
e = [[] for i in range(n + 1)]
for i in range(m):
x, y = map(int, input().split(... |
1062_C. Banh-mi | JATC loves Banh-mi (a Vietnamese food). His affection for Banh-mi is so much that he always has it for breakfast. This morning, as usual, he buys a Banh-mi and decides to enjoy it in a special way.
First, he splits the Banh-mi into n parts, places them on a row and numbers them from 1 through n. For each part i, he de... | ```python
import sys
MOD = 10 ** 9 + 7
r = sys.stdin.readlines()
n, q = r[0].split(' ')
n = int(n)
q = int(q)
s = r[1]
c = [0] * (n + 1)
for i in range(n):
c[i + 1] = c[i] + (s[i] == '1')
p2 = [1] * (2 * n + 1)
for i in range(1, 2 * n + 1):
p2[i] = p2[i - 1] * 2 % MOD
out = []
for qq in range(q):
a, b = r[q... |
1084_B. Kvass and the Fair Nut | The Fair Nut likes kvass very much. On his birthday parents presented him n kegs of kvass. There are v_i liters of kvass in the i-th keg. Each keg has a lever. You can pour your glass by exactly 1 liter pulling this lever. The Fair Nut likes this drink very much, so he wants to pour his glass by s liters of kvass. But ... | ```python
x,y=map(int,input().split())
s=list(map(int,input().split()))
if sum(s)<y:
print(-1)
else:
j=sum(s)-y
if j<x:
print(0)
elif x==j:
print(1)
else:
print(min(min(s),j//x))
``` |
1131_D. Gourmet choice | Mr. Apple, a gourmet, works as editor-in-chief of a gastronomic periodical. He travels around the world, tasting new delights of famous chefs from the most fashionable restaurants. Mr. Apple has his own signature method of review — in each restaurant Mr. Apple orders two sets of dishes on two different days. All the di... | ```python
r,c = map(int, input().split())
m = []
p = [i for i in range(0,r+c)]
tree = [[] for i in range(0, r+c)]
for i in range(0,r):
s = input().split('\n')[0]
m.append(list(s))
def find(i):
if p[i] ==i:
return i
par = find(p[i])
p[i] = par
return p[i]
def join(i,j):
p[find(i... |
1151_F. Sonya and Informatics | A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens:
* Two numbers i and... | ```python
N, T = map(int, input().split())
A = [int(a) for a in input().split()]
if sum(A) > N//2:
A = [1-a for a in A][::-1]
K = sum(A)
S = sum(A[-K:])
M = K + 1
P = 10**9+7
inv = pow(N*(N-1)//2, P-2, P)
X = [[0]*M for _ in range(M)]
for i in range(M):
if i > 0: X[i-1][i] = ((K-i+1)**2*inv)%P
if i < M-1: X... |
1191_B. Tokitsukaze and Mahjong | Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first c... | ```python
string = input().split()
first = string[0]
second = string[1]
third = string[2]
string.sort(key=lambda x: int(x[0]))
if first == second == third or first[1] == second[1] == third[1] and all(int(string[i][0]) == int(string[i - 1][0]) + 1 for i in range(1, 3)):
print(0)
elif (first == second or second == th... |
122_E. Lucky Permutation | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how ... | ```python
import math
def good(x):
while x > 0:
if x % 10 != 4 and x % 10 != 7:
return False
x //=10
return True
n, k = map(int, input().split())
l = 1
r = n
if n >= 15:
l = n-14
if n <= 15 and math.factorial(n) < k:
print(-1)
else:
L = r - l + 1
a = []
for i i... |
1251_D. Salary Changing | You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the ... | ```python
import sys
from bisect import bisect_left
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
t = int(input())
for _ in range(t):
n, s = map(int, input().split())
mid = n >> 1
rl = []
for i in r... |
1271_B. Blocks | 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... | ```python
n=int(input())
s=list(input())
s.append("B")
b=s.count("B")
w=len(s)-b
if b==1 or w==0:
print(0)
exit(0)
s.pop(n)
b-=1
if b%2 and w%2:
print("-1")
exit(0)
if b%2==0:
p=[]
for i in range(s.index('B'),n-1):
if s[i]=="W":
continue
if s[i+1:].count('B')==0:
... |
1294_C. Product of Three Numbers | You are given one integer number n. Find three distinct integers a, b, c such that 2 ≤ a, b, c and a ⋅ b ⋅ c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 100)... | ```python
for _ in range(int(input())):
n=int(input())
i=1
c=2
l=[]
y=n
while(i<=2):
if n%c==0:
n=n//c
i=i+1
l.append(c)
if c>=y**0.5:
break
c=c+1
if l==[] or len(l)==1:
print("NO")
elif y%(l[0]*l[1])==0:
... |
1315_C. Restoring Permutation | You are given a sequence b_1, b_2, …, b_n. Find the lexicographically minimal permutation a_1, a_2, …, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 100).
The first line of... | ```python
t = int(input())
from collections import defaultdict
for _ in range(t):
dic = defaultdict(int)
dic2 = defaultdict(int)
n = int(input())
bl = list(map(int,input().split()))
for idx, b in enumerate(bl):
dic[b] = idx + 1
bl_sort = sorted(bl)
s = 0
kouho = []
for b in... |
1359_C. Mixing Water | There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infin... | ```python
# abs((desired*(2*n + 1) - ((n+1)*hot + n*cold))/(2*n + 1))
#EXPERIMENTING WITH LOSS DEFINTION - float ops ko aage peeche kar diya
import sys
def input():
return sys.stdin.readline().rstrip()
testcases = int(input())
answers = []
def loss(two_n_plus_one, hot, cold, desired):
n = two_n_plus_one//2
# if ... |
1379_E. Inverse Genealogy | Ivan is fond of genealogy. Currently he is studying a particular genealogical structure, which consists of some people. In this structure every person has either both parents specified, or none. Additionally, each person has exactly one child, except for one special person, who does not have any children. The people in... | ```python
from heapq import *
import sys
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(row... |
139_C. Literature Lesson | Vera adores poems. All the poems Vera knows are divided into quatrains (groups of four lines) and in each quatrain some lines contain rhymes.
Let's consider that all lines in the poems consist of lowercase Latin letters (without spaces). Letters "a", "e", "i", "o", "u" are considered vowels.
Two lines rhyme if their ... | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt'... |
1468_H. K and Medians | Let's denote the median of a sequence s with odd length as the value in the middle of s if we sort s in non-decreasing order. For example, let s = [1, 2, 5, 7, 2, 3, 12]. After sorting, we get sequence [1, 2, 2, \underline{3}, 5, 7, 12], and the median is equal to 3.
You have a sequence of n integers [1, 2, ..., n] an... | ```python
T = int(input())
for _ in range(T):
n, k, m = map(int, input().split())
b = [int(i) for i in input().split()]
f = False
ff = False
for p, i in enumerate(b):
if i - p - 1 == n - i - len(b) + p + 1:
f = True
break
if i - p - 1 >= k>>1 and n - i - len(... |
1493_B. Planet Lapituletti | The time on the planet Lapituletti goes the same way it goes on Earth but a day lasts h hours and each hour lasts m minutes. The inhabitants of that planet use digital clocks similar to earth ones. Clocks display time in a format HH:MM (the number of hours in decimal is displayed first, then (after the colon) follows t... | ```python
import sys,functools,collections,bisect,math,heapq
input = sys.stdin.readline
#print = sys.stdout.write
mirror = {0:0,1:1,2:5,5:2,8:8}
@functools.lru_cache(None)
def fun(i):
ones = i%10
i //= 10
tens = i%10
if ones in mirror:
newten = mirror[ones]
else:
return None
if... |
1543_A. Exciting Bets | Welcome to Rockport City!
It is time for your first ever race in the game against Ronnie. To make the race interesting, you have bet a dollars and Ronnie has bet b dollars. But the fans seem to be disappointed. The excitement of the fans is given by gcd(a,b), where gcd(x, y) denotes the [greatest common divisor (GCD)]... | ```python
import io,os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import math
t=int(input())
while(t>0):
t-=1
a,b=sorted(list(map(int,input().split())))
if(a==0):
print(str(b)+" 0")
continue
if(a==b):
print("0 0")
continue
if((b-a)==1):
print... |
171_B. Star | <image>
Input
The input contains a single integer a (1 ≤ a ≤ 18257).
Output
Print a single integer output (1 ≤ output ≤ 2·109).
Examples
Input
2
Output
13 | ```python
def star(n):
a, b = 1, 12
for i in range(2, n + 1):
a += b
b += 12
return a
print(star(int(input())))
``` |
263_C. Circle of Numbers | One day Vasya came up to the blackboard and wrote out n distinct integers from 1 to n in some order in a circle. Then he drew arcs to join the pairs of integers (a, b) (a ≠ b), that are either each other's immediate neighbors in the circle, or there is number c, such that a and с are immediate neighbors, and b and c ar... | ```python
#!/usr/local/bin/python3
from __future__ import print_function
import sys
DEBUG = '-d' in sys.argv
def debug(*args, **kwargs):
if DEBUG:
print(*args, file=sys.stderr, **kwargs)
return None
def main():
n = int(input())
cnt = [0] * (n + 1)
edge = []
for i in range(0, n ... |
287_C. Lucky Permutation | A permutation p of size n is the sequence p1, p2, ..., pn, consisting of n distinct integers, each of them is from 1 to n (1 ≤ pi ≤ n).
A lucky permutation is such permutation p, that any integer i (1 ≤ i ≤ n) meets this condition ppi = n - i + 1.
You have integer n. Find some lucky permutation p of size n.
Input
T... | ```python
n=int(input())
L=[0]*(n+1)
X=[False]*(n+1)
if(n%4!=0 and n%4!=1):
print(-1)
else:
for i in range(1,n+1):
if(X[i]):
continue
X[i]=True
X[n-i+1]=True
for j in range(i+1,n+1):
if(X[j]):
continue
X[j]=True
... |
312_C. The Closest Pair | Currently Tiny is learning Computational Geometry. When trying to solve a problem called "The Closest Pair Of Points In The Plane", he found that a code which gave a wrong time complexity got Accepted instead of Time Limit Exceeded.
The problem is the follows. Given n points in the plane, find a pair of points between... | ```python
n,k = map(int,input().split())
if n*(n-1) <= k*2:
print('no solution')
else:
for i in range(n):
print(0,i)
``` |
335_A. Banana | Piegirl is buying stickers for a project. Stickers come on sheets, and each sheet of stickers contains exactly n stickers. Each sticker has exactly one character printed on it, so a sheet of stickers can be described by a string of length n. Piegirl wants to create a string s using stickers. She may buy as many sheets ... | ```python
s = input()
n = int(input())
symb_cnt = {}
for c in s:
symb_cnt[c] = symb_cnt[c] + 1 if c in symb_cnt else 1
for cnt in range(1, len(s) + 1):
s1 = ""
for c in symb_cnt:
s1 += c * ((symb_cnt[c] + cnt - 1) // cnt)
if len(s1) <= n:
for i in range(n - len(s1)):
s1 += 'a'
print(cnt)
print(s1)
exi... |
358_A. Dima and Continuous Line | Dima and Seryozha live in an ordinary dormitory room for two. One day Dima had a date with his girl and he asked Seryozha to leave the room. As a compensation, Seryozha made Dima do his homework.
The teacher gave Seryozha the coordinates of n distinct points on the abscissa axis and asked to consecutively connect them... | ```python
n = int(input())
lst = list(map(int,input().split()))
a = list(zip(lst,lst[1:]))
record = []
for x in a:
s,e = min(x[0],x[1]),max(x[0],x[1])
for y in record:
if y[0]<s<y[1]<e or s<y[0]<e<y[1]:
exit(print("yes"))
record.append((s,e))
print("no")
``` |
451_C. Predict Outcome of the Game | There are n games in a football tournament. Three teams are participating in it. Currently k games had already been played.
You are an avid football fan, but recently you missed the whole k games. Fortunately, you remember a guess of your friend for these k games. Your friend did not tell exact number of wins of each... | ```python
from sys import *
t=int(stdin.readline())
for i in range(t):
n,k,d1,d2=(int(z) for z in stdin.readline().split())
vars=((2*d1+d2,2*d2+d1),(2*max(d1,d2)-min(d1,d2),d1+d2))
y=False
for i in vars:
if i[0]<=k and i[0]%3==k%3 and n-k-i[1]>=0 and (n-i[1]-k)%3==0:
print("yes")
... |
474_B. Worms | It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole n ordered piles of worms such that i-th pile contains ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number... | ```python
from bisect import bisect_left
n = int(input())
n1 = input().split()
m = int(input())
m1 = input().split()
lista = []
valor = 0
for e in n1:
valor += int(e)
lista.append(valor)
for e in m1:
print(bisect_left(lista, int(e)) + 1)
``` |
498_A. Crazy Town | Crazy Town is a plane on which there are n infinite line roads. Each road is defined by the equation aix + biy + ci = 0, where ai and bi are not both equal to the zero. The roads divide the plane into connected regions, possibly of infinite space. Let's call each such region a block. We define an intersection as the po... | ```python
x1,y1 = [int(i) for i in input().split()]
x2,y2 = [int(i) for i in input().split()]
n = int(input())
m = 0
for i in range(n):
x,y,c = [int(g) for g in input().split()]
if(x1*x+y1*y+c>0):
l = 1
else:
l = -1
if(l==-1)and(x2*x+y2*y+c>0):
m+=1
elif(l==1)and(x2*x+y2*y+c<... |
521_B. Cubes | Once Vasya and Petya assembled a figure of m cubes, each of them is associated with a number between 0 and m - 1 (inclusive, each number appeared exactly once). Let's consider a coordinate system such that the OX is the ground, and the OY is directed upwards. Each cube is associated with the coordinates of its lower le... | ```python
import heapq
def coor_neighbor(coor, dxs, dys):
x, y = coor
for dx in dxs:
for dy in dys:
yield x + dx, y + dy
def coor_bottoms(coor):
return coor_neighbor(coor, (-1, 0, 1), (-1, ))
def coor_tops(coor):
return coor_neighbor(coor, (-1, 0, 1), (1, ))
def coor_sibs(coor... |
548_D. Mike and Feet | Mike is the president of country What-The-Fatherland. There are n bears living in this country besides Mike. All of them are standing in a line and they are numbered from 1 to n from left to right. i-th bear is exactly ai feet high.
<image>
A group of bears is a non-empty contiguous segment of the line. The size of ... | ```python
from sys import stdin, stdout
def input(): return stdin.readline().strip()
def print(x, end='\n'): stdout.write(str(x) + end)
n, lst = int(input()), list(map(int, input().split()))
nse, pse, stk, ans = [n for i in range(n)], [-1 for i in range(n)], [], [0 for i in range(n+1)]
for i in range(n):
while stk... |
618_A. Slime Combining | Your friend recently gave you some slimes for your birthday. You have n slimes all initially with value 1.
You are going to play a game with these slimes. Initially, you put a single slime by itself in a row. Then, you will add the other n - 1 slimes one by one. When you add a slime, you place it at the right of all a... | ```python
def answer(n):
x=[]
while(n!=0):
temp=n%2
n//=2
x.append(temp)
for i in reversed(range(len(x))):
if x[i]==1:
print(i+1,end=' ')
n=int(input())
answer(n)
``` |
638_C. Road Improvement | In Berland there are n cities and n - 1 bidirectional roads. Each road connects some pair of cities, from any city you can get to any other one using only the given roads.
In each city there is exactly one repair brigade. To repair some road, you need two teams based in the cities connected by the road to work simulta... | ```python
import sys
import threading
from collections import defaultdict
def put():
return map(int, input().split())
def dfs(i, p, m):
cnt = 1
z = 0
for j in tree[i]:
if j==p: continue
if cnt==m: cnt+=1
index = edge_index[(i,j)]
ans[cnt].append(index)
z = max(d... |
666_A. Reberland Linguistics | First-rate specialists graduate from Berland State Institute of Peace and Friendship. You are one of the most talented students in this university. The education is not easy because you need to have fundamental knowledge in different areas, which sometimes are not related to each other.
For example, you should know l... | ```python
from sys import *
setrecursionlimit(200000)
d = {}
t = set()
s = input() + ' '
def gen(l, ll):
if (l, ll) in t: return
t.add((l, ll))
if l > 6:
d[s[l - 2 : l]] = 1
if s[l - 2 : l] != s[l : ll]: gen(l - 2, l)
if l > 7:
d[s[l - 3 : l]] = 1
if s[l - 3 : l] != s[l :... |
712_C. Memory and De-Evolution | Memory is now interested in the de-evolution of objects, specifically triangles. He starts with an equilateral triangle of side length x, and he wishes to perform operations to obtain an equilateral triangle of side length y.
In a single second, he can modify the length of a single side of the current triangle such th... | ```python
x, y = map(int, input().split())
a, b, c = y, y, y
cnt = 0
while True:
if a >= x and b >= x and c >= x:
break
cnt += 1
if cnt % 3 == 0:
a = b+c - 1
elif cnt % 3 == 1:
b = c + a - 1
elif cnt % 3 == 2:
c = b+a - 1
print(cnt)
``` |
733_B. Parade | Very soon there will be a parade of victory over alien invaders in Berland. Unfortunately, all soldiers died in the war and now the army consists of entirely new recruits, many of whom do not even know from which leg they should begin to march. The civilian population also poorly understands from which leg recruits beg... | ```python
n = int(input())
L, R = 0, 0
D = []
for i in range(n):
l, r = map(int, input().split())
L += l
R += r
D.append((l, r))
ans = abs(L - R)
num = 0
for i in range(n):
l, r = D[i]
L1 = L - l + r
R1 = R - r + l
if ans < abs(L1 - R1):
ans = abs(L1 - R1)
num = i + 1
p... |
757_C. Felicity is Coming! | It's that time of the year, Felicity is around the corner and you can see people celebrating all around the Himalayan region. The Himalayan region has n gyms. The i-th gym has gi Pokemon in it. There are m distinct Pokemon types in the Himalayan region numbered from 1 to m. There is a special evolution camp set up in t... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict,Counter
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.sta... |
802_H. Fake News (medium) | Thanks to your help, Heidi is confident that no one can fool her. She has now decided to post some fake news on the HC2 Facebook page. However, she wants to be able to communicate to the HC2 committee that the post is fake, using some secret phrase hidden in the post as a subsequence. To make this method foolproof, she... | ```python
def rek(k):
if k == 1:
return ('a', 'a')
elif k == 2:
return ('aa', 'a')
s, p = rek((k - 1) // 2)
x = chr(ord(p[-1]) + 1)
return (p + x * (2 - k % 2) + s[len(p):] + 2 * x, p + x)
s, p = rek(int(input()))
print(s, p)
``` |
825_D. Suitable Replacement | You are given two strings s and t consisting of small Latin letters, string s can also contain '?' characters.
Suitability of string s is calculated by following metric:
Any two letters can be swapped positions, these operations can be performed arbitrary number of times over any pair of positions. Among all resulti... | ```python
from collections import Counter
import sys
input = sys.stdin.readline
s = list(input().rstrip())
t = input().rstrip()
cnt1 = Counter(s)
cnt2 = Counter(t)
if cnt1['?'] == 0:
print(*s, sep='')
exit()
ok, ng = 0, 10**9
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
hatena = cnt1['?']
for k, ... |
848_B. Rooter's Song | Wherever the destination is, whoever we meet, let's render this song together.
On a Cartesian coordinate plane lies a rectangular stage of size w × h, represented by a rectangle with corners (0, 0), (w, 0), (w, h) and (0, h). It can be seen that no collisions will happen before one enters the stage.
On the sides of t... | ```python
import sys
def main():
n, w, h = map(int, sys.stdin.readline().split())
gv = {}
gh = {}
for i in range(n):
g, p, t = map(int, sys.stdin.readline().split())
c = p - t
t = (g, p, -t, i)
if g == 1:
if c in gv:
gv[c].append(t)
... |
967_C. Stairs and Elevators | In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are l... | ```python
import bisect as bs
import sys
inp = sys.stdin.readlines()
n, m, ladders, elevators, v = [int(x) for x in inp[0].strip().split()]
ladders = [int(x) for x in inp[1].strip().split()]
elevators = [int(x) for x in inp[2].strip().split()]
q = int(inp[3].strip())
qs = []
for i in range(q):
qs.append([int(x) f... |
993_C. Careful Maneuvering | There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a wa... | ```python
n, m = map(int, input().strip().split())
y1 = list(map(int, input().strip().split()))
y2 = list(map(int, input().strip().split()))
y1.sort()
y2.sort()
u1 = list()
u2 = list()
p = 0
while p < n:
q = p
while q < n and y1[q] == y1[p]:
q += 1
u1.append((y1[p], q - p))
p = q
p = 0
while p ... |
p02629 AtCoder Beginner Contest 171 - One Quadrillion and One Dalmatians | 1000000000000001 dogs suddenly appeared under the roof of Roger's house, all of which he decided to keep. The dogs had been numbered 1 through 1000000000000001, but he gave them new names, as follows:
* the dogs numbered 1,2,\cdots,26 were respectively given the names `a`, `b`, ..., `z`;
* the dogs numbered 27,28,29,\... | ```python
n = int(input())
s = ''
while n > 0:
n -= 1
s = chr(ord('a') + n % 26) + s
n //= 26
print(s)
``` |
p02760 AtCoder Beginner Contest 157 - Bingo | We have a bingo card with a 3\times3 grid. The square at the i-th row from the top and the j-th column from the left contains the number A_{i, j}.
The MC will choose N numbers, b_1, b_2, \cdots, b_N. If our bingo sheet contains some of those numbers, we will mark them on our sheet.
Determine whether we will have a bi... | ```python
A=[]
for _ in range(3):
A+=list(map(int, input().split()))
N=int(input())
b=[]
for _ in range(N):
b.append(int(input()))
BINGO=[{0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}]
hole=set()
for num in b:
for i in range(9):
if num==A[i]:
hole.add(i)
for ... |
p03030 AtCoder Beginner Contest 128 - Guidebook | You have decided to write a book introducing good restaurants. There are N restaurants that you want to introduce: Restaurant 1, Restaurant 2, ..., Restaurant N. Restaurant i is in city S_i, and your assessment score of that restaurant on a 100-point scale is P_i. No two restaurants have the same score.
You want to in... | ```python
n = int(input())
SP = []
for i in range(n):
s,p = input().split()
SP.append((s,-int(p),i+1))
SP.sort()
for s,p,i in SP:
print(i)
``` |
p03171 Educational DP Contest - Deque | Taro and Jiro will play the following game against each other.
Initially, they are given a sequence a = (a_1, a_2, \ldots, a_N). Until a becomes empty, the two players perform the following operation alternately, starting from Taro:
* Remove the element at the beginning or the end of a. The player earns x points, whe... | ```python
import sys
input = sys.stdin.buffer.readline
def main():
N = int(input())
a = list(map(int,input().split()))
dp = [[-1 for _ in range(N)] for _ in range(N)]
for i in range(N):
dp[i][i] = a[i]
for i in range(N-1,-1,-1):
for j in range(i,N):
if dp[i][j] != -... |
p03317 AtCoder Beginner Contest 101 - Minimization | There is a sequence of length N: A_1, A_2, ..., A_N. Initially, this sequence is a permutation of 1, 2, ..., N.
On this sequence, Snuke can perform the following operation:
* Choose K consecutive elements in the sequence. Then, replace the value of each chosen element with the minimum value among the chosen elements.... | ```python
import math
n, k = map(int, input().split())
print(math.ceil((n-k) / (k - 1) + 1))
``` |
p03473 AtCoder Beginner Contest 084 - New Year | 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... | ```python
M=int(input())
time=24-M
print(time+24)
``` |
p03636 AtCoder Beginner Contest 069 - i18n | The word `internationalization` is sometimes abbreviated to `i18n`. This comes from the fact that there are 18 letters between the first `i` and the last `n`.
You are given a string s of length at least 3 consisting of lowercase English letters. Abbreviate s in the same way.
Constraints
* 3 ≤ |s| ≤ 100 (|s| denotes ... | ```python
S = input()
t = str(len(S)-2)
print(S[0]+t+S[-1])
``` |
p03962 AtCoder Beginner Contest 046 - AtCoDeer and Paint Cans | AtCoDeer the deer recently bought three paint cans. The color of the one he bought two days ago is a, the color of the one he bought yesterday is b, and the color of the one he bought today is c. Here, the color of each paint can is represented by an integer between 1 and 100, inclusive.
Since he is forgetful, he migh... | ```python
print(len(set(input().rstrip().split())))
``` |
p00053 Sum of Prime Numbers | Let p (i) be the i-th prime number from the smallest. For example, 7 is the fourth prime number from the smallest, 2, 3, 5, 7, so p (4) = 7.
Given n, the sum of p (i) from i = 1 to n s
s = p (1) + p (2) + .... + p (n)
Create a program that outputs. For example, when n = 9, s = 2 + 3 + 5 + 7 + 11 + 13 + 17 + 19 + 23 ... | ```python
num = 200000
L = [True] * (num+1)
L[0] = False
L[1] = False
for i in range( 2, int(num**0.5)+ 2 ):
if not L[i]:
continue
for j in range(i*2, num+1, i):
L[j] = False
p = [ x for x in range(num+1) if L[x] ]
while True:
n = int(input())
if n == 0:
break
print(sum(p[0... |
p00183 Black-and-White | Consider a tic-tac-toe on a 3x3 board. Tic-tac-toe is a two-player battle game. Decide the first attack and the second attack, one hits Kuroishi and one hits Shiraishi. The winner is the person who puts stones one by one on the board alternately and arranges three of his own stones first in either the vertical, horizon... | ```python
def f1(c, l):
for i in range(3):
if c*3 == l[i]:
return 1
return 0
def f2(c, l):
for i in range(0, 7, 3):
s = set(h[i:i+3])
if c in s and len(s) == 1:
return 1
return 0
def f3(c, l):
if c*3 == l[0]+l[4]+l[8]:
return 1
if c*3 == ... |
p00697 Jigsaw Puzzles for Computers | Ordinary Jigsaw puzzles are solved with visual hints; players solve a puzzle with the picture which the puzzle shows on finish, and the diverse patterns of pieces. Such Jigsaw puzzles may be suitable for human players, because they require abilities of pattern recognition and imagination.
On the other hand, "Jigsaw pu... | ```python
p_ch = [True] * 9
rot = ((0, 1, 2, 3), (1, 2, 3, 0), (2, 3, 0, 1), (3, 0, 1, 2))
adj = ['c'] * 13
# record indices of right and botoom adjacent edge label. 12 is invalid.
rec_adj = [[0, 2], [1, 3], [12, 4], [5, 7], [6, 8], [12, 9], [10, 12],
[11, 12], [12, 12]]
# refernce indices to top and left ... |
p00838 Colored Cubes | There are several colored cubes. All of them are of the same size but they may be colored differently. Each face of these cubes has a single color. Colors of distinct faces of a cube may or may not be the same.
Two cubes are said to be identically colored if some suitable rotations of one of the cubes give identical l... | ```python
import copy
# 回転方法の全列挙
def turn(box):
turnlist = []
for j in range(4):
for i in range(4):
turnlist.append(box)
box = [box[0], box[3], box[1], box[4], box[2], box[5]]
box = [box[3], box[1], box[0], box[5], box[4], box[2]]
box = [box[1], box[5], box[2], box[3... |
p00970 Emergency Evacuation | Emergency Evacuation
The Japanese government plans to increase the number of inbound tourists to forty million in the year 2020, and sixty million in 2030. Not only increasing touristic appeal but also developing tourism infrastructure further is indispensable to accomplish such numbers.
One possible enhancement on t... | ```python
#!/usr/bin/python3
import array
from fractions import Fraction
import functools
import itertools
import math
import os
import sys
def main():
R, S, P = read_ints()
A = []
for _ in range(P):
i, j = read_ints()
i -= 1
j -= 1
A.append((i, j))
print(solve(R, S, ... |
p01102 Almost Identical Programs | Almost Identical Programs
The programming contest named Concours de Programmation Comtemporaine Interuniversitaire (CPCI) has a judging system similar to that of ICPC; contestants have to submit correct outputs for two different inputs to be accepted as a correct solution. Each of the submissions should include the pr... | ```python
def main(s):
if s == ".":
return False
ss = input()
diffc = 0
sl = s.split("\"")
ssl = ss.split("\"")
if len(sl) != len(ssl):
print("DIFFERENT")
return True
for i in range(len(sl)):
if i % 2 == 0:
if sl[i] != ssl[i]:
print("DIFFERENT")
return True
else:
if sl[i] != ssl[i]:
d... |
p01401 The Legendary Sword | Problem D: Legendary Sword
* This problem contains a lot of two ingredients in the kitchen. Please be careful about heartburn.
The Demon King, who has finally revived, is about to invade the human world to wrap the world in darkness again.
The Demon King decided to destroy the legendary sword first before launching ... | ```python
while True:
w, h = map(int, input().split())
if w == 0:break
mp = [input().split() for _ in range(h)]
points = {}
for y in range(h):
for x in range(w):
if mp[y][x] == "S":
sx, sy = x, y
points[0] = [(x, y)]
elif mp[y][x] == "G":
gx, gy = x, y
elif mp[... |
p01555 FizzBuzz | FizzBuzz is a game in which integers of 1 or more are spoken in order according to the following rules.
* "Fizz" when divisible by 3
* "Buzz" when divisible by 5
* "FizzBuzz" when divisible by both 3 and 5
* At other times, that number
An example of the progress of the game is shown below.
1, 2, Fizz, 4, Buzz,... | ```python
def calc_start(mid):
cnt = -1
i = 1
while 10 ** i < mid:
cnt += i * (10 ** i - 10 ** (i - 1))
fif = (10 ** i - 1) // 15 - (10 ** (i - 1) - 1) // 15
three = (10 ** i - 1) // 3 - (10 ** (i - 1) - 1) // 3
five = (10 ** i - 1) // 5 - (10 ** (i - 1) - 1) // 5
cnt... |
p01710 Website Tour | Problem Statement
You want to compete in ICPC (Internet Contest of Point Collection). In this contest, we move around in $N$ websites, numbered $1$ through $N$, within a time limit and collect points as many as possible. We can start and end on any website.
There are $M$ links between the websites, and we can move be... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def scc(N, G, RG):
order = []
used = [0]*N
group = [None]*N
def dfs(s):
used[s] = 1
for t in G[s]:
if not used[t]:
dfs(t)
order.append(s)
def... |
p01855 Checkered Pattern | Problem statement
There are rectangles with vertical and horizontal lengths of h and w, and square squares with a side length of 1 are spread inside. If the upper left cell is (0,0) and the cell to the right of j below (0,0) is represented as (i, j), (i, j) is i + j. If is even, it is painted red, and if it is odd, it... | ```python
def gcd(a,b):
if a == 0:
return b
else:
return gcd(b%a,a)
t = int(input())
while t:
t -= 1
a,b = map(int, input().split())
c = gcd(a,b)
a = a//c
b = b//c
if a == b:
ans1 = 1
ans2 = 0
elif a % 2 == 0 or b % 2 == 0:
ans1 = 1
ans... |
p01990 Pivots | B: Pivots
problem
Given a permutation of length N, a_1, a_2, ..., a_N, which is a permutation of integers from 1 to N. Also, Q queries are given in order for this permutation. In the i-th query, you have to do the following:
* The value q_i (1 \ leq q_i \ leq N) is given. In the permutation \\ {a_1, a_2, ..., a_N \\... | ```python
# -*- coding: utf-8 -*-
def inpl(): return list(map(int, input().split()))
N, _ = inpl()
A = inpl()
if N == 1:
print(*A)
exit()
L = [0]*(N+1)
R = [0]*(N+1)
for i in range(N-1):
R[A[i]] = A[i+1]
L[A[i+1]] = A[i]
lm = A[0]
rm = A[-1]
for q in inpl():
if q == rm:
l = L[q]
... |
p02277 Quick Sort | Let's arrange a deck of cards. Your task is to sort totally n cards. A card consists of a part of a suit (S, H, C or D) and an number. Write a program which sorts such cards based on the following pseudocode:
Partition(A, p, r)
1 x = A[r]
2 i = p-1
3 for j = p to r-1
4 do if A[j] <= x
5 then i = i+1
6 ... | ```python
def partition(A, p, r):
x = A[r][1]
i = p - 1
for j in range(p, r):
if A[j][1] <= x:
i += 1
A[i], A[j] = A[j], A[i]
A[i + 1], A[r] = A[r], A[i + 1]
return i + 1
def quick_sort(A, p, r):
if p < r:
q = partition(A, p, r)
# 左半分
quic... |
p02424 Bit Operation II | Given two non-negative decimal integers $a$ and $b$, calculate their AND (logical conjunction), OR (logical disjunction) and XOR (exclusive disjunction) and print them in binary representation of 32 bits.
Constraints
* $0 \leq a, b \leq 2^{32} - 1$
Input
The input is given in the following format.
$a \; b$
Outp... | ```python
n,m=map(int,input().split())
print("{:032b}".format(n&m))
print("{:032b}".format(n|m))
print("{:032b}".format(n^m))
``` |
1008_C. Reorder the Array | You are given an array of integers. Vasya can permute (change order) its integers. He wants to do it so that as many as possible integers will become on a place where a smaller integer used to stand. Help Vasya find the maximal number of such integers.
For instance, if we are given an array [10, 20, 30, 40], we can pe... | ```python
n = int(input().strip())
a = list(map(int, input().strip().split()))
a.sort()
cnt = 0
que = []
l = 0
for i in a:
if l == 0:
que.append(i)
l += 1
else:
if i != que[0]:
que.append(i)
del que[0]
cnt += 1
else:
que.append(i)
l += 1
print(cnt)
``` |
1031_A. Golden Plate | You have a plate and you want to add some gilding to it. The plate is a rectangle that we split into w× h cells. There should be k gilded rings, the first one should go along the edge of the plate, the second one — 2 cells away from the edge and so on. Each ring has a width of 1 cell. Formally, the i-th of these rings ... | ```python
w, h, k = input().split()
w = int(w)
h = int(h)
k = int(k)
s = 0
for i in range(k):
k = 2*w + 2*h - 4 - 16*i
s = s + k
print(s)
``` |
1054_A. Elevator or Stairs? | Masha lives in a multi-storey building, where floors are numbered with positive integers. Two floors are called adjacent if their numbers differ by one. Masha decided to visit Egor. Masha lives on the floor x, Egor on the floor y (not on the same floor with Masha).
The house has a staircase and an elevator. If Masha u... | ```python
x,y,z,tuno,tdos,ttres=map(int,input().split())
var1=(x-y)
stair=abs(var1)*tuno
var2=(x-z)
eleva=(3*ttres)+((abs(var2))*tdos)+((abs(var1))*tdos)
if stair >= eleva:
print("YES")
else:
print("NO")
``` |
1076_A. Minimizing the String | You are given a string s consisting of n lowercase Latin letters.
You have to remove at most one (i.e. zero or one) character of this string in such a way that the string you obtain will be lexicographically smallest among all strings that can be obtained using this operation.
String s = s_1 s_2 ... s_n is lexicograp... | ```python
import sys, threading
sys.setrecursionlimit(10 ** 6)
scan = lambda: map(int, input().split())
n = int(input())
string = input()
ans = string
for i in range(n-1):
if string[i] > string[i+1]:
print(string[0:i]+string[i+1:n])
exit(0)
print(string[0:n-1])
``` |
1097_A. Gennady and a Card Game | Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau".
To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds — D, Clubs — C, Spades — S, or ... | ```python
n = str(input())
alist = input().split(' ')
for i in alist:
if i[0] == n[0]:
print('YES')
exit(0)
elif i[-1] == n[-1]:
print('YES')
exit(0)
print('NO')
``` |
1118_B. Tanya and Candies | Tanya has n candies numbered from 1 to n. The i-th candy has the weight a_i.
She plans to eat exactly n-1 candies and give the remaining candy to her dad. Tanya eats candies in order of increasing their numbers, exactly one candy per day.
Your task is to find the number of such candies i (let's call these candies goo... | ```python
N , vals= int(input()),list(map(int, input().split()))
odds, evens = 0,0
for i in range(N):
if i % 2 == 0:
odds += vals[i]
else:
evens += vals[i]
odds, evens, num_good = evens, odds-vals[0],0
if odds == evens:
num_good+=1
for i in range(1,N):
if i % 2 == 1:
odds = odds - vals[i] + vals[i-1... |
1144_E. Median String | You are given two strings s and t, both consisting of exactly k lowercase Latin letters, s is lexicographically less than t.
Let's consider list of all strings consisting of exactly k lowercase Latin letters, lexicographically not less than s and not greater than t (including s and t) in lexicographical order. For exa... | ```python
def divide_2(a, m):
r = 0
q = []
for x in a:
cur = r * m + x
q.append(cur // 2)
r = cur % 2
return q
def add(s, t, m):
r = 0
a = []
for x, y in zip(s[::-1], t[::-1]):
cur = r+x+y
a.append(cur % m )
r = cur // m
... |
1165_D. Almost All Divisors | We guessed some integer number x. You are given a list of almost all its divisors. Almost all means that there are all divisors except 1 and x in the list.
Your task is to find the minimum possible integer x that can be the guessed number, or say that the input data is contradictory and it is impossible to find such n... | ```python
def divisors(num):
"""
約数全列挙
"""
divisors = []
for i in range(1, int(num ** 0.5) + 1):
if num % i == 0:
divisors.append(i)
if i != num // i:
divisors.append(num // i)
return divisors
T = int(input())
for t in range(T):
N = int(inpu... |
1202_F. You Are Given Some Letters... | You are given a uppercase Latin letters 'A' and b letters 'B'.
The period of the string is the smallest such positive integer k that s_i = s_{i~mod~k} (0-indexed) for each i. Note that this implies that k won't always divide a+b = |s|.
For example, the period of string "ABAABAA" is 3, the period of "AAAA" is 1, and t... | ```python
import math
a,b= map(int,input().split())
n=a+b
ans,l=0,1
while l<=n:
g= n//l
if a<g or b<g:
l= (n//g) +1
continue
r= n//g
a_low = (a+g)//(g+1)
a_high = a//g
b_low=(b+g)//(g+1)
b_high = b//g
if (a_low <= a_high and b_low <= b_high):
ans += max(0,min(r,a_... |
121_B. Lucky Transformation | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of n digits without leading zeroes. He represented it as an array of d... | ```python
import sys
input=sys.stdin.readline
from math import *
n,m=map(int,input().split())
s=list(input().rstrip())
for i in range(n-1):
if m==0:
break
if i>0:
if s[i-1]=='4' and s[i]=='4' and s[i+1]=='7' and i%2==1:
if m%2==1:
s[i]='7'
break
if s... |
1244_F. Chips | There are n chips arranged in a circle, numbered from 1 to n.
Initially each chip has black or white color. Then k iterations occur. During each iteration the chips change their colors according to the following rules. For each chip i, three chips are considered: chip i itself and two its neighbours. If the number of... | ```python
import sys
input = sys.stdin.readline
n,k=map(int,input().split())
S=input().strip()
ANS=["?"]*n
for i in range(n-1):
if S[i]=="B":
if S[i-1]=="B" or S[i+1]=="B":
ANS[i]="B"
else:
if S[i-1]=="W" or S[i+1]=="W":
ANS[i]="W"
if S[n-1]=="B":
if S[n-2]=="B" ... |
1305_A. Kuroni and the Gifts | Kuroni has n daughters. As gifts for them, he bought n necklaces and n bracelets:
* the i-th necklace has a brightness a_i, where all the a_i are pairwise distinct (i.e. all a_i are different),
* the i-th bracelet has a brightness b_i, where all the b_i are pairwise distinct (i.e. all b_i are different).
Kuro... | ```python
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
a=sorted(a)
b=sorted(b)
print(*a)
print(*b)
``` |
1329_C. Drazil Likes Heap | Drazil likes heap very much. So he created a problem with heap:
There is a max heap with a height h implemented on the array. The details of this heap are the following:
This heap contains exactly 2^h - 1 distinct positive non-zero integers. All integers are distinct. These numbers are stored in the array a indexed f... | ```python
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
T = int(input())
for _ in range(T):
H, G = map(int, input().split())
A = [0] + list(map(int, input().split()))
N = len(A)
target_N = 2**G - 1
target_ans_len = 2**H - 2**G
Ans = []
Roots = [True] * (N+1)
i... |
1349_C. Orac and Game of Life | Please notice the unusual memory limit of this problem.
Orac likes games. Recently he came up with the new game, "Game of Life".
You should play this game on a black and white grid with n rows and m columns. Each cell is either black or white.
For each iteration of the game (the initial iteration is 0), the color of... | ```python
import sys
input = sys.stdin.readline
n,m,t=map(int,input().split())
MAP=[input().strip() for i in range(n)]
COUNT=[[-1]*m for i in range(n)]
from collections import deque
Q=deque()
for i in range(n):
for j in range(m):
for z,w in [[i+1,j],[i-1,j],[i,j+1],[i,j-1]]:
if 0<=z<n and 0<=... |
136_A. Presents | Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.
If t... | ```python
n = int(input())
arr = list(map(int, input().split()))
brr = arr[:]
t = 0
for i in range(n):
t = arr[i] - 1
brr[t] = i + 1
print(*brr)
``` |
1392_A. Omkar and Password | Lord Omkar has permitted you to enter the Holy Church of Omkar! To test your worthiness, Omkar gives you a password which you must interpret!
A password is an array a of n positive integers. You apply the following operation to the array: pick any two adjacent numbers that are not equal to each other and replace them ... | ```python
for _ in range(int(input())):
n = int(input())
s = list(map(int,input().split()))
#a,b = map(int,input().split())
k = set(s)
if len(list(k)) == 1:
print(n)
else:
print(1)
``` |
1416_C. XOR Inverse | You are given an array a consisting of n non-negative integers. You have to choose a non-negative integer x and form a new array b of size n according to the following rule: for all i from 1 to n, b_i = a_i ⊕ x (⊕ denotes the operation [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR)).
An inversion i... | ```python
n=int(input())
l=input().split()
li=[int(i) for i in l]
xori=0
ans=0
mul=1
for i in range(32):
hashi1=dict()
hashi0=dict()
inv1=0
inv2=0
for j in li:
if(j//2 in hashi1 and j%2==0):
inv1+=hashi1[j//2]
if(j//2 in hashi0 and j%2==1):
inv2+=hashi0[j//2]
... |
1433_B. Yet Another Bookshelf | There is a bookshelf which can fit n books. The i-th position of bookshelf is a_i = 1 if there is a book on this position and a_i = 0 otherwise. It is guaranteed that there is at least one book on the bookshelf.
In one move, you can choose some contiguous segment [l; r] consisting of books (i.e. for each i from l to r... | ```python
import sys
try:
import os
f = open('input.txt', 'r')
sys.stdin = f
except FileNotFoundError:
None
from math import sqrt, ceil
input=lambda: sys.stdin.readline().strip()
o=int(input())
for _ in range(o):
n=int(input())
A=list(map(int,input().split()))
dou=-1 ;las=-1
for i in ra... |
1458_A. Row GCD | You are given two positive integer sequences a_1, …, a_n and b_1, …, b_m. For each j = 1, …, m find the greatest common divisor of a_1 + b_j, …, a_n + b_j.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 2 ⋅ 10^5).
The second line contains n integers a_1, …, a_n (1 ≤ a_i ≤ 10^{18}).
The third line co... | ```python
from math import gcd
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
for i in b:
ans = a[0]+i
if(len(a)>=2):
ans = gcd(a[0]+i,a[1]+i)
if(len(a)>2):
ans = gcd(ans, a[(len(a)-1)//4]+i)
ans = gcd(ans, a[(len(a)-1)//2]+... |
1481_A. Space Navigation | You were dreaming that you are traveling to a planet named Planetforces on your personal spaceship. Unfortunately, its piloting system was corrupted and now you need to fix it in order to reach Planetforces.
<image>
Space can be represented as the XY plane. You are starting at point (0, 0), and Planetforces is locate... | ```python
# https://codeforces.com/problemset/problem/1481/A
for _ in range(int(input())):
x, y = map(int, input().split())
string = input()
positiveX, positiveY, negativeX, negativeY = 0, 0, 0, 0
for i in string:
if i == "R":
positiveX += 1
elif i == "L":
negati... |
1508_B. Almost Sorted | Seiji Maki doesn't only like to observe relationships being unfolded, he also likes to observe sequences of numbers, especially permutations. Today, he has his eyes on almost sorted permutations.
A permutation a_1, a_2, ..., a_n of 1, 2, ..., n is said to be almost sorted if the condition a_{i + 1} ≥ a_i - 1 holds for... | ```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
for _ in range(int(input())):
n,k = map(int,input().split())
if n < 100 and 1 << (n - 1) < k:
print(-1)
continue
k -= 1
ans = [0] * (n - 1)
cnt = 0
... |
1534_C. Little Alawn's Puzzle | When he's not training for IOI, Little Alawn enjoys playing with puzzles of various types to stimulate his brain. Today, he's playing with a puzzle that consists of a 2 × n grid where each row is a permutation of the numbers 1,2,3,…,n.
The goal of Little Alawn's puzzle is to make sure no numbers on the same column or ... | ```python
t=(int(input()))
while t:
t-=1
n = int(input())
x = list(map(int, input().split()))
y = list(map(int, input().split()))
ans,vi,graph= 0,[0]*(n+1),{}
for i in range(n):
graph[x[i]]=y[i]
for j in graph.keys():
if vi[j]:
continue
else:
ans+=1
te=j... |
181_A. Series of Crimes | The Berland capital is shaken with three bold crimes committed by the Pihsters, a notorious criminal gang.
The Berland capital's map is represented by an n × m rectangular table. Each cell of the table on the map represents some districts of the capital.
The capital's main detective Polycarpus took a map and marked ... | ```python
a,b=map(int,input().split());c,d,e,g=0,0,0,0
for i in range(a):
k=input().replace(" ","")
if k.count("*")==2:c=k.find("*");k=k[::-1];d=b-1-k.find("*")
if k.count("*")==1:e=k.find("*");g=i
if e==c:print(g+1,d+1)
else :print(g+1,c+1)
``` |
229_B. Planets | Goa'uld Apophis captured Jack O'Neill's team again! Jack himself was able to escape, but by that time Apophis's ship had already jumped to hyperspace. But Jack knows on what planet will Apophis land. In order to save his friends, Jack must repeatedly go through stargates to get to this planet.
Overall the galaxy has n... | ```python
from heapq import *
n, m = map(int, input().split())
l = []
from copy import *
from bisect import *
from math import *
from sys import *
for _ in range(0, n + 2):
l.append([])
for i in range(0, m):
a, b, c = map(int, stdin.readline().split())
l[a].append((c, b))
l[b].append((c, a))
dist = [1... |
278_A. Circle Line | The circle line of the Berland subway has n stations. We know the distances between all pairs of neighboring stations:
* d1 is the distance between the 1-st and the 2-nd station;
* d2 is the distance between the 2-nd and the 3-rd station;
...
* dn - 1 is the distance between the n - 1-th and the n-th station;
... | ```python
n = int(input())
a = list(map(int, input().split()))
s, t = sorted(map(int, input().split()))
print(min(sum(a[s-1:t-1]), sum(a[:s-1])+sum(a[t-1:])))
``` |
2_C. Commentator problem | The Olympic Games in Bercouver are in full swing now. Here everyone has their own objectives: sportsmen compete for medals, and sport commentators compete for more convenient positions to give a running commentary. Today the main sport events take place at three round stadiums, and the commentator's objective is to cho... | ```python
import math
x1, y1, r1 = [int(_) for _ in input().split()]
x2, y2, r2 = [int(_) for _ in input().split()]
x3, y3, r3 = [int(_) for _ in input().split()]
def get_line(p1, p2):
x1, y1 = p1
x2, y2 = p2
if x1 * y2 == x2 * y1:
c = 0
a = 1
if y1 != 0:
b = -x1 / y1
... |
325_C. Monsters and Diamonds | Piegirl has found a monster and a book about monsters and pies. When she is reading the book, she found out that there are n types of monsters, each with an ID between 1 and n. If you feed a pie to a monster, the monster will split into some number of monsters (possibly zero), and at least one colorful diamond. Monster... | ```python
import sys, heapq
_BLANCO, _GRIS, _NEGRO = 0, 1, 2
_OO = int(1e18)
class Regla:
def __init__(self, id, diamantes, deMonstruo, monstruos):
self.id = id
self.diamantes = diamantes
self.deMonstruo = deMonstruo
self.monstruos = monstruos
def clonar(self):
return... |
371_E. Subway Innovation | Berland is going through tough times — the dirt price has dropped and that is a blow to the country's economy. Everybody knows that Berland is the top world dirt exporter!
The President of Berland was forced to leave only k of the currently existing n subway stations.
The subway stations are located on a straight lin... | ```python
from sys import stdin
n = int(stdin.readline())
a = [int(x) for x in stdin.readline().split()]
a = sorted([(a[x],str(x+1)) for x in range(n)])
k = int(stdin.readline())
sums = [0]
for x in a:
sums.append(sums[-1]+x[0])
total = 0
s = 0
for x in range(k):
total += a[x][0]*x-s
s += a[x][0]
low =... |
393_B. Three matrices | Chubby Yang is studying linear equations right now. He came up with a nice problem. In the problem you are given an n × n matrix W, consisting of integers, and you should find two n × n matrices A and B, all the following conditions must hold:
* Aij = Aji, for all i, j (1 ≤ i, j ≤ n);
* Bij = - Bji, for all i, j... | ```python
def transpose(m, d):
new = []
for i in range(d):
new.append([m[j][i] for j in range(d)])
return new
def sum(a,b, dim):
new = []
for i in range(dim):
new.append([(a[i][j]+b[i][j])/2 for j in range(dim)])
return new
def diff(a,b, dim):
new = []
for i in rang... |
416_C. Booking System | Innovation technologies are on a victorious march around the planet. They integrate into all spheres of human activity!
A restaurant called "Dijkstra's Place" has started thinking about optimizing the booking system.
There are n booking requests received by now. Each request is characterized by two numbers: ci and p... | ```python
import sys
input = sys.stdin.readline
read_tuple = lambda _type: map(_type, input().split(' '))
def solve():
# input
n = int(input())
c_p = []
for i in range(n):
c_i, p_i = read_tuple(int)
c_p.append((c_i, p_i, i + 1))
k = int(input())
r = [(r_i, i + 1) for i, r_i in ... |
443_A. Anton and Letters | Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | ```python
ls=list(input())
d=list(dict.fromkeys(ls))
if(len(d)==2):
print(0)
elif(len(d)==3):
print(1)
else:
print(len(d)-4)
``` |
465_B. Inbox (100500) | Over time, Alexey's mail box got littered with too many letters. Some of them are read, while others are unread.
Alexey's mail program can either show a list of all letters or show the content of a single letter. As soon as the program shows the content of an unread letter, it becomes read letter (if the program shows... | ```python
n=int(input())
z=list(map(int,input().split()))
##y=[]
##for i in z :
## y.append(i)
##y.reverse()
##kevin=y.index(1)
count=0
for i in range(n) :
if z[i]==1 :
count+=1
if i+1!=n :
if z[i+1]==0 :
count+=1
else :
counti=1
... |
489_A. SwapSort | In this problem your goal is to sort an array consisting of n integers in at most n swaps. For the given array find the sequence of swaps that makes the array sorted in the non-descending order. Swaps are performed consecutively, one after another.
Note that in this problem you do not have to minimize the number of sw... | ```python
n = int(input())
arr = list(map(int,input().split()))
ans = []
for i in range(n):
k = i
for j in range(i+1,n):
if arr[j]<arr[k]:
k=j
if k!=i:
arr[k],arr[i]=arr[i],arr[k]
ans.append([i,k])
print(len(ans))
if len(ans)>0:
for i in ans:
print(*i)
``` |
538_A. Cutting Banner | A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ... | ```python
inp=input()
fl=False
for i in range(len(inp)):
for j in range(i,len(inp)+1):
if inp[:i]+inp[j:]=='CODEFORCES':
fl=True
if fl:
print('Yes')
else:
print('No')
``` |
566_B. Replicating Processes | A Large Software Company develops its own social network. Analysts have found that during the holidays, major sporting events and other significant events users begin to enter the network more frequently, resulting in great load increase on the infrastructure.
As part of this task, we assume that the social network is... | ```python
from collections import deque
import random
class CodeforcesTask566BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.rules = []
def read_input(self):
self.n = int(input())
self.rules = [[int(x) for x in input().split(" ")] + [y + 1] for y in ran... |
609_E. Minimum spanning tree for each edge | Connected undirected weighted graph without self-loops and multiple edges is given. Graph contains n vertices and m edges.
For each edge (u, v) find the minimal possible weight of the spanning tree that contains the edge (u, v).
The weight of the spanning tree is the sum of weights of all edges included in spanning t... | ```python
from sys import stdin, stdout
n, m = map(int, stdin.readline().split())
d = []
ev = [set() for _ in range(n + 1)]
ans = [0] * m
for i in range(m):
u, v, w = map(int, stdin.readline().split())
d.append((w, u, v))
ev[u].add(i)
ev[v].add(i)
ans[i] = w
d.sort()
par = [i for i in range(n + 1)... |
630_D. Hexagons! | After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cel... | ```python
n = int(input())
n += 1
print(1 + 6 * n * (n-1) // 2)
``` |
658_A. Bear and Reverse Radewoosh | Limak and Radewoosh are going to compete against each other in the upcoming algorithmic contest. They are equally skilled but they won't solve problems in the same order.
There will be n problems. The i-th problem has initial score pi and it takes exactly ti minutes to solve it. Problems are sorted by difficulty — it'... | ```python
n,c = map(int,input().split())
p=input().split()
t=input().split()
sl=0
sr=0
ti=0
for i in range(n):
ti+=int(t[i])
if int(p[i])-c*ti>=0:
sl+=int(p[i])-c*ti
ti=0
for i in range(n):
ti+=int(t[n-i-1])
if int(p[n-i-1])-c*ti>=0:
sr+=int(p[n-i-1])-c*ti
if sl == sr:
print('Tie')
e... |
680_C. Bear and Prime 100 | This is an interactive problem. In the output section below you will see the information about flushing the output.
Bear Limak thinks of some hidden number — an integer from interval [2, 100]. Your task is to say if the hidden number is prime or composite.
Integer x > 1 is called prime if it has exactly two distinct ... | ```python
# from __future__ import division, print_function
import sys
import os
from io import BytesIO, IOBase
# def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
# n = int(os.read(0,100))
# if(n==1):
# os.write(1,b'! 1')
# sys.stdout.flush()
# else:
# per = [0]*n
# # print('?... |
703_B. Mishka and trip | Little Mishka is a great traveller and she visited many countries. After thinking about where to travel this time, she chose XXX — beautiful, but little-known northern country.
Here are some interesting facts about XXX:
1. XXX consists of n cities, k of whose (just imagine!) are capital cities.
2. All of cities ... | ```python
from collections import *
import os, sys
from io import BytesIO, IOBase
def main():
n, k = rints()
a, b = rints(), set(rints())
su, ans, su2 = sum(a), 0, 0
for i in b:
ans += a[i - 1] * (su - a[i - 1])
su2 += a[i - 1]
for i in range(n):
if i + 1 not in b:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.