name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1358_C. Celex Update | During the quarantine, Sicromoft has more free time to create the new functions in "Celex-2021". The developers made a new function GAZ-GIZ, which infinitely fills an infinite table to the right and down from the upper left corner as follows:
<image> The cell with coordinates (x, y) is at the intersection of x-th row ... | ```python
t = int(input())
for _ in range(t):
x1, y1, x2, y2 = map(int, input().split())
print((x2-x1)*(y2-y1)+1)
``` |
1399_D. Binary String To Subsequences | You are given a binary string s consisting of n zeros and ones.
Your task is to divide the given string into the minimum number of subsequences in such a way that each character of the string belongs to exactly one subsequence and each subsequence looks like "010101 ..." or "101010 ..." (i.e. the subsequence should no... | ```python
t=int(input())
for _ in range(t):
n=int(input())
s=str(input())
arr=[]
for i in range(n):
arr.append(int(s[i]))
ones=[]
zeros=[]
vals=[]
k=0
for i in range(n):
p=arr[i]
if(p==0):
if(ones==[]):
zeros.append(k+1)
... |
1492_A. Three swimmers | Three swimmers decided to organize a party in the swimming pool! At noon, they started to swim from the left side of the pool.
It takes the first swimmer exactly a minutes to swim across the entire pool and come back, exactly b minutes for the second swimmer and c minutes for the third. Hence, the first swimmer will b... | ```python
t=int(input())
for i in range(t):
p,a,b,c=map(int,input().split())
if(p%a==0 or p%b==0 or p%c==0):
print(0)
else:
a1=a-p%a
b1=b-p%b
c1=c-p%c
print(min(a1,b1,c1))
``` |
1515_B. Phoenix and Puzzle | Phoenix is playing with a new puzzle, which consists of n identical puzzle pieces. Each puzzle piece is a right isosceles triangle as shown below.
<image> A puzzle piece
The goal of the puzzle is to create a square using the n pieces. He is allowed to rotate and move the pieces around, but none of them can overlap an... | ```python
import math
def issqr(x):
root = int(math.sqrt(x))
return root*root == x
for i in range(int(input())):
n = int(input())
print("YES" if (n % 4 == 0 and issqr(n//4)) or (n % 2 == 0 and issqr(n//2)) else "NO")
``` |
1542_A. Odd Set | You are given a multiset (i. e. a set that can contain multiple equal integers) containing 2n integers. Determine if you can split it into exactly n pairs (i. e. each element should be in exactly one pair) so that the sum of the two elements in each pair is odd (i. e. when divided by 2, the remainder is 1).
Input
The... | ```python
t=int(input())
for _ in range(t):
n=int(input())
l=list(map(int,input().split()))
x=[]
y=[]
for i in l:
if i%2==0:
x.append(i)
else:
y.append(i)
if len(x)==len(y):
print("YES")
else:
print("NO")
``` |
16_A. Flag | According to a new ISO standard, a flag of every country should have a chequered field n × m, each square should be of one of 10 colours, and the flag should be «striped»: each horizontal row of the flag should contain squares of the same colour, and the colours of adjacent horizontal rows should be different. Berland'... | ```python
#--------------------#
#INCLUDE <HajLorenzo>
#INCLUDE <MUSIC.H>
#Mitchell Broom - Ascension
#--------------------#
_=list(map(int,input().split()))
__=True
____="WTF"
for _i_ in range(_[0]):
___=input()
if((___.count(___[0])!=_[1]) or (___[0]==____)):__=False
____=___[0]
print("YES" if(__) el... |
18_D. Seller Bob | Last year Bob earned by selling memory sticks. During each of n days of his work one of the two following events took place:
* A customer came to Bob and asked to sell him a 2x MB memory stick. If Bob had such a stick, he sold it and got 2x berllars.
* Bob won some programming competition and got a 2x MB memory ... | ```python
N = int(input())
L = [-1]*2010
DP = [0]*5010
for i in range(N):
type, cost = input().split()
cost = int(cost)
if type == 'win':
L[cost] = i
elif L[cost] >= 0:
DP[i+1] = DP[L[cost]]+(2**cost)
DP[i+1] = max(DP[i], DP[i+1])
print(DP[N])
``` |
237_D. T-decomposition | You've got a undirected tree s, consisting of n nodes. Your task is to build an optimal T-decomposition for it. Let's define a T-decomposition as follows.
Let's denote the set of all nodes s as v. Let's consider an undirected tree t, whose nodes are some non-empty subsets of v, we'll call them xi <image>. The tree t i... | ```python
import sys
input = sys.stdin.readline
N = 10**5 + 5
g = [[] for _ in range(N)]
p = [0]*N
def bfs(cur):
q = [cur]
i = 0
while i < len(q):
cur = q[i]
i += 1
for nxt in g[cur]:
if(nxt != p[cur]):
p[nxt] = cur
q.append(nxt)
n = int(input())
for i in range(n-1):
a, b = map(int, input().split()... |
262_B. Roma and Changing Signs | Roma works in a company that sells TVs. Now he has to prepare a report for the last year.
Roma has got a list of the company's incomes. The list is a sequence that consists of n integers. The total income of the company is the sum of all integers in sequence. Roma decided to perform exactly k changes of signs of sever... | ```python
rd = lambda: list(map(int, input().split()))
k = kk = rd()[1]
a = rd()
k -= sum(x<0 for x in a)
a[:kk] = list(map(abs, a[:kk]))
print(sum(a)-(2*min(a) if k>0 and k&1 else 0))
# Made By Mostafa_Khaled
``` |
400_C. Inna and Huge Candy Matrix | Inna and Dima decided to surprise Sereja. They brought a really huge candy matrix, it's big even for Sereja! Let's number the rows of the giant matrix from 1 to n from top to bottom and the columns — from 1 to m, from left to right. We'll represent the cell on the intersection of the i-th row and j-th column as (i, j).... | ```python
n,m,x,y,z,p=map(int,input().split())
x=x%4
y=y%2
z=z%4
n0,m0=n,m
for i in range(p):
n,m=n0,m0
x1,y1=map(int,input().split())
for j in range(x):
x1,y1=y1,n-x1+1
n,m=m,n
if y==1:
y1=m-y1+1
# print(x1,y1)
for i in range(z):
x1,y1=m-y1+1,x1
n,m=m... |
450_B. Jzzhu and Sequences | Jzzhu has invented a kind of sequences, they meet the following property:
<image>
You are given x and y, please calculate fn modulo 1000000007 (109 + 7).
Input
The first line contains two integers x and y (|x|, |y| ≤ 109). The second line contains a single integer n (1 ≤ n ≤ 2·109).
Output
Output a single integer... | ```python
n,m=map(int,input().split())
k=int(input())
l=m-n
s=[n,m,l]
z=(k-1)//3
if(z%2==0):
print((s[k%3-1])%1000000007)
else:
print((-1*s[k%3-1])%1000000007)
``` |
472_C. Design Tutorial: Make It Nondeterministic | A way to make a new task is to make it nondeterministic or probabilistic. For example, the hard task of Topcoder SRM 595, Constellation, is the probabilistic version of a convex hull.
Let's try to make a new task. Firstly we will use the following task. There are n people, sort them by their name. It is just an ordina... | ```python
# itne me hi thakk gaye?
n = int(input())
arr = []
for i in range(n):
arr.append(sorted(input().split()))
to_get = [i-1 for i in list(map(int, input().split()))]
# print(arr)
# print(to_get)
ok = True
checked = ""
for i in to_get:
if(arr[i][0] > checked):
curr = arr[i][0]
else:
cur... |
496_D. Tennis Game | Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the ne... | ```python
#!/usr/bin/env python3
import itertools
n = int(input())
a = [int(x) for x in input().split()]
winner = a[-1]
looser = 3 - winner
serve_win_cnt, serve_loose_cnt, win_pos, loose_pos, result = [0], [0], [-1], [-1], []
win_cnt = a.count(winner)
for i in range(n):
if a[i] == winner:
win_pos.append... |
520_A. Pangram | A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | ```python
import string
gauge = set(string.ascii_lowercase)
n = int(input())
line = set(input().lower())
if line == gauge:
print("YES")
else:
print("NO")
``` |
595_C. Warrior and Archer | In the official contest this problem has a different statement, for which jury's solution was working incorrectly, and for this reason it was excluded from the contest. This mistake have been fixed and the current given problem statement and model solution corresponds to what jury wanted it to be during the contest.
V... | ```python
#!/usr/bin/env python3
n = int(input())
n_2 = n // 2
x = sorted([int(tok) for tok in input().split()])
res = min((x[j] - x[j-n_2] for j in range(n_2, n)))
print(res)
``` |
637_A. Voting for Photos | After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the win... | ```python
from collections import Counter
n=int(input())
a=[int(i) for i in input().split(' ')]
c=Counter()
mx=-1
mxid=-1
for i in range(n):
c[a[i]]+=1
if c[a[i]]>mx:
mx=c[a[i]]
mxid=a[i]
print(mxid)
``` |
665_A. Buses Between Cities | Buses run between the cities A and B, the first one is at 05:00 AM and the last one departs not later than at 11:59 PM. A bus from the city A departs every a minutes and arrives to the city B in a ta minutes, and a bus from the city B departs every b minutes and arrives to the city A in a tb minutes.
The driver Simion... | ```python
def solve(a, t1, t2):
l1 = t1 - (t1 - 300) % a + a
if (l1 < 300):
l1 = 300
l2 = t2 - (t2 - 300) % a
if (l2 > 1439):
l2 = 1439
if (l2 < l1):
return 0
return (l2-l1) // a + 1 - (l2 == t2)
def trans(h, m):
return 60 * h + m
data1 = [int(x) for x in in... |
689_D. Friends and Subsequences | Mike and !Mike are old childhood rivals, they are opposite in everything they do, except programming. Today they have a problem they cannot solve on their own, but together (with you) — who knows?
Every one of them has an integer sequences a and b of length n. Being given a query of the form of pair of integers (l, r... | ```python
from bisect import bisect
HISENTINEL = 10**9 + 1
LOSENTINEL = -HISENTINEL
def main():
length = int(input())
a = [int(fld) for fld in input().strip().split()]
b = [int(fld) for fld in input().strip().split()]
print(countmaxminsubseq(a, b))
def countmaxminsubseq(a, b):
leq, lgt = getl... |
711_B. Chris and Magic Square | ZS the Coder and Chris the Baboon arrived at the entrance of Udayland. There is a n × n magic grid on the entrance which is filled with integers. Chris noticed that exactly one of the cells in the grid is empty, and to enter Udayland, they need to fill a positive integer into the empty cell.
Chris tried filling in ran... | ```python
lines = int(input())
if lines == 1:
print(1)
exit(0)
grid = []
number_with_zero = set()
impossible = False
no_zero = -1
for x in range(lines):
num = list(map(int, input().split()))
grid.append(num)
for line in grid:
have_zero = False
s = 0
for n in line:
if n ==0:
... |
732_B. Cormen — The Best Friend Of a Man | Recently a dog was bought for Polycarp. The dog's name is Cormen. Now Polycarp has a lot of troubles. For example, Cormen likes going for a walk.
Empirically Polycarp learned that the dog needs at least k walks for any two consecutive days in order to feel good. For example, if k = 5 and yesterday Polycarp went for a... | ```python
import math
n,k=map(int,input().split())
l2=[]
a=list(map(int,input().split()))
for i in a:
l2.append(i)
i=1
l=[a[0]]
while i<=n-1:
if a[i]+a[i-1]<k:
a[i]=k-a[i-1]
l.append(k-a[i-1])
else:
l.append(a[i])
i=i+1
print(sum(l)-sum(l2))
print(*l)
``` |
777_D. Cloud of Hashtags | Vasya is an administrator of a public page of organization "Mouse and keyboard" and his everyday duty is to publish news from the world of competitive programming. For each news he also creates a list of hashtags to make searching for a particular topic more comfortable. For the purpose of this problem we define hashta... | ```python
def cut_to_lexicographic(word_bigger, word_smaller):
for l in range(len(word_bigger)):
if word_bigger[l] != word_smaller[l]:
return word_bigger[:l]
return word_bigger
n = int(input())
array = [str(input()) for c in range(n)]
b = n - 2
while b > -1:
if array[b + 1] >= array[b]... |
802_B. Heidi and Library (medium) | Whereas humans nowadays read fewer and fewer books on paper, book readership among marmots has surged. Heidi has expanded the library and is now serving longer request sequences.
Input
Same as the easy version, but the limits have changed: 1 ≤ n, k ≤ 400 000.
Output
Same as the easy version.
Examples
Input
4 100... | ```python
import sys
input = sys.stdin.readline
from collections import deque, defaultdict
from heapq import heappush, heappop
n, k = map(int, input().split())
A = list(map(int, input().split()))
dic = defaultdict(deque)
for i, a in enumerate(A):
dic[a].append(i)
hp = []
# for d in dic:
# heappush(hp, (-dic[d][... |
895_C. Square Subsets | Petya was late for the lesson too. The teacher gave him an additional task. For some array a Petya should find the number of different ways to select non-empty subset of elements from it in such a way that their product is equal to a square of some integer.
Two ways are considered different if sets of indexes of eleme... | ```python
from collections import *
l = int(input())
c = Counter(map(int, input().split()))
t = defaultdict(int)
p = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
for k, s in c.items():
d = 0
for i, q in enumerate(p):
while k % q == 0:
k //= q
d ^= 1 ... |
939_E. Maximize! | You are given a multiset S consisting of positive integers (initially empty). There are two kind of queries:
1. Add a positive integer to S, the newly added integer is not less than any number in it.
2. Find a subset s of the set S such that the value <image> is maximum possible. Here max(s) means maximum value ... | ```python
import sys
import math
from collections import defaultdict
#n=int(sys.stdin.readline().split())
arr=[]
q=int(sys.stdin.readline())
a,b=map(int,sys.stdin.readline().split())
l,r=0,0
mean=b
num=1
arr.append(b)
for _ in range(1,q):
lis=list(map(int,sys.stdin.readline().split()))
if lis[0]==1:
b=l... |
965_B. Battleship | Arkady is playing Battleship. The rules of this game aren't really important.
There is a field of n × n cells. There should be exactly one k-decker on the field, i. e. a ship that is k cells long oriented either horizontally or vertically. However, Arkady doesn't know where it is located. For each cell Arkady knows if... | ```python
n, k = [int(x) for x in input().split()]
p = [0]*n
for x in range(n):
p[x] = [x for x in input()]
res = [[0]*n for x in range(n)]
for y in range(n):
for x in range(n):
if x + k <= n:
a = True
for b in range(k):
if p[y][x + b] == "#":
... |
992_B. Nastya Studies Informatics | Today on Informatics class Nastya learned about GCD and LCM (see links below). Nastya is very intelligent, so she solved all the tasks momentarily and now suggests you to solve one of them as well.
We define a pair of integers (a, b) good, if GCD(a, b) = x and LCM(a, b) = y, where GCD(a, b) denotes the [greatest commo... | ```python
from collections import defaultdict
l, r, x, y = map(int, input().split())
if x == y == 1:
if l == 1:
print(1)
exit()
print(0)
exit()
if y % x != 0:
print(0)
exit()
c = x * y
c_ = y // x
i = 2
del_ = defaultdict(int)
while c_ > 1:
while c_ % i == 0:
c_ //=... |
p02623 AtCoder Beginner Contest 172 - Tsundoku | We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.
It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).
Consider the following action:
* Ch... | ```python
from bisect import*
from itertools import*
n,m,k,*x=map(int,open(0).read().split());c=accumulate;b=[*c(x[n:])];print(max(i+bisect(b,k-v)for i,v in enumerate(c([0]+x[:n]))if v<=k))
``` |
p02754 AtCoder Beginner Contest 158 - Count Balls | Takahashi has many red balls and blue balls. Now, he will place them in a row.
Initially, there is no ball placed.
Takahashi, who is very patient, will do the following operation 10^{100} times:
* Place A blue balls at the end of the row of balls already placed. Then, place B red balls at the end of the row.
How ... | ```python
n,a,b = map(int,input().split())
print((n//(a+b)) * a + min((n%(a+b),a)))
``` |
p02889 AtCoder Beginner Contest 143 - Travel by Car | There are N towns numbered 1 to N and M roads. The i-th road connects Town A_i and Town B_i bidirectionally and has a length of C_i.
Takahashi will travel between these towns by car, passing through these roads. The fuel tank of his car can contain at most L liters of fuel, and one liter of fuel is consumed for each u... | ```python
import sys
input = sys.stdin.readline
N, M, L = map(int, input().split())
d = [[10 ** 16 * (i != j) for j in range(N + 1)] for i in range(N + 1)]
for _ in range(M):
x, y, c = map(int, input().split())
d[x][y] = c
d[y][x] = c
for k in range(N + 1):
for i in range(N + 1):
for j in range(N + 1): d[i]... |
p03024 M-SOLUTIONS Programming Contest - Sumo | Takahashi is competing in a sumo tournament. The tournament lasts for 15 days, during which he performs in one match per day. If he wins 8 or more matches, he can also participate in the next tournament.
The matches for the first k days have finished. You are given the results of Takahashi's matches as a string S cons... | ```python
s = input()
print('YES' if s.count('x') <= 7 else "NO")
``` |
p03165 Educational DP Contest - LCS | You are given strings s and t. Find one longest string that is a subsequence of both s and t.
Constraints
* s and t are strings consisting of lowercase English letters.
* 1 \leq |s|, |t| \leq 3000
Input
Input is given from Standard Input in the following format:
s
t
Output
Print one longest string that is a su... | ```python
s1=input()
s2=input()
dp=[0]*(len(s1)+1)
dp[0]=[0]*(len(s2)+1)
for i in range(1,len(s1)+1):
dp[i]=[0]*(len(s2)+1)
for j in range(1,len(s2)+1):
if s1[i-1]==s2[j-1]:
dp[i][j]=dp[i-1][j-1]+1
else:
dp[i][j]=max(dp[i-1][j],dp[i][j-1])
# for i in range(len(s1)+1):
# print(dp[i])
s=""
i,j=len(s1),len(s2... |
p03307 AtCoder Beginner Contest 102 - Multiple of 2 and N | You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N.
Constraints
* 1 \leq N \leq 10^9
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
Output
Print the minimum positive integer divisible by both 2 and N.
Example... | ```python
n = int(input())
if n % 2 == 0:
print(n)
else:
print(2*n)
``` |
p03629 AtCoder Regular Contest 081 - Don't Be a Subsequence | A subsequence of a string S is a string that can be obtained by deleting zero or more characters from S without changing the order of the remaining characters. For example, `arc`, `artistic` and (an empty string) are all subsequences of `artistic`; `abc` and `ci` are not.
You are given a string A consisting of lowerca... | ```python
import sys
input = sys.stdin.readline
A = input().rstrip()
dp = [chr(c) for c in range(ord('a'), ord('z')+1)]
for c in A[::-1]:
s = min(dp, key=lambda x: len(x))
dp[ord(c) - ord('a')] = c + s
print(min(dp, key=lambda x: len(x)))
``` |
p03787 AtCoder Grand Contest 011 - Squared Graph | Takahashi has received an undirected graph with N vertices, numbered 1, 2, ..., N. The edges in this graph are represented by (u_i, v_i). There are no self-loops and multiple edges in this graph.
Based on this graph, Takahashi is now constructing a new graph with N^2 vertices, where each vertex is labeled with a pair ... | ```python
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(m):
u, v = map(int, input().split())
u -= 1
v -= 1
G[u].append(v)
G[v].append(u)
seen = [-1]*n
p, q, r = 0, 0, 0
def dfs(v):
global p, q
stack = [(v, 0)]
seen[v] = 0
f = False
... |
p03955 AtCoder Grand Contest 006 - Rotate 3x3 | We have a grid with 3 rows and N columns. The cell at the i-th row and j-th column is denoted (i, j). Initially, each cell (i, j) contains the integer i+3j-3.
<image>
A grid with N=5 columns
Snuke can perform the following operation any number of times:
* Choose a 3×3 subrectangle of the grid. The placement of inte... | ```python
def merge_and_count_rec(A, W, l, r):
if l+1 >= r:
return 0
m = (l+r)//2
cnt = merge_and_count_rec(A, W, l, m)
cnt += merge_and_count_rec(A, W, m, r)
i,j,k = l,m,l
while i<m and j<r:
if A[i]<=A[j]:
W[k] = A[i]
i+=1
else:
W[k] ... |
p00045 Sum and Average | Create a program that reads the sales unit price and sales quantity and outputs the total sales amount and the average sales quantity.
Input
The input is given in the following format:
Sales unit price, sales quantity
Sales unit price, sales quantity
::
::
A comma-separated pair of unit price and quantity is gi... | ```python
A=[]
while True:
try:
x,y=map(int,input().split(','))
A.append((x,y))
except:
break
amount_of_sales=0
sales_number=0
for i in A:
amount_of_sales+=i[0]*i[1]
sales_number+=i[1]
print(amount_of_sales)
print(int(sales_number/len(A)+0.5))
``` |
p00177 Distance Between Two Cities | Create a program that calculates and outputs the surface distance by inputting the north latitude and east longitude of two cities on the earth. However, the earth is a sphere with a radius of 6,378.1 km, and the surface distance between two points is the shortest distance along this sphere. Also, in the southern hemis... | ```python
from math import pi, acos, cos, sin
while 1:
*S, = map(float, input().split())
if all(e == -1 for e in S):
break
a, b, c, d = map(lambda x: pi * x / 180., S)
x = 6378.1 * acos(sin(a)*sin(c) + cos(a)*cos(c)*cos(b-d))
print(round(x))
``` |
p00333 New Town | In Aizu prefecture, we decided to create a new town to increase the population. To that end, we decided to cultivate a new rectangular land and divide this land into squares of the same size. The cost of developing this land is proportional to the number of plots, but the prefecture wants to minimize this cost.
Create... | ```python
import math
w, h, c = [int(i) for i in input().split()]
g = math.gcd(w, h)
print((w//g) * (h//g) * c)
``` |
p00515 Average Score | problem
Five students, Taro, Jiro, Saburo, Shiro, and Hanako, participated in the JOI High School class.
In this class, a final exam was conducted. All five people took the final exam. For students with a final exam score of 40 or higher, the final exam score was used as is. All students with a final exam score of le... | ```python
data = []
kekka = []
for i in range(5):
n = int(input())
data.append(n)
for i in range(5):
if data[i]<40:
kekka.append(40)
else:
kekka.append(data[i])
print(int(sum(kekka)/5))
``` |
p00691 Fermat's Last Theorem | In the 17th century, Fermat wrote that he proved for any integer $n \geq 3$, there exist no positive integers $x$, $y$, $z$ such that $x^n + y^n = z^n$. However he never disclosed the proof. Later, this claim was named Fermat's Last Theorem or Fermat's Conjecture.
If Fermat's Last Theorem holds in case of $n$, then it... | ```python
a=1/3
while 1:
z=int(input())
if z==0:break
m,zz=0,z*z*z
for x in range(1,int(z/pow(2,a))+1):
xx=x*x*x
y=int(pow(zz-xx,a))
yy=y*y*y
m=max(m,yy+xx)
print(zz-m)
``` |
p00832 Dice Puzzle | Let’s try a dice puzzle. The rules of this puzzle are as follows.
1. Dice with six faces as shown in Figure 1 are used in the puzzle.
<image>
Figure 1: Faces of a die
2. With twenty seven such dice, a 3 × 3 × 3 cube is built as shown in Figure 2.
<image>
Figure 2: 3 × 3 × 3 cube
3. When building up a cube made o... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
D = [
(1, 5, 2, 3, 0, 4), # 'U'
(3, 1, 0, 5, 4, 2), # 'R'
(4, 0, 2, 3, 5, 1), # 'D'
(2, 1, 5, 0, 4, 3), # 'L'
]
p_dice = (0, 0, 0, 1, 1, 2, 2, 3)*3
def enumerate_dice(L0):
L = L0[:]
for k in p_dice:
yield L
... |
p00963 Rendezvous on a Tetrahedron | Problem G Rendezvous on a Tetrahedron
One day, you found two worms $P$ and $Q$ crawling on the surface of a regular tetrahedron with four vertices $A$, $B$, $C$ and $D$. Both worms started from the vertex $A$, went straight ahead, and stopped crawling after a while.
When a worm reached one of the edges of the tetrahe... | ```python
from math import cos, sin, pi, sqrt
B = ["BC", "CD", "DB"]
XY0, d0, l0, XY1, d1, l1 = open(0).read().split()
d0, l0, d1, l1 = map(int, [d0, l0, d1, l1])
def calc(XY, d, l):
angle = B.index(XY) * 60 + d
x = l * cos(pi*angle/180)
y = l * sin(pi*angle/180)
x = x + y/sqrt(3)
y = y * 2/sqrt(3)... |
p01096 Daruma Otoshi | Daruma Otoshi
You are playing a variant of a game called "Daruma Otoshi (Dharma Block Striking)".
At the start of a game, several wooden blocks of the same size but with varying weights are stacked on top of each other, forming a tower. Another block symbolizing Dharma is placed atop. You have a wooden hammer with it... | ```python
n=int(input())
while n!=0:
w=list(map(int,input().split()))
check=[[False]*n for i in range(n)]
for i in range(n-1):
if abs(w[i+1]-w[i])<=1:
check[i][i+1]=True
for i in range(3,n,2):
for j in range(n-i):
for k in range(j+1,j+i):
if check[... |
p01366 Road Construction | King Mercer is the king of ACM kingdom. There are one capital and some cities in his kingdom. Amazingly, there are no roads in the kingdom now. Recently, he planned to construct roads between the capital and the cities, but it turned out that the construction cost of his plan is much higher than expected.
In order to ... | ```python
from heapq import heappush, heappop
def dijkstra(edges, size, source):
distance = [float('inf')] * size
distance[source] = 0
visited = [False] * size
pq = []
heappush(pq, (0, source))
while pq:
dist_u, u = heappop(pq)
visited[u] = True
for v, weight, _ in edge... |
p01704 Flowers | Problem Statement
We have planted $N$ flower seeds, all of which come into different flowers. We want to make all the flowers come out together.
Each plant has a value called vitality, which is initially zero. Watering and spreading fertilizers cause changes on it, and the $i$-th plant will come into flower if its vi... | ```python
import sys
def main():
readline = sys.stdin.readline
write = sys.stdout.write
def gcd(m, n):
while n:
m, n = n, m % n
return m
def init(p, q=1):
g = gcd(p, q)
return p//g, q//g
def add(A, B):
pa, qa = A
pb, qb = B
if pa ... |
p01848 Early Morning Work at Summer Camp | Early morning in summer camp
The morning of JAG summer training camp is early. To be exact, it is not so fast, but many participants feel that it is fast.
At the facility that is the venue for the training camp every year, participants must collect and clean the sheets when they move out. If even one room is delayed,... | ```python
def dfs(s):
for t in G[s]:
if not used[t]:
used[t] = 1
dfs(t)
res.append(s)
def rdfs(s, l):
for t in RG[s]:
if label[t] is None:
label[t] = l
rdfs(t, l)
while 1:
n = int(input())
if n == 0:
break
G = [[] for i in... |
p01984 Tanka Number | Number of tanka
Wishing to die in the spring under the flowers
This is one of the famous tanka poems that Saigyo Hoshi wrote. Tanka is a type of waka poem that has been popular in Japan for a long time, and most of it consists of five phrases and thirty-one sounds of 5, 7, 5, 7, and 7.
By the way, the number 57577 c... | ```python
def solve(N):
k = 0
rng = 0
for i in range(54):
if cl[i] < N <= cl[i+1]:
k = i + 2
rng2 = cl[i]
rng = cl[i+1] - cl[i]
# print(k)
posrng = (N-rng2)%(rng//9)
perrng = (N-rng2)//(rng//9)+1
if posrng == 0:
posrng = rng//9
perr... |
p02130 Combine Two Elements | Problem
Given $ N $ a pair of non-negative integers $ (a_i, b_i) $ and non-negative integers $ A $, $ B $.
I want to do as many of the following operations as possible.
* $ | a_i --b_i | \ leq A $ or $ B \ leq | a_i --b_i | \ leq Take out and delete the element $ i $ that satisfies 2A $
* $ | (a_i + a_j)-(b_i + b_j)... | ```python
N, A, B = map(int, input().split())
P = []
Q = []
ans = 0
for i in range(N):
a, b = map(int, input().split())
v = abs(a-b)
if v <= A or B <= v <= 2*A:
ans += 1
continue
if a > b:
P.append(a-b)
else:
Q.append(a-b)
import collections
class Dinic:
def __in... |
p02271 Exhaustive Search | Write a program which reads a sequence A of n elements and an integer M, and outputs "yes" if you can make M by adding elements in A, otherwise "no". You can use an element only once.
You are given the sequence A and q questions where each question contains Mi.
Notes
You can solve this problem by a Burte Force appro... | ```python
n=int(input())
A=list(map(int,input().split()))
q=int(input())
M=list(map(int,input().split()))
pattern=[]
for i in range(2**n):
s=0
for j in range(n):
if i >> j & 1:
s+=A[j]
pattern.append(s)
P=set(pattern)
for m in M:
print('yes' if m in P else 'no')
``` |
p02418 Ring | Write a program which finds a pattern $p$ in a ring shaped text $s$.
<image>
Constraints
* $1 \leq $ length of $p \leq $ length of $s \leq 100$
* $s$ and $p$ consists of lower-case letters
Input
In the first line, the text $s$ is given.
In the second line, the pattern $p$ is given.
Output
If $p$ is in $s$, prin... | ```python
s = input()
p = input()
print("Yes" if p in (s + s) else "No")
``` |
1057_B. DDoS | We get more and more news about DDoS-attacks of popular websites.
Arseny is an admin and he thinks that a website is under a DDoS-attack if the total number of requests for a some period of time exceeds 100 ⋅ t, where t — the number of seconds in this time segment.
Arseny knows statistics on the number of requests p... | ```python
from itertools import accumulate as ac
from collections import Counter as cc
from bisect import bisect_left as bsl
from bisect import bisect as bs
from math import factorial as f
from collections import *
from itertools import *
from string import *
from bisect import *
from queue import *
from heapq import *... |
1080_A. Petya and Origami | Petya is having a party soon, and he has decided to invite his n friends.
He wants to make invitations in the form of origami. For each invitation, he needs two red sheets, five green sheets, and eight blue sheets. The store sells an infinite number of notebooks of each color, but each notebook consists of only one co... | ```python
data=[int(i) for i in input().split()]
n=data.pop(0)
k=data.pop(0)
red=n*2
green=n*5
blue=n*8
answer=0
if red%k==0:
answer+=red//k
else:
answer+=red//k+1
if blue%k==0:
answer+=blue//k
else:
answer+=blue//k+1
if green%k==0:
answer+=green//k
else:
answer+=green//k+1
print(int... |
1120_E. The very same Munchhausen | A positive integer a is given. Baron Munchausen claims that he knows such a positive integer n that if one multiplies n by a, the sum of its digits decreases a times. In other words, S(an) = S(n)/a, where S(x) denotes the sum of digits of the number x.
Find out if what Baron told can be true.
Input
The only line co... | ```python
tabela = """
3 11 1 1 2 1 2
6 1 4 2 11 3 20
7 2 7 9 1 7 6
9 11 40 1 2 40 0
11 1 7 6 1 6 3
12 2 13 2 11 12 1
13 1 9 15 1 8 30
14 1 10 12 11 9 36
15 11 14 2 2 14 4
17 2 14 9 2 13 27
18 1 34 4 1 33 1
19 1 15 18 1 14 9
21 1 17 10 2 14 8
22 1 12 6 1 10 3
23 1 11 3 11 9 27
24 1 39 6 1 38 0
26 1 16 18 2 15 36
27 11 ... |
1148_A. Another One Bites The Dust | Let's call a string good if and only if it consists of only two types of letters — 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string.
You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin... | ```python
a,b,c=map(int,input().split())
dif=abs(a-b)
if dif <=1:
print(a+b+c*2)
else:
print(min(a,b)*2+1+c*2)
``` |
1169_C. Increasing by Modulo | Toad Zitz has an array of integers, each integer is between 0 and m-1 inclusive. The integers are a_1, a_2, …, a_n.
In one operation Zitz can choose an integer k and k indices i_1, i_2, …, i_k such that 1 ≤ i_1 < i_2 < … < i_k ≤ n. He should then change a_{i_j} to ((a_{i_j}+1) mod m) for each chosen integer i_j. The i... | ```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
l, r = 0, m-1
while r > l:
mid = (l + r) >> 1
p = 0
f = False
for i in a:
if i <= p <= i+mid or i <= p+m <= i+mid:
continue
if i < p:
f = True
break
p = max(p, i)
... |
1187_E. Tree Painting | You are given a tree (an undirected connected acyclic graph) consisting of n vertices. You are playing a game on this tree.
Initially all vertices are white. On the first turn of the game you choose one vertex and paint it black. Then on each turn you choose a white vertex adjacent (connected by an edge) to any black ... | ```python
import sys
input = sys.stdin.readline
n = int(input())
G = [[] for _ in range(n)]
for _ in range(n-1):
a,b = map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
F = [0]*n
stk = [0]
visited = [0]*n
while stk:
x = stk[-1]
if not visited[x]:
visited[x] = 1
for ... |
1206_D. Shortest Cycle | You are given n integer numbers a_1, a_2, ..., a_n. Consider graph on n nodes, in which nodes i, j (i≠ j) are connected if and only if, a_i AND a_j≠ 0, where AND denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND).
Find the length of the shortest cycle in this graph or determine th... | ```python
import sys, os, re, datetime, copy
from collections import *
from bisect import *
def mat(v, *dims):
def dim(i): return [copy.copy(v) for _ in range(dims[-1])] if i == len(dims)-1 else [dim(i+1) for _ in range(dims[i])]
return dim(0)
__cin__ = None
def cin():
global __cin__
if __cin__ is None: __cin__ = i... |
1249_C1. Good Numbers (easy version) | The only difference between easy and hard versions is the maximum value of n.
You are given a positive integer number n. You really love good numbers so you want to find the smallest good number greater than or equal to n.
The positive integer is called good if it can be represented as a sum of distinct powers of 3 (... | ```python
def ternary (n):
if n == 0:
return '0'
nums = []
while n:
n, r = divmod(n, 3)
nums.append(str(r))
return ''.join(reversed(nums))
for xyz in range(0,int(input())):
n=int(input())
s=ternary(n)
f=0
for i in range(0,len(s)):
if s[i]=='2':
... |
1267_J. Just Arrange the Icons | BerPhone X is almost ready for release with n applications being preinstalled on the phone. A category of an application characterizes a genre or a theme of this application (like "game", "business", or "education"). The categories are given as integers between 1 and n, inclusive; the i-th application has category c_i.... | ```python
t = int(input())
for i in range(t):
n = int(input())
c =[int(x) for x in input().split()]
dt = [0]*n
for j in c:
dt[j-1]+=1
# print('dt: ', dt)
dt = sorted(dt)
# print ('dt: ',dt)
for i in range(len(dt)):
if dt[i]!=0:
dt=dt[i:]
break
... |
128_D. Numbers | One day Anna got the following task at school: to arrange several numbers in a circle so that any two neighboring numbers differs exactly by 1. Anna was given several numbers and arranged them in a circle to fulfill the task. Then she wanted to check if she had arranged the numbers correctly, but at this point her youn... | ```python
n=int(input())
g={}
for i in list(map(int,input().split())):g[i]=g.get(i,0)+2
mx=max(g)
for i in sorted(g)[:-1]:
if i+1 not in g:exit(print('NO'))
g[i+1]-=g[i]
if g[i+1]<0:exit(print('NO'))
print('YES'if g[mx]==0 and list(g.values()).count(0)==1else'NO')
``` |
1332_E. Height All the Same | Alice has got addicted to a game called Sirtet recently.
In Sirtet, player is given an n × m grid. Initially a_{i,j} cubes are stacked up in the cell (i,j). Two cells are called adjacent if they share a side. Player can perform the following operations:
* stack up one cube in two adjacent cells;
* stack up two ... | ```python
import io
import os
from collections import Counter, defaultdict, deque
DEBUG = False
def modInverse(a, p):
# Fermat's little theorem, a**(p-1) = 1 mod p
return pow(a, p - 2, p)
def solve(N, M, L, R):
MOD = 998244353
num = R - L + 1
numCells = N * M
# Answer doesn't have to lie... |
1353_A. Most Unstable Array | You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | ```python
t = int(input())
for i in range(t):
n, m = map(int, input().split())
if n >= 3:
print(2 * m)
if n == 2:
print(m)
if n == 1:
print(0)
``` |
141_A. Amusing Joke | 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... | ```python
a = input()
b = input()
n = list(a) + list(b)
n = sorted(n)
p = sorted(list(input()))
if n == p:
print("YES")
else:
print("NO")
``` |
1438_A. Specific Tastes of Andre | Andre has very specific tastes. Recently he started falling in love with arrays.
Andre calls an nonempty array b good, if sum of its elements is divisible by the length of this array. For example, array [2, 3, 1] is good, as sum of its elements — 6 — is divisible by 3, but array [1, 1, 2, 3] isn't good, as 7 isn't div... | ```python
t=int(input())
for i in range(t):
n= int(input())
l=[1]*n
print(*l)
``` |
1462_F. The Treasure of The Segments | Polycarp found n segments on the street. A segment with the index i is described by two integers l_i and r_i — coordinates of the beginning and end of the segment, respectively. Polycarp realized that he didn't need all the segments, so he wanted to delete some of them.
Polycarp believes that a set of k segments is go... | ```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
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.... |
1511_D. Min Cost String | Let's define the cost of a string s as the number of index pairs i and j (1 ≤ i < j < |s|) such that s_i = s_j and s_{i+1} = s_{j+1}.
You are given two positive integers n and k. Among all strings with length n that contain only the first k characters of the Latin alphabet, find a string with minimum possible cost. If... | ```python
def createks(k):
ks = ['a', 'a']
if k == 1:
return ks
ks = ['a', 'a', 'b', 'b', 'a']
if k == 2:
return ks
# k >= 3, follows formula.
msd = 2
while msd < k:
#create extension with msd.
ks.extend([chr(ord('a') + msd), chr(ord('a') + msd-1), chr(ord('a... |
1539_B. Love Song | Petya once wrote a sad love song and shared it to Vasya. The song is a string consisting of lowercase English letters. Vasya made up q questions about this song. Each question is about a subsegment of the song starting from the l-th letter to the r-th letter. Vasya considers a substring made up from characters on this ... | ```python
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
s, psa = [ord(char) - 96 for char in input().strip()], [0]
for i in range(n):
psa.append(s[i] + psa[i])
for _ in range(q):
l, r = map(int, input().split())
print(psa[r] - psa[l - 1])
``` |
233_A. Perfect Permutation | A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn.
Nickolas adores permutations. He likes some permutations more than the o... | ```python
n=int(input())
if n%2==1:
print(-1)
else:
arr1=[2*int(x) for x in range(1,int((n+2)/2))]
arr2=[x-1 for x in arr1]
for i in range(n//2):
print(arr1[i],end=" ")
print(arr2[i],end=" ")
``` |
304_D. Rectangle Puzzle II | You are given a rectangle grid. That grid's size is n × m. Let's denote the coordinate system on the grid. So, each point on the grid will have coordinates — a pair of integers (x, y) (0 ≤ x ≤ n, 0 ≤ y ≤ m).
Your task is to find a maximum sub-rectangle on the grid (x1, y1, x2, y2) so that it contains the given point (... | ```python
#!/usr/bin/python3
def gcd(a, b):
while a:
a, b = b % a, a
return b
n, m, x, y, a, b = tuple(map(int, input().strip().split()))
g = gcd(a, b)
a //= g
b //= g
k = min(n // a, m // b)
w = k * a
h = k * b
ans = [x - w + w // 2, y - h + h // 2, x + w // 2, y + h // 2]
if ans[0] < 0:
ans[2] -... |
352_C. Jeff and Rounding | Jeff got 2n real numbers a1, a2, ..., a2n as a birthday present. The boy hates non-integer numbers, so he decided to slightly "adjust" the numbers he's got. Namely, Jeff consecutively executes n operations, each of them goes as follows:
* choose indexes i and j (i ≠ j) that haven't been chosen yet;
* round elemen... | ```python
n = int(input())
As = list(map(float, input().split()))
B = list(x - int(x) for x in As if x - int(x) > 0.000)
l = len(B)
if l == 0:
print('{:.3f}'.format(0))
exit(0)
S = sum(x for x in B)
ll = l if l % 2 == 0 else l + 1
ans = 1e10
for i in range(max(0, l - n), (n if l > n else l) + 1):
ans = min(ans, ... |
399_A. Pages | User ainta is making a web site. This time he is going to make a navigation of the pages. In his site, there are n pages numbered by integers from 1 to n. Assume that somebody is on the p-th page now. The navigation will look like this:
<< p - k p - k + 1 ... p - 1 (p) p + 1 ... p + k - 1 p + k >>
When someone clicks... | ```python
n, p, k = map(int, input().split())
x = 0
close_symbol = True
pages = ""
if((p-k) > 1):
pages += "<< "
if(k<=p):
for x in range (k):
if(p-k+x == 0):
continue #means that p == k and need to ommit first navigation number
pages += str(p-k+x) + " "
else:
for x in range(1,... |
421_B. Start Up | Recently, a start up by two students of a state university of city F gained incredible popularity. Now it's time to start a new company. But what do we call it?
The market analysts came up with a very smart plan: the name of the company should be identical to its reflection in a mirror! In other words, if we write out... | ```python
def main():
s = input()
print(("NO", "YES")[s == s[::-1] and all(c in "AHIMOTUVWXY" for c in s)])
if __name__ == '__main__':
main()
``` |
46_A. Ball Game | A kindergarten teacher Natalia Pavlovna has invented a new ball game. This game not only develops the children's physique, but also teaches them how to count.
The game goes as follows. Kids stand in circle. Let's agree to think of the children as numbered with numbers from 1 to n clockwise and the child number 1 is h... | ```python
#----Kuzlyaev-Nikita-Codeforces-----
#------------03.04.2020-------------
alph="abcdefghijklmnopqrstuvwxyz"
#-----------------------------------
n=int(input())
now_child=1
for i in range(1,n):
now_child+=i
if now_child>n:
now_child=now_child%n
print(now_child,end=" ")
``` |
492_B. Vanya and Lanterns | Vanya walks late at night along a straight street of length l, lit by n lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point l. Then the i-th lantern is at the point ai. The lantern lights all points of the street that are at the ... | ```python
n,l=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
max=0
for i in range(len(a)-1):
if a[i+1]-a[i]>max:
max=a[i+1]-a[i]
if a[0]>=max/2 and a[0]>=l-a[len(a)-1]:
print("%.10f"%(a[0]))
elif l-a[len(a)-1]>=max/2 and l-a[len(a)-1]>=a[0]:
print("%.10f"%(l-a[len(a)-1]))
elif ma... |
516_A. Drazil and Factorial | Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | ```python
def add(x, i):
if i == 1:
pass
if i == 2:
x.append(2)
if i == 3:
x.append(3)
if i == 4:
x.append(2)
x.append(2)
x.append(3)
if i == 5:
x.append(5)
if i == 6:
x.append(5)
x.append(3)
if i == 7:
x.append... |
543_A. Writing Code | Programmers working on a large project have just received a task to write exactly m lines of code. There are n programmers working on a project, the i-th of them makes exactly ai bugs in every line of code that he writes.
Let's call a sequence of non-negative integers v1, v2, ..., vn a plan, if v1 + v2 + ... + vn = m... | ```python
import sys
import copy
input=sys.stdin.readline
n,m,b,mod=map(int,input().split())
a=list(map(int,input().split()))
dp=[[0]*(m+1) for i in range(b+1)]
dp[0][0]=1
for i in range(n):
for j in range(a[i],b+1):
for k in range(1,m+1):
dp[j][k]=(dp[j][k]+dp[j-a[i]][k-1])%mod
ans=0
for i in range(b+1):
... |
56_C. Corporation Mail | The Beroil corporation structure is hierarchical, that is it can be represented as a tree. Let's examine the presentation of this structure as follows:
* employee ::= name. | name:employee1,employee2, ... ,employeek.
* name ::= name of an employee
That is, the description of each employee consists of his name,... | ```python
#!/usr/bin/env python3
tree = input().strip()
def get_answer(tree, start_index = 0, prev = []):
colon_index = tree.find(':', start_index)
period_index = tree.find('.', start_index)
name_end_index = colon_index if ((colon_index != -1) and (colon_index < period_index)) else period_index
name = tree[s... |
591_A. Wizards' Duel | Harry Potter and He-Who-Must-Not-Be-Named engaged in a fight to the death once again. This time they are located at opposite ends of the corridor of length l. Two opponents simultaneously charge a deadly spell in the enemy. We know that the impulse of Harry's magic spell flies at a speed of p meters per second, and the... | ```python
l=int(input())
p=int(input())
q=int(input())
v=p+q
t=l/v
d=p*t
print(d)
``` |
612_E. Square Root of Permutation | A permutation of length n is an array containing each integer from 1 to n exactly once. For example, q = [4, 5, 1, 2, 3] is a permutation. For the permutation q the square of permutation is the permutation p that p[i] = q[q[i]] for each i = 1... n. For example, the square of q = [4, 5, 1, 2, 3] is p = q2 = [2, 3, 4, 5,... | ```python
import sys
#import random
from bisect import bisect_right as rb
from collections import deque
#sys.setrecursionlimit(10**8)
from queue import PriorityQueue
from math import *
input_ = lambda: sys.stdin.readline().strip("\r\n")
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = la... |
685_B. Kay and Snowflake | After the piece of a devilish mirror hit the Kay's eye, he is no longer interested in the beauty of the roses. Now he likes to watch snowflakes.
Once upon a time, he found a huge snowflake that has a form of the tree (connected acyclic graph) consisting of n nodes. The root of tree has index 1. Kay is very interested ... | ```python
import operator
import bisect
n, q = [int(s) for s in input().split()]
ps = [int(s) for s in input().split()]
childs = [[] for _ in range(n)]
for (c,pa) in enumerate(ps):
childs[pa-1].append(c+1)
toposort = []
this_level = [0]
next_level = []
while len(this_level) > 0:
for this_n in this_level:
... |
708_A. Letters Cyclic Shift | You are given a non-empty string s consisting of lowercase English letters. You have to pick exactly one non-empty substring of s and shift all its letters 'z' <image> 'y' <image> 'x' <image> 'b' <image> 'a' <image> 'z'. In other words, each character is replaced with the previous character of English alphabet and 'a' ... | ```python
import sys
n=input()
i=0
n=n+'a'
m=""
while n[i]=='a' and len(n)>i+1:
i+=1
m=m+'a'
if i+1==len(n):
w=m[0:len(m)-1]+'z'
print(w)
sys.exit()
while n[i]!='a' and len(n)>i:
m=m+chr(ord(n[i])-1)
i+=1
m=m+n[i:len(n)-1]
print(m)
``` |
750_D. New Year and Fireworks | One tradition of welcoming the New Year is launching fireworks into the sky. Usually a launched firework flies vertically upward for some period of time, then explodes, splitting into several parts flying in different directions. Sometimes those parts also explode after some period of time, splitting into even more par... | ```python
import sys
plane = set()
crackers = {((0, -1), (0, 1))}
n = int(input())
a = [int(x) for x in input().split()]
crack_dict = {
(1, 0): ((1, -1), (1, 1)),
(1, 1): ((1, 0), (0, 1)),
(0, 1): ((1, 1), (-1, 1)),
(-1, 1): ((0, 1), (-1, 0)),
(-1, 0): ((-1, 1), (-1, -1)),
(-1, -1): ((-1, 0),... |
774_B. Significant Cups | Stepan is a very experienced olympiad participant. He has n cups for Physics olympiads and m cups for Informatics olympiads. Each cup is characterized by two parameters — its significance ci and width wi.
Stepan decided to expose some of his cups on a shelf with width d in such a way, that:
* there is at least one ... | ```python
n, m, d = map(int, input().split())
ph = [[int(j) for j in input().split()] for i in range(n)]
inf = [[int(j) for j in input().split()] for i in range(m)]
for i in range(n):
ph[i][1] = -ph[i][1]
for i in range(m):
inf[i][1] = -inf[i][1]
ph.sort(reverse=True)
inf.sort(reverse=True)
sw, sc = 0, 0
for p ... |
799_B. T-shirt buying | A new pack of n t-shirts came to a shop. Each of the t-shirts is characterized by three integers pi, ai and bi, where pi is the price of the i-th t-shirt, ai is front color of the i-th t-shirt and bi is back color of the i-th t-shirt. All values pi are distinct, and values ai and bi are integers from 1 to 3.
m buyers ... | ```python
n = int(input())
p = map(int,input().split())
a = map(int,input().split())
b = map(int,input().split())
m = int(input())
pos = map(int,input().split())
fut = zip(p,a,b)
fut=list(fut)
def sravni(elem):
return elem[0]
fut.sort(key=sravni)
vz = []
for i in range(n):
vz.append(False)
lastc = [0,0,0]
re... |
819_B. Mister B and PR Shifts | Some time ago Mister B detected a strange signal from the space, which he started to study.
After some transformation the signal turned out to be a permutation p of length n or its cyclic shift. For the further investigation Mister B need some basis, that's why he decided to choose cyclic shift of this permutation whi... | ```python
def main():
n = int(input())
data = input().split()
#print(str(n) + " " + str(data))
data = list(map(lambda x: int(x), data))
res = 0
ires = 0
neg = 0
when = [0] * n
for i in range(n):
data[i] = i + 1 - data[i]
res += abs(data[i])
if data[i] <= 0:
neg += 1
a = -data[i]
if a < 0:
a ... |
865_B. Ordering Pizza | It's another Start[c]up finals, and that means there is pizza to order for the onsite contestants. There are only 2 types of pizza (obviously not, but let's just pretend for the sake of the problem), and all pizzas contain exactly S slices.
It is known that the i-th contestant will eat si slices of pizza, and gain ai ... | ```python
def solve(ls):
ls.sort(key=lambda q: q[1] - q[0])
m = sum(si for a, b, si in ls)
k = s * (m // s)
n = m - k
x = y = z = 0
for a, b, si in ls:
if k >= si:
k -= si
z += si * a
elif k:
z += k * a
x = (si - k) * a
... |
891_B. Gluttony | You are given an array a with n distinct integers. Construct an array b by permuting a such that for every non-empty subset of indices S = {x1, x2, ..., xk} (1 ≤ xi ≤ n, 0 < k < n) the sums of elements on that positions in a and b are different, i. e.
<image>
Input
The first line contains one integer n (1 ≤ n ≤ 22)... | ```python
import sys
input()
a = list(map(int, input().split()))
b = sorted(a)
for i in a:
sys.stdout.write(str(b[b.index(i)-1]))
sys.stdout.write(" ")
sys.stdout.write("\n")
``` |
913_E. Logical Expression | You are given a boolean function of three variables which is defined by its truth table. You need to find an expression of minimum length that equals to this function. The expression may consist of:
* Operation AND ('&', ASCII code 38)
* Operation OR ('|', ASCII code 124)
* Operation NOT ('!', ASCII code 33) ... | ```python
answers = [
'!x&x',
'x&y&z',
'!z&x&y',
'x&y',
'!y&x&z',
'x&z',
'!y&x&z|!z&x&y',
'(y|z)&x',
'!y&!z&x',
'!y&!z&x|x&y&z',
'!z&x',
'!z&x|x&y',
'!y&x',
'!y&x|x&z',
'!(y&z)&x',
'x',
'!x&y&z',
'y&z',
'!x&y&z|!z&x&y',
'(x|z)&y',
'!x&y&z|!y&x&z',
'(x|y)&z',
'!x&y&z|!y&x&z|!z&x&y',
'(x|y)&z|x&y',
'!x&y&z|!y&!z&x',
'!y&... |
935_E. Fafa and Ancient Mathematics | Ancient Egyptians are known to have understood difficult concepts in mathematics. The ancient Egyptian mathematician Ahmes liked to write a kind of arithmetic expressions on papyrus paper which he called as Ahmes arithmetic expression.
An Ahmes arithmetic expression can be defined as:
* "d" is an Ahmes arithmetic ... | ```python
from math import inf
class Node:
def __init__(self, parent = None, leftExp = None, rightExp = None, signQ = 0):
self.parent, self.leftExp, self.rightExp, self.signQ = parent, leftExp, rightExp, signQ
def __str__(self):
return "Node"
memo = {}
def Memoize(node, p, maxValue, minValue)... |
961_D. Pair Of Lines | You are given n points on Cartesian plane. Every point is a lattice point (i. e. both of its coordinates are integers), and all points are distinct.
You may draw two straight lines (not necessarily distinct). Is it possible to do this in such a way that every point lies on at least one of these lines?
Input
The firs... | ```python
n = int(input())
lst = []
for x in range(n):
(a, b) = map(int, input().split())
lst.append((a, b))
def scal(x1, y1, x2, y2, x3, y3):
if (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1) == 0:
return True
return False
def check():
for x in range(n - 2):
if len(s2) >= 3:
... |
989_C. A Mist of Florescence | As the boat drifts down the river, a wood full of blossoms shows up on the riverfront.
"I've been here once," Mino exclaims with delight, "it's breathtakingly amazing."
"What is it like?"
"Look, Kanno, you've got your paintbrush, and I've got my words. Have a try, shall we?"
There are four kinds of flowers in the ... | ```python
import sys
A, B, C, D = map(int, sys.stdin.readline().split())
cols = 49
rows = 50
res = [['.' for i in range(cols)] for j in range (rows)]
A -= 1
B -= 1
for r in range (rows // 2):
for c in range (cols):
if r % 2 == 0 or c % 2 == 0:
res[r][c] = 'A'
elif B > 0:
res[r][c] = 'B'
B -=... |
p02601 M-SOLUTIONS Programming Contest 2020 - Magic 2 | M-kun has the following three cards:
* A red card with the integer A.
* A green card with the integer B.
* A blue card with the integer C.
He is a genius magician who can do the following operation at most K times:
* Choose one of the three cards and multiply the written integer by 2.
His magic is successful if... | ```python
a,b,c,k=map(int,open(0).read().split())
for i in' '*k:
if a>=b:b*=2
elif b>=c:c*=2
print('NYoe s'[a<b<c::2])
``` |
p02732 AtCoder Beginner Contest 159 - Banned K | We have N balls. The i-th ball has an integer A_i written on it.
For each k=1, 2, ..., N, solve the following problem and print the answer.
* Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.
Constraint... | ```python
n=int(input())
a=list(map(int,input().split()))
e=list(set(a))
s=0
t=[0]*200000
for i in a:
t[i]+=1
for j in e:
k=t[j]
s+=(k*(k-1))//2
for u in a:
print(s-t[u]+1)
``` |
p02865 NIKKEI Programming Contest 2019-2 - Sum of Two Integers | How many ways are there to choose two distinct positive integers totaling N, disregarding the order?
Constraints
* 1 \leq N \leq 10^6
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Examples
Input
4
Output
1
Input
999999
Output
499999 | ```python
N = int(input())
print(N // 2 - int(N // 2 * 2 == N))
``` |
p03000 AtCoder Beginner Contest 130 - Bounding | A ball will bounce along a number line, making N + 1 bounces. It will make the first bounce at coordinate D_1 = 0, and the i-th bounce (2 \leq i \leq N+1) at coordinate D_i = D_{i-1} + L_{i-1}.
How many times will the ball make a bounce where the coordinate is at most X?
Constraints
* 1 \leq N \leq 100
* 1 \leq L_i ... | ```python
n, x = map(int, input().split())
l = [int(i) for i in input().split()]
d = 0
c = 0
for i in l:
d += i
if d <= x:
c += 1
print(c+1)
``` |
p03141 NIKKEI Programming Contest 2019 - Different Strokes | There are N dishes of cuisine placed in front of Takahashi and Aoki. For convenience, we call these dishes Dish 1, Dish 2, ..., Dish N.
When Takahashi eats Dish i, he earns A_i points of happiness; when Aoki eats Dish i, she earns B_i points of happiness.
Starting from Takahashi, they alternately choose one dish and ... | ```python
N = int(input())
A, B = [], []
for i in range(N):
a,b = map(int, input().split())
A.append(a)
B.append(b)
AB = sorted([s+t for s,t in zip(A,B)], reverse=True)
su = sum(AB[::2])
print(su-sum(B))
``` |
p03285 AtCoder Beginner Contest 105 - Cakes and Donuts | La Confiserie d'ABC sells cakes at 4 dollars each and doughnuts at 7 dollars each. Determine if there is a way to buy some of them for exactly N dollars. You can buy two or more doughnuts and two or more cakes, and you can also choose to buy zero doughnuts or zero cakes.
Constraints
* N is an integer between 1 and 10... | ```python
n = int(input())
li = [1,2,3,5,6,9,10,13,17]
if n in li:
print("No")
else:
print("Yes")
``` |
p03441 AtCoder Petrozavodsk Contest 001 - Antennas on Tree | We have a tree with N vertices. The vertices are numbered 0 through N - 1, and the i-th edge (0 ≤ i < N - 1) comnnects Vertex a_i and b_i. For each pair of vertices u and v (0 ≤ u, v < N), we define the distance d(u, v) as the number of edges in the path u-v.
It is expected that one of the vertices will be invaded by ... | ```python
import sys
readline = sys.stdin.readline
from collections import Counter
from random import randrange
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stac... |
p03599 AtCoder Beginner Contest 074 - Sugar Water | Snuke is making sugar water in a beaker. Initially, the beaker is empty. Snuke can perform the following four types of operations any number of times. He may choose not to perform some types of operations.
* Operation 1: Pour 100A grams of water into the beaker.
* Operation 2: Pour 100B grams of water into the beaker.... | ```python
a,b,c,d,e,f=map(int,input().split())
a100=a*100
b100=b*100
ok=[]
for ai in range(31):
for bi in range(31):
for ci in range(101):
for di in range(101):
ab= ai*a100+bi*b100
cd= ci*c+di*d
if ab + cd >f:
break
else:
if (ab/100)*e>=cd:
ok.... |
p03760 AtCoder Beginner Contest 058 - ∵∴∵ | Snuke signed up for a new website which holds programming competitions. He worried that he might forget his password, and he took notes of it. Since directly recording his password would cause him trouble if stolen, he took two notes: one contains the characters at the odd-numbered positions, and the other contains the... | ```python
O = input()
E = input() + " "
for i in range(len(O)): print(O[i]+E[i],end="",sep="")
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.