name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
15_C. Industrial Nim | There are n stone quarries in Petrograd.
Each quarry owns mi dumpers (1 ≤ i ≤ n). It is known that the first dumper of the i-th quarry has xi stones in it, the second dumper has xi + 1 stones in it, the third has xi + 2, and the mi-th dumper (the last for the i-th quarry) has xi + mi - 1 stones in it.
Two oligarchs p... | ```python
__author__ = 'Darren'
def solve():
n = int(input())
xor = 0
for _i in range(n):
x, m = map(int, input().split())
xor ^= xor_range(x - 1) ^ xor_range(x + m - 1)
print(["tolik", "bolik"][xor == 0])
def xor_range(n):
return [n, 1, n+1, 0][n % 4]
if __name... |
202_A. LLPS | This problem's actual name, "Lexicographically Largest Palindromic Subsequence" is too long to fit into the page headline.
You are given string s consisting of lowercase English letters only. Find its lexicographically largest palindromic subsequence.
We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk (1 ≤ ... | ```python
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 19:56:34 2020
@author: roastedcoder
This is for CodeForces
"""
mod = 1000000007
ssi = lambda : map(int,input().split())
# RoastedCoder
s = input()
l = [0]*26
for i in range(len(s)):
l[ord(s[i])-97] += 1
for i in range(25,-1,-1):
if(l[i] >= 1):
... |
250_C. Movie Critics | A film festival is coming up in the city N. The festival will last for exactly n days and each day will have a premiere of exactly one film. Each film has a genre — an integer from 1 to k.
On the i-th day the festival will show a movie of genre ai. We know that a movie of each of k genres occurs in the festival progra... | ```python
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in... |
275_D. Zero Tree | A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tr... | ```python
import sys
def minp():
return sys.stdin.readline().strip()
n = int(minp())
e = [0]
p = [None]*(n+1)
for i in range(n):
e.append([])
for i in range(n-1):
a, b = map(int,minp().split())
e[a].append(b)
e[b].append(a)
v = list(map(int,minp().split()))
plus = [0]*(n+1)
minus = [0]*(n+1)
was = [False]*(n+1)... |
299_A. Ksusha and Array | Ksusha is a beginner coder. Today she starts studying arrays. She has array a1, a2, ..., an, consisting of n positive integers.
Her university teacher gave her a task. Find such number in the array, that all array elements are divisible by it. Help her and find the number!
Input
The first line contains integer n (1 ... | ```python
input()
line = list(map(int, input().split()))
line.sort()
for i in line:
if i % line[0] != 0:
print(-1)
break
else:
print(line[0])
``` |
346_B. Lucky Common Subsequence | In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence BDF is a subsequence of ABCDEF. A substring of a string is a continuous subsequence of the string. For example, BCD is a substri... | ```python
#Not actually my code, solved mentally, only submitting to mark as solved so I don't do it again.
def gen(i, j):
if a[i][j] == -1:
a[i][j] = max(gen(i - 1, j - 1) + s2[i - 1] * (s2[i - 1] == s1[j - 1]), gen(i - 1, j), gen(i, j - 1), key = lambda x: [len(x), -x.count(viru)])
return a[i][j]
s... |
414_A. Mashmokh and Numbers | It's holiday. Mashmokh and his boss, Bimokh, are playing a game invented by Mashmokh.
In this game Mashmokh writes sequence of n distinct integers on the board. Then Bimokh makes several (possibly zero) moves. On the first move he removes the first and the second integer from from the board, on the second move he rem... | ```python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
def main():
n, k = [ int(x) for x in input().split() ]
x = k - (n // 2 - 1)
if x < 1 or (n < 2 and k > 0):
print(-1)
return
sequence = [0] * n
sequence[0] = x
if n... |
440_C. One-Based Arithmetic | Prof. Vasechkin wants to represent positive integer n as a sum of addends, where each addends is an integer number containing only 1s. For example, he can represent 121 as 121=111+11+–1. Help him to find the least number of digits 1 in such sum.
Input
The first line of the input contains integer n (1 ≤ n < 1015).
Ou... | ```python
import math
def find(n,i):
ans = 0
k = n // ones[i]
n = n % ones[i]
ans = ans + k * i
if n == 0:
return ans
return ans + min(find(n, i-1), i + find(ones[i] - n, i-1))
n = int(input())
ones = [0]
for i in range(1,17):
one = 10 * ones[i-1] + 1
ones.append(one)
print(find(n,16))
``` |
486_D. Valid Sets | As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In ... | ```python
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
# def print(x):
# sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
... |
50_C. Happy Farm 5 | The Happy Farm 5 creators decided to invent the mechanism of cow grazing. The cows in the game are very slow and they move very slowly, it can even be considered that they stand still. However, carnivores should always be chased off them.
For that a young player Vasya decided to make the shepherd run round the cows a... | ```python
import math
n = int(input())
l = []
for i in range(n):
l.append(tuple(list(map(int, input().split(" ")))))
l = list(set(l))
n = len(l)
pmin = 0
for i in range(1, n):
if(l[i][1] < l[pmin][1] or (l[i][1] == l[pmin][1] and l[i][0] < l[pmin][0])):
pmin = i
l[pmin], l[0] = l[0], l[pmin]
def or... |
534_E. Berland Local Positioning System | In Berland a bus travels along the main street of the capital. The street begins from the main square and looks like a very long segment. There are n bus stops located along the street, the i-th of them is located at the distance ai from the central square, all distances are distinct, the stops are numbered in the orde... | ```python
r = lambda: list(map(int, input().split()))
ri = lambda: int(input())
n, a, m, b = ri(), r(), ri(), r()
c = [0] * n
for e in b: c[e - 1] += 1
c[0] *= 2; c[-1] *= 2
d = 0
df= 0
r = max(e // 2 for e in c)
c = [e - r * 2 for e in c]
if any(c):
for i in range(n - 1):
de = a[i+1] - a[i]
d += mi... |
585_C. Alice, Bob, Oranges and Apples | Alice and Bob decided to eat some fruit. In the kitchen they found a large bag of oranges and apples. Alice immediately took an orange for herself, Bob took an apple. To make the process of sharing the remaining fruit more fun, the friends decided to play a game. They put multiple cards and on each one they wrote a let... | ```python
import fractions
def solve(x, y):
if fractions.gcd(x, y) > 1: return 'Impossible'
turn = x > y
if not turn: x, y = y, x
ans = []
while x != 0 and y != 0:
ans.append((x//y, 'A' if turn else 'B'))
x, y = y, x%y
turn = not turn
ans[-1] = (ans[-1][0]-1, ans[-1][1])
... |
607_C. Marbles | In the spirit of the holidays, Saitama has given Genos two grid paths of length n (a weird gift even by Saitama's standards). A grid path is an ordered sequence of neighbouring squares in an infinite grid. Two squares are neighbouring if they share a side.
One example of a grid path is (0, 0) → (0, 1) → (0, 2) → (1, 2... | ```python
from time import time
opposite = {
'N': 'S',
'S': 'N',
'E': 'W',
'W': 'E'
}
otr = str.maketrans(opposite)
bits = {
'N': 0,
'S': 1,
'E': 2,
'W': 3,
}
Q = 4294967291
def combine(h, v, q):
return (h<<2 | v) % q
def combinel(h, v, q, s):
return (v*s + h) % q
def f... |
629_B. Far Relative’s Problem | Famil Door wants to celebrate his birthday with his friends from Far Far Away. He has n friends and each of them can come to the party in a specific range of days of the year from ai to bi. Of course, Famil Door wants to have as many friends celebrating together with him as possible.
Far cars are as weird as Far Far A... | ```python
n = (int)(input())
F1=[0]*n
F2=[0]*n
M1=[0]*n
M2=[0]*n
m=0
f=0
for i in range(n):
c = (input().split())
if(c[0]=='M'):
M1[m]=(int)(c[1])
M2[m]=(int)(c[2])
m=m+1
if(c[0]=='F'):
F1[f]=(int)(c[1])
F2[f]=(int)(c[2])
f=f+1
F=[0]*3232
M=[0]*3266
for i in r... |
653_C. Bear and Up-Down | The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, ... | ```python
def main():
n, l = int(input()), list(map(int, input().split()))
if not (n & 1):
l.append(0)
l.append(150001)
a, b, fails, res = 0, 150001, [], 0
for i, c in enumerate(l, -1):
if i & 1:
if a >= b or b <= c:
if len(fails) > 5:
... |
679_A. 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
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.... |
701_B. Cells Not Under Attack | Vasya has the square chessboard of size n × n and m rooks. Initially the chessboard is empty. Vasya will consequently put the rooks on the board one after another.
The cell of the field is under rook's attack, if there is at least one rook located in the same row or in the same column with this cell. If there is a roo... | ```python
n, m = map(int, input().strip().split())
remains = n*n
deleted_rows = set()
deleted_cols = set()
answer = []
for _ in range(m):
c, r = map(int, input().strip().split())
col_deleted = c in deleted_cols
row_deleted = r in deleted_rows
if not (col_deleted and row_deleted):
if col_deleted... |
723_C. Polycarp at the Radio | Polycarp is a music editor at the radio station. He received a playlist for tomorrow, that can be represented as a sequence a1, a2, ..., an, where ai is a band, which performs the i-th song. Polycarp likes bands with the numbers from 1 to m, but he doesn't really like others.
We define as bj the number of songs the g... | ```python
from collections import Counter
n, m = map(int, input().split())
nums = list(map(int, input().split()))
cnts = dict(Counter(nums))
for i in range(1, m+1):
if i not in cnts:
cnts[i] = 0
def minner():
return min(cnts.items(), key=lambda x: x[1])
n //= m
res = 0
for i, num in enumerate(nums... |
745_B. Hongcow Solves A Puzzle | Hongcow likes solving puzzles.
One day, Hongcow finds two identical puzzle pieces, with the instructions "make a rectangle" next to them. The pieces can be described by an n by m grid of characters, where the character 'X' denotes a part of the puzzle and '.' denotes an empty part of the grid. It is guaranteed that th... | ```python
n, m = map(int, input().split())
o1 = set()
for i in range(n):
s = input()
if s.count('X') != 0:
o1.add((s.count('X'), s.find('X'), s.rfind('X')))
if len(o1) == 1:
print('YES')
else:
print('NO')
``` |
768_D. Jon and Orbs | Jon Snow is on the lookout for some orbs required to defeat the white walkers. There are k different types of orbs and he needs at least one of each. One orb spawns daily at the base of a Weirwood tree north of the wall. The probability of this orb being of any kind is equal. As the north of wall is full of dangers, he... | ```python
k, q = map(int, input().split())
t = [0] * (k + 1)
t[1] = 1
c = [0]
n = i = 1
while i < 1001:
if (2000 * t[k] > i - (10**-7)):
c.append(n)
i += 1
else:
t = [0] + [(j * t[j] + (k - j + 1) * t[j - 1]) / k for j in range(1, k + 1)]
n += 1
for i in range(q):
print(c[in... |
792_C. Divide by Three | A positive integer number n is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zer... | ```python
a = input()
if len(a) == 1:
if int(a) % 3 == 0:
print(a)
else:
print(-1)
exit(0)
one = []
two = []
sum = 0
zs, zf = 0, 0
for i in range(len(a)):
q = int(a[i])
sum += q
if q == 0:
if zs == 0:
zs = i
else:
if zs != 0 and zf == 0:
... |
812_E. Sagheer and Apple Tree | Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd ... | ```python
n= int(input())
a = [int(_) for _ in input().split()]
c = [int(_) for _ in input().split()]
depth = [0] * (n)
for i in range(1,n):
depth[i] = depth[c[i-1]-1] + 1
MAX = max(depth)
t = 0
store = {}
todo = []
p = 0
for i in range(n):
if (MAX-depth[i]) % 2 == 0: # odd, useful
t ^= a[i]
todo... |
859_B. Lazy Security Guard | Your security guard friend recently got a new job at a new security company. The company requires him to patrol an area of the city encompassing exactly N city blocks, but they let him choose which blocks. That is, your friend must walk the perimeter of a region whose area is exactly N blocks. Your friend is quite lazy... | ```python
import math
n=int(input())
print(math.ceil(math.sqrt(n)*2)*2)
``` |
884_A. Book Reading | Recently Luba bought a very interesting book. She knows that it will take t seconds to read the book. Luba wants to finish reading as fast as she can.
But she has some work to do in each of n next days. The number of seconds that Luba has to spend working during i-th day is ai. If some free time remains, she can spend... | ```python
n,t=map(int,input().split())
a=input().split()
i=0
while t > 0:
t-=(86400-int(a[i]))
i += 1
print(i)
``` |
908_C. New Year and Curling | Carol is currently curling.
She has n disks each with radius r on the 2D plane.
Initially she has all these disks above the line y = 10100.
She then will slide the disks towards the line y = 0 one by one in order from 1 to n.
When she slides the i-th disk, she will place its center at the point (xi, 10100). She w... | ```python
n, r = map(int, input().split())
a = input().split()
ans = []
for i in range(n):
res = r
for j in range(i):
if (abs(int(a[j]) - int(a[i])) <= 2 * r):
res = max(res, ans[j] + (4 * r * r - abs(int(a[j]) - int(a[i])) ** 2) ** 0.5)
ans.append(res)
for i in range(n):
print(ans[i... |
92_B. Binary Number | Little walrus Fangy loves math very much. That's why when he is bored he plays with a number performing some operations.
Fangy takes some positive integer x and wants to get a number one from it. While x is not equal to 1, Fangy repeats the following action: if x is odd, then he adds 1 to it, otherwise he divides x by... | ```python
from collections import *
def add(n):
for i in range(len(n) - 1, -1, -1):
if n[i] == '1':
n[i] = '0'
else:
n[i] = '1'
return n
n.appendleft('1')
return n
def main():
n, ans = deque(input()), 0
while (len(n) != 1):
if n[-1] ==... |
983_B. XOR-pyramid | For an array b of length m we define the function f as
f(b) = \begin{cases} b[1] & if m = 1 \\\ f(b[1] ⊕ b[2],b[2] ⊕ b[3],...,b[m-1] ⊕ b[m]) & otherwise, \end{cases}
where ⊕ is [bitwise exclusive OR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, f(1,2,4,8)=f(1⊕2,2⊕4,4⊕8)=f(3,6,12)=f(3⊕6... | ```python
n = int(input())
arr = list(map(int, input().split()))
aux = [[0] * n for i in range(n)]
for i in range(n):
aux[0][i] = arr[i]
for i in range(1, n):
for j in range(n-i):
aux[i][j] = aux[i-1][j] ^ aux[i-1][j+1]
for i in range(1, n):
for j in range(n-i):
aux[i][j] = max(aux[i][j], aux[i-1][... |
p02565 AtCoder Library Practice Contest - Two SAT | Consider placing N flags on a line. Flags are numbered through 1 to N.
Flag i can be placed on the coordinate X_i or Y_i. For any two different flags, the distance between them should be at least D.
Decide whether it is possible to place all N flags. If it is possible, print such a configulation.
Constraints
* 1 \l... | ```python
class Two_SAT:
"""2-SATを定義する.
"""
#入力定義
def __init__(self,variable=[]):
self.variable=set(variable)
self.clause_number=0
self.variable_number=len(variable)
self.adjacent_out={(v,b):set() for v in variable for b in [True,False]} #出近傍(vが始点)
self.adjace... |
p02696 AtCoder Beginner Contest 165 - Floor Function | Given are integers A, B, and N.
Find the maximum possible value of floor(Ax/B) - A × floor(x/B) for a non-negative integer x not greater than N.
Here floor(t) denotes the greatest integer not greater than the real number t.
Constraints
* 1 ≤ A ≤ 10^{6}
* 1 ≤ B ≤ 10^{12}
* 1 ≤ N ≤ 10^{12}
* All values in input are i... | ```python
A,B,N = map(int,input().split())
c = min(B - 1,N)
print((A * c)//B)
``` |
p02825 AtCoder Grand Contest 041 - Domino Quality | Let us consider a grid of squares with N rows and N columns. You want to put some domino pieces on this grid. Each domino piece covers two squares that have a common side. Each square can be covered by at most one piece.
For each row of the grid, let's define its quality as the number of domino pieces that cover at le... | ```python
n = int(input())
s3=["abb","a.d","ccd"]
s = [["abcc", "abdd", "ddba", "ccba"],
["dccdd", "daa.c", "c..bc", "c..bd", "ddccd"],
["abbc..", "a.ac..", "bba.cc", "a..aab", "a..b.b", ".aabaa"],
["aba....","aba....","bab....","bab....","a..bbaa","a..aabb",".aabbaa"]]
if n == 2:
print(-1)
elif n == 3:
[print... |
p02962 AtCoder Beginner Contest 135 - Strings of Eternity | Given are two strings s and t consisting of lowercase English letters. Determine if the number of non-negative integers i satisfying the following condition is finite, and find the maximum value of such i if the number is finite.
* There exists a non-negative integer j such that the concatenation of i copies of t is a... | ```python
# AOJ ALDS1_14_B "String Search"
# returns i s.t. S[i+j] = T[j] for 0 <= j < len(T)
def RollingHash(S, T, ls):
if len(S) < len(T):
return []
# gcd(h, b) = 1
h = 10**11+7
b = 10**7+7
L = len(T)
bL = 1
for i in range(L):
bL = bL * b % h
hashS = 0
for i in r... |
p03097 AtCoder Grand Contest 031 - Differ by 1 Bit | You are given integers N,\ A and B. Determine if there exists a permutation (P_0,\ P_1,\ ...\ P_{2^N-1}) of (0,\ 1,\ ...\ 2^N-1) that satisfies all of the following conditions, and create one such permutation if it exists.
* P_0=A
* P_{2^N-1}=B
* For all 0 \leq i < 2^N-1, the binary representations of P_i and P_{i+1} ... | ```python
N, A, B = map(int, input().split())
def f(n, a, b):
if n == 1:
return [a, b]
mask = 1 << (n-1)
if a & mask == b & mask:
v1 = f(n-1, a, b)
v2 = f(n-1, a ^ mask, v1[1] ^ mask)
ret = v1[:1]
ret.extend(v2)
ret.extend(v1[1:])
return ret
els... |
p03243 AtCoder Beginner Contest 111 - AtCoder Beginner Contest 111 | Kurohashi has never participated in AtCoder Beginner Contest (ABC).
The next ABC to be held is ABC N (the N-th ABC ever held). Kurohashi wants to make his debut in some ABC x such that all the digits of x in base ten are the same.
What is the earliest ABC where Kurohashi can make his debut?
Constraints
* 100 \leq N... | ```python
N=int(input());print(111*(-(-N//111)))
``` |
p03561 AtCoder Regular Contest 084 - Finite Encyclopedia of Integer Sequences | In Finite Encyclopedia of Integer Sequences (FEIS), all integer sequences of lengths between 1 and N (inclusive) consisting of integers between 1 and K (inclusive) are listed.
Let the total number of sequences listed in FEIS be X. Among those sequences, find the (X/2)-th (rounded up to the nearest integer) lexicograph... | ```python
import sys
input = sys.stdin.readline
K,N = map(int,input().split())
if K % 2 == 0:
L = K // 2
R = L + 1
# 先頭の文字が L のものの最後、R のものの最初、で境界
arr = [L] + [K] * (N-1)
else:
"""
[3,3,3,3,3] だと 手前に3 33 333 3333 が余分。2歩戻る。
"""
arr = [(K+1)//2] * N
x = N//2# x歩 戻る
for i in range(... |
p03714 AtCoder Beginner Contest 062 - 3N Numbers | Let N be a positive integer.
There is a numerical sequence of length 3N, a = (a_1, a_2, ..., a_{3N}). Snuke is constructing a new sequence of length 2N, a', by removing exactly N elements from a without changing the order of the remaining elements. Here, the score of a' is defined as follows: (the sum of the elements ... | ```python
def f(x):
y=x[:n];heapify(y);z=sum(y);s=[z]
for i in x[n:n*2]:z+=i-heappushpop(y,i);s+=[z]
return s
from heapq import*;n,*a=map(int,open(0).read().split());print(max(map(sum,zip(f([-i for i in a[n:][::-1]]),f(a)[::-1]))))
``` |
p04037 AtCoder Grand Contest 002 - Candy Piles | There are N piles of candies on the table. The piles are numbered 1 through N. At first, pile i contains a_i candies.
Snuke and Ciel are playing a game. They take alternating turns. Snuke goes first. In each turn, the current player must perform one of the following two operations:
1. Choose a pile with the largest n... | ```python
N=int(input())
A=list(map(int,input().split()))
A.append(0)
A.sort()
winner=""
for i in range(N+1):
if A[N-i]>i:
if (A[N-i]-i)%2==0:
winner="First"
else:
winner="Second"
elif A[N-i]==i:
if (A[N-i+1]-A[N-i])%2==1:
winner="First"
br... |
p00118 Property Distribution | Mr. Tanaka died leaving the orchard of HW Earl. The orchard is divided into H x W plots in the north, south, east, and west directions, and apples, oysters, and oranges are planted in each plot. Mr. Tanaka left such a will.
Divide the orchard into as many relatives as possible on a parcel basis. However, if the same k... | ```python
import sys
sys.setrecursionlimit(100000)
def solve(x, y, char):
for deltaX in [1, -1]:
if 0 <= x + deltaX and x + deltaX < w and matrix[y][x + deltaX] == char:
matrix[y][x + deltaX] = "."
solve(x+deltaX, y, char)
for deltaY in [1, -1]:
if 0 <= y + deltaY and y... |
p00251 Points for a Perfect Scorer | Welcome to PC Koshien, players. This year marks the 10th anniversary of Computer Koshien, but the number of questions and the total score will vary from year to year. Scores are set for each question according to the difficulty level. When the number of questions is 10 and the score of each question is given, create a ... | ```python
s1=int(input())
s2=int(input())
s3=int(input())
s4=int(input())
s5=int(input())
s6=int(input())
s7=int(input())
s8=int(input())
s9=int(input())
s10=int(input())
total=0
total+=s1
total+=s2
total+=s3
total+=s4
total+=s5
total+=s6
total+=s7
total+=s8
total+=s9
total+=s10
print(total)
``` |
p00628 Yes | Dr .: Peter, do you know "Yes, I have a number"?
Peter: I used to do it on TV the other day. You remember something by the number of characters in each word contained in a sentence. "Yes, I have a number", so it means "the number 3.14" and is a keyword for remembering pi.
Dr .: Peter, that's not the case. This should... | ```python
import sys
sys.setrecursionlimit(10**6)
def main():
s = input()
if s == "END OF INPUT":
return False
if s[0] == " ":
s[0] = "."
for _ in range(100):
s = s.replace(" ", " . ")
lst = s.split()
ans = []
for i in lst:
if i == ".":
ans += [0]... |
p00903 Round Trip | Jim is planning to visit one of his best friends in a town in the mountain area. First, he leaves his hometown and goes to the destination town. This is called the go phase. Then, he comes back to his hometown. This is called the return phase. You are expected to write a program to find the minimum total cost of this t... | ```python
from heapq import heappush, heappop
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
if N == M == 0:
return False
D = [0]*N; E = [0]*N
B = [0]*N
H = defaultdict(int)
H[0] = 1
... |
p01036 Yu-kun Likes To Play Darts | Background
The kindergarten attached to the University of Aizu is a kindergarten where children who love programming gather. Yu, one of the kindergarten children, loves darts as much as programming. Yu-kun was addicted to darts recently, but he got tired of ordinary darts, so he decided to make his own darts board.
S... | ```python
# 参考 http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=3277276#1
from math import acos, hypot, isclose, sqrt
def intersection(circle, polygon):
# 円と多角形の共通部分の面積
# 多角形の点が反時計回りで与えられれば正の値、時計回りなら負の値を返す
x, y, r = circle
polygon = [(xp-x, yp-y) for xp, yp in polygon]
area = 0.0
for p1, p2... |
p01306 Unit Converter | In the International System of Units (SI), various physical quantities are expressed in the form of "numerical value + prefix + unit" using prefixes such as kilo, mega, and giga. For example, "3.5 kilometers", "5.1 milligrams", and so on.
On the other hand, these physical quantities can be expressed as "3.5 * 10 ^ 3 m... | ```python
m = {"yotta":24, "zetta":21, "exa":18, "peta":15, "tera":12, "giga":9, "mega":6, "kilo":3, "hecto":2, "deca":1, "deci":-1, "centi":-2, "milli":-3, "micro":-6, "nano":-9, "pico":-12, "femto":-15, "ato":-18, "zepto":-21, "yocto":-24}
for _ in range(int(input())):
v, *b = input().split()
if len(b) == 2:
... |
p01787 RLE Replacement | H - RLE Replacement
Problem Statement
In JAG Kingdom, ICPC (Intentionally Compressible Programming Code) is one of the common programming languages. Programs in this language only contain uppercase English letters and the same letters often appear repeatedly in ICPC programs. Thus, programmers in JAG Kingdom prefer t... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p02060 Four Tea | A: four tea
problem
Tea is indispensable for programming contests. Tea has the effect of relieving constant tension [citation needed]
There are N players participating in the contest, so I would like to prepare tea for this number of people. There are four types of tea packages, A, B, C, and D, all of which are the ... | ```python
n,pa,pb,pc,pd,ta,tb,tc,td=map(int,open(0).read().split())
r=range(n+1)
m=1e9
for i in r:
for j in r:
for k in r:
l=0--(n-ta*i-tb*j-tc*k)//td
m=min(m,pa*i+pb*j+pc*k+pd*l*(l>=0))
print(m)
``` |
p02202 Gag | Gag
Segtree has $ N $ of "gags", each with a value of $ V_i $.
Segtree decided to publish all the gags in any order.
Here, the "joy" you get when you publish the $ i $ th gag to the $ j $ th is expressed as $ V_i --j $.
Find the maximum sum of the "joy" you can get.
input
Input is given from standard input in the... | ```python
n = int(input())
v = list(map(int,input().split()))
count = 0
ans = 0
s = -1
while count != n:
ans -= s
s -= 1
count += 1
print(sum(v)-ans)
``` |
p02356 The Number of Windows | For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and $Q$ integers $x_i$ as queries, for each query, print the number of combinations of two integers $(l, r)$ which satisfies the condition: $1 \leq l \leq r \leq N$ and $a_l + a_{l+1} + ... + a_{r-1} + a_r \leq x_i$.
Constraints
* $1 \leq N \leq 10^5$
* $1 ... | ```python
from bisect import bisect_right
def main():
N, Q = map(int, input().split())
a = [-1 for i in range(N)]
sum = [0 for i in range(N + 1)]
for i, val in enumerate(input().split()):
a[i] = int(val)
sum[i + 1] = sum[i] + a[i]
X = list(map(int, input().split()))
# print("DE... |
1015_A. Points in Segments | You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints.
Consider... | ```python
n, m = [int(x) for x in input().split()]
s = set(range(1, m+1))
for _ in range(n):
a, b = [int(x) for x in input().split()]
s -= set(range(a, b+1))
print(len(s))
print(*s)
``` |
1038_E. Maximum Matching | You are given n blocks, each of them is of the form [color_1|value|color_2], where the block can also be flipped to get [color_2|value|color_1].
A sequence of blocks is called valid if the touching endpoints of neighboring blocks have the same color. For example, the sequence of three blocks A, B and C is valid if th... | ```python
def min(a, b):
if a < b:
return a
return b
def max(a,b):
return abs(min(-a,-b))
been = [0 for i in range(4)]
ans = 0
minw = 10**18
degpar = [0 for i in range(4)]
w = [0 for i in range(4)]
gr = [list() for i in range(4)]
rem = [[0 for i in range(4)] for j in range(4)]
def dfs(x, l):
l.a... |
1061_A. Coins | You have unlimited number of coins with values 1, 2, …, n. You want to select some set of coins having the total value of S.
It is allowed to have multiple coins with the same value in the set. What is the minimum number of coins required to get sum S?
Input
The only line of the input contains two integers n and S ... | ```python
n, s = map(int, input().split())
print((s + n - 1) // n)
``` |
1082_G. Petya and Graph | Petya has a simple graph (that is, a graph without loops or multiple edges) consisting of n vertices and m edges.
The weight of the i-th vertex is a_i.
The weight of the i-th edge is w_i.
A subgraph of a graph is some set of the graph vertices and some set of the graph edges. The set of edges must meet the condition... | ```python
class edge(object):
def __init__(self,ne,to,fl):
self.ne=ne
self.to=to
self.fl=fl
def add(x,y,z):
global tot
tot+=1
e.append(edge(he[x],y,z))
he[x]=tot
def addedge(x,y,z):
add(x,y,z)
add(y,x,0)
def bfs():
global deep
deep=[0 for i in range(T+1)]
q=[]
q.append(S)
deep[S]=1
while (len(q)>0... |
1102_B. Array K-Coloring | You are given an array a consisting of n integer numbers.
You have to color this array in k colors in such a way that:
* Each element of the array should be colored in some color;
* For each i from 1 to k there should be at least one element colored in the i-th color in the array;
* For each i from 1 to k al... | ```python
from collections import defaultdict
n,k=map(int,input().split())
arr=list(map(int,input().split()))
temp=[0]*5001
for i in arr:
temp[i]+=1
if(max(temp)>k):
print('NO')
elif(k>n):
print('NO')
else:
print('YES')
d=defaultdict(list)
c=0
t=[0]*n
for i in range(n):
t[i]=arr[... |
1130_B. Two Cakes | Sasha and Dima want to buy two n-tier cakes. Each cake should consist of n different tiers: from the size of 1 to the size of n. Tiers should go in order from the smallest to the biggest (from top to bottom).
They live on the same street, there are 2 ⋅ n houses in a row from left to right. Each house has a pastry shop... | ```python
l2=[]
n=int(input())
l=list(map(int,input().split()))
for i in range(2*n):
l2.append([l[i],i])
l2.sort()
sd,dd=l2[0][1],l2[1][1]
for i in range(2,2*n):
if i%2:
dd+=abs(l2[i][1]-l2[i-2][1])
else:
sd+=abs(l2[i][1]-l2[i-2][1])
print(sd+dd)
``` |
1150_C. Prefix Sum Primes | We're giving away nice huge bags containing number tiles! A bag we want to present to you contains n tiles. Each of them has a single number written on it — either 1 or 2.
However, there is one condition you must fulfill in order to receive the prize. You will need to put all the tiles from the bag in a sequence, in a... | ```python
n=int(input())
l=list(map(int,input().split()))
n1,n2=0,0
for i in l:
if i==1:
n1+=1
else:
n2+=1
r=[]
if n1==0 or n2==0:
r=l
else:
r.append(2)
r.append(1)
n1-=1
n2-=1
while n2!=0:
r.append(2)
n2-=1
while n1!=0:
r.append(1)
n... |
1172_C2. Nauuo and Pictures (hard version) | The only difference between easy and hard versions is constraints.
Nauuo is a girl who loves random picture websites.
One day she made a random picture website by herself which includes n pictures.
When Nauuo visits the website, she sees exactly one picture. The website does not display each picture with equal proba... | ```python
P = 998244353
N, M = map(int, input().split())
A = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
li = sum([A[i]*B[i] for i in range(N)])
di = sum([(A[i]^1)*B[i] for i in range(N)])
X = [1]
SU = li+di
PO = [0] * (5*M+10)
for i in range(-M-5, 2*M+5):
PO[i] = pow((SU+i)%P, P-2, P)
... |
118_E. Bertown roads | Bertown has n junctions and m bidirectional roads. We know that one can get from any junction to any other one by the existing roads.
As there were more and more cars in the city, traffic jams started to pose real problems. To deal with them the government decided to make the traffic one-directional on all the roads,... | ```python
from sys import stdin,setrecursionlimit
import threading
input = lambda: stdin.readline().rstrip("\r\n")
from collections import deque as que
inin = lambda: int(input())
inar = lambda: list(map(int,input().split()))
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwa... |
1209_D. Cow and Snacks | The legendary Farmer John is throwing a huge party, and animals from all over the world are hanging out at his house. His guests are hungry, so he instructs his cow Bessie to bring out the snacks! Moo!
There are n snacks flavors, numbered with integers 1, 2, …, n. Bessie has n snacks, one snack of each flavor. Every g... | ```python
from collections import defaultdict
import sys
import typing
class DSU:
'''
Implement (union by size) + (path halving)
Reference:
Zvi Galil and Giuseppe F. Italiano,
Data structures and algorithms for disjoint set union problems
'''
def __init__(self, n: int = 0) -> None:
... |
1228_C. Primes and Multiplication | Let's introduce some definitions that will be needed later.
Let prime(x) be the set of prime divisors of x. For example, prime(140) = \{ 2, 5, 7 \}, prime(169) = \{ 13 \}.
Let g(x, p) be the maximum possible integer p^k where k is an integer such that x is divisible by p^k. For example:
* g(45, 3) = 9 (45 is divis... | ```python
"""
import math
MOD=1000000007
def powr(n,N):
temp=1
while(N>0):
if(N%2!=0):
temp=(temp*n)%MOD
n=(n*n)%MOD
N=N//2
return (temp%MOD)
x,n=map(int,input().split())
n1=x
L=[]
while(n1%2==0):
L.append(2)
n1=n1//2
for i in range(3,int(math.sqrt(n1))+1,... |
1270_C. Make Good | Let's call an array a_1, a_2, ..., a_m of nonnegative integer numbers good if a_1 + a_2 + ... + a_m = 2⋅(a_1 ⊕ a_2 ⊕ ... ⊕ a_m), where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
For example, array [1, 2, 3, 6] is good, as 1 + 2 + 3 + 6 = 12 = 2⋅ 6 = 2⋅ (1⊕ 2 ⊕ 3 ⊕ 6). A... | ```python
from functools import reduce
from operator import xor
for _ in range(int(input())):
n = int(input())
a = [*map(int, input().split())]
print(2)
print(sum(a) + reduce(xor, a), reduce(xor, a))
``` |
1293_A. ConneR and the A.R.C. Markland-N | [Sakuzyo - Imprinting](https://www.youtube.com/watch?v=55Ca6av1kAY)
A.R.C. Markland-N is a tall building with n floors numbered from 1 to n. Between each two adjacent floors in the building, there is a staircase connecting them.
It's lunchtime for our sensei Colin "ConneR" Neumann Jr, and he's planning for a location... | ```python
t = int(input())
for _ in range(t):
variables = [int(_) for _ in input().split()]
n = variables[0]
s = variables[1]
k = variables[2]
closed = set([int(i) for i in input().split()])
minimum = n
tmp = n
for x in range(s, 0, -1):
if x not in closed:
tmp = abs(... |
1313_A. Fast Food Restaurant | Tired of boring office work, Denis decided to open a fast food restaurant.
On the first day he made a portions of dumplings, b portions of cranberry juice and c pancakes with condensed milk.
The peculiarity of Denis's restaurant is the procedure of ordering food. For each visitor Denis himself chooses a set of dishes... | ```python
import os
import sys
from io import BytesIO, IOBase
def solution(a, b, c):
if a == 0 and b == 0 and c == 0:
print(0)
return
res = 0
comb = ['001', '010', '100', '011', '101', '110', '111']
comb2 = ['01', '10', '11']
a, b, c = sorted([a, b, c])
if a == 0 and b == 0:
... |
1335_E1. Three Blocks Palindrome (easy version) | The only difference between easy and hard versions is constraints.
You are given a sequence a consisting of n positive integers.
Let's define a three blocks palindrome as the sequence, consisting of at most two distinct elements (let these elements are a and b, a can be equal b) and is as follows: [\underbrace{a, a, ... | ```python
T = int(input())
Q = []
# Read all inputs before computing (see last comment, the goal is to print once)
for t in range(T):
N = int(input())
A = [int(_) for _ in input().split()]
Q.append((N, A))
R = []
for N, A in Q:
# Switch the 2 dimensions of the array to maybe prevent cache miss on loo... |
1358_A. Park Lighting | Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | ```python
import math
t=int(input())
while(t>0):
t-=1
n,m=map(int,input().split())
print(math.floor((n*m+1)/2))
``` |
1399_B. Gifts Fixing | You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | ```python
# Gifts Fixing
# https://codeforces.com/problemset/problem/1399/B
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
min_a = min(a)
min_b = min(b)
count = 0
for i in range(n):
diff_a = a[i] - min_a
diff_b = b[i] - m... |
1422_E. Minlexes | Some time ago Lesha found an entertaining string s consisting of lowercase English letters. Lesha immediately developed an unique algorithm for this string and shared it with you. The algorithm is as follows.
Lesha chooses an arbitrary (possibly zero) number of pairs on positions (i, i + 1) in such a way that the foll... | ```python
import sys
s = input().strip()
N = len(s)
if len(s) == 1:
print(1, s[0])
sys.exit()
X = [s[-1], s[-2]+s[-1] if s[-2]!=s[-1] else ""]
Y = [1, 2 if s[-2]!=s[-1] else 0]
for i in range(N-3, -1, -1):
c = s[i]
k1 = c+X[-1]
ng = Y[-1]+1
if ng > 10:
k1 = k1[:5] + "..." + k1[-2:]
i... |
1440_C2. Binary Table (Hard Version) | This is the hard version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem.
You are given a binary table of size n × m. This table consists of symbols 0 and 1.
You can make such operat... | ```python
import sys
input=sys.stdin.readline
def change(x1,x2,x3,y1,y2,y3,ll):
ll[x1][y1]=1-ll[x1][y1]
ll[x2][y2]=1-ll[x2][y2]
#print(x3,y3,ll)
ll[x3][y3]=1-ll[x3][y3]
t=int(input())
while t:
n,m=map(int,input().split())
ll=[]
for i in range(n):
l=list(map(int,input().strip())... |
1467_E. Distinctive Roots in a Tree | You are given a tree with n vertices. Each vertex i has a value a_i associated with it.
Let us root the tree at some vertex v. The vertex v is called a distinctive root if the following holds: in all paths that start at v and end at some other node, all the values encountered are distinct. Two different paths may have... | ```python
import io, os
from collections import Counter, defaultdict, deque
class LazySegmentTree:
def __init__(self, data, default=0, func=max):
_default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self._lazy = [... |
1541_E1. Converging Array (Easy Version) | This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operat... | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
C = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
Q = int(input())
x = int(input())
P = 10 ** 9 + 7
dp = [[0] * 20100 for _ in range(N + 1)]
dp[0][0] = 1
ans = 0
s = x
t = s
for i in range(N):
for j in ran... |
18_B. Platforms | In one one-dimensional world there are n platforms. Platform with index k (platforms are numbered from 1) is a segment with coordinates [(k - 1)m, (k - 1)m + l], and l < m. Grasshopper Bob starts to jump along the platforms from point 0, with each jump he moves exactly d units right. Find out the coordinate of the poin... | ```python
class Platforms:
@classmethod
def read_input(cls):
nums = list(map(int, input('').split()))
return nums[0], nums[1], nums[2], nums[3]
@classmethod
def run(cls):
n, d, m, l = cls.read_input()
end_plat = (n - 1) * m + l
for cur_jump in range(d, (m + 1) * ... |
213_B. Numbers | Furik loves writing all sorts of problems, especially such that he can't solve himself. You've got one of his problems, the one Furik gave to Rubik. And Rubik asks you to solve it.
There is integer n and array a, consisting of ten integers, indexed by numbers from 0 to 9. Your task is to count the number of positive i... | ```python
from math import factorial
dp=[[-1 for i in range (101)] for j in range(101)]
def solve(n,p,a):
if dp[n][p] is not -1:
return dp[n][p]
elif p is 9:
if n>=a[9]:
return 1
else:
return 0
elif p is 0:
ans=0
for i in range(a[0],n):
... |
237_B. Young Table | You've got table a, consisting of n rows, numbered from 1 to n. The i-th line of table a contains ci cells, at that for all i (1 < i ≤ n) holds ci ≤ ci - 1.
Let's denote s as the total number of cells of table a, that is, <image>. We know that each cell of the table contains a single integer from 1 to s, at that all ... | ```python
n = int(input())
I = lambda : map(int,input().split())
li = list (I())
dd = {}
arr = [ [0 for i in range(51)] for j in range(51) ]
l2 = [ ]
c=0
for i in range (1,n+1) :
l1 = list(I())
l2 = l2 + l1
c = c + len(l1)
for j in range(li[i-1]) :
arr[i][j+1] = l1[j]
dd[l1[j]] = [i , j... |
285_E. Positions in Permutations | Permutation p is an ordered set of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. We'll denote the i-th element of permutation p as pi. We'll call number n the size or the length of permutation p1, p2, ..., pn.
We'll call position i (1 ≤ i ≤ n) in permutation p1, p... | ```python
mod=10**9+7
n,k=map(int,input().split())
A=[0]*(n+1)
B=[0]*(n+1)
C=[0]*(n+1)
F=[0]*(n+1)
G=[0]*(n+1)
F[0]=G[0]=1
for i in range(1,n+1):
G[i]=F[i]=F[i-1]*i%mod
G[i]=pow(F[i],(mod-2),mod)
for i in range(0,n):
if i*2>n:
break
B[i]=(F[n-i]*G[i]*G[n-i*2])%mod
for i in range(0,n//2+1):
for j in range(0,n/... |
356_C. Compartments | A team of students from the city S is sent to the All-Berland Olympiad in Informatics. Traditionally, they go on the train. All students have bought tickets in one carriage, consisting of n compartments (each compartment has exactly four people). We know that if one compartment contain one or two students, then they ge... | ```python
n = int(input())
A = [0, 0, 0, 0, 0]
B = map(int, input().split(' '))
for i in B:
A[i] += 1
res = min(A[1], A[2])
A[1] -= res
A[2] -= res
A[3] += res
res += 2 * (A[1] // 3)
A[3] += A[1] // 3
A[1] %= 3
res += 2 * (A[2] // 3)
A[3] += 2 * (A[2] // 3)
A[2] %= 3
assert(A[1] == 0 or A[2] == 0)
if (A[1] == 1)... |
37_B. Computer Game | Vasya’s elder brother Petya loves playing computer games. In one of his favourite computer games Petya reached the final level where a fight with the boss take place.
While playing the game Petya found spell scrolls and now he is about to use them. Let’s describe the way fighting goes on this level:
1) The boss has t... | ```python
class Scroll:
def __init__(self, id, power, damage):
self.id = id
self.power = power
self.damage = damage
self.active = False
num_scrolls, boss_max, regenerate = map(int, input().split())
scrolls = [Scroll(i+1, *map(int, input().split())) for i in range(num_scrolls)]
scrolls.sort(key = lambda scroll... |
400_A. Inna and Choose Options | There always is something to choose from! And now, instead of "Noughts and Crosses", Inna choose a very unusual upgrade of this game. The rules of the game are given below:
There is one person playing the game. Before the beginning of the game he puts 12 cards in a row on the table. Each card contains a character: "X"... | ```python
n = int(input())
a = [1, 2, 3, 4, 6, 12]
for i in range(0, n):
s = str(input())
ans = [False for x in range(0, 6)]
nans = 0;
for i in range (0, 6):
for j in range (0, 12 // a[i]):
good = True
for k in range(0, a[i]):
if s[k * 12 // a[i] + j] is 'O':
good = False
break
if good:
... |
427_B. Prison Transfer | The prison of your city has n prisoners. As the prison can't accommodate all of them, the city mayor has decided to transfer c of the prisoners to a prison located in another city.
For this reason, he made the n prisoners to stand in a line, with a number written on their chests. The number is the severity of the crim... | ```python
a=list(map(int,input().split()[1:]))
b=list(map(int,input().split()))
m=0
c=0
for i in b:
if i>a[0]:
if not c<a[1]:
m+=c-a[1]+1
c=0
else:c+=1
print(m+c-a[1]+1 if c>=a[1]else m)
``` |
472_A. Design Tutorial: Learn from Math | One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | ```python
def isprime(k):
m=0
for j in range(2,k):
if k%j==0:
m=m+1
if m==0:
return 0
else:
return 1
n=int(input())
for i in range(4,n-3):
if isprime(i)==1 and isprime(n-i)==1:
print(i,n-i)
exit()
``` |
496_B. Secret Combination | You got a box with a combination lock. The lock has a display showing n digits. There are two buttons on the box, each button changes digits on the display. You have quickly discovered that the first button adds 1 to all the digits (all digits 9 become digits 0), and the second button shifts all the digits on the displ... | ```python
n = int(input())
s = input()
i = 0
min_ = int(s)
s1 = s
i = 0
while (i <= n):
s = s[1::] + s[0]
if (int(s[0]) != 0):
g = (9 - int(s[0])) + 1
s2 = ''
for j in range(len(s)):
h = int(s[j]) + g
if (h >= 10):
h = abs(10 - h)
s2 = ... |
547_A. Mike and Frog | Mike has a frog and a flower. His frog is named Xaniar and his flower is named Abol. Initially(at time 0), height of Xaniar is h1 and height of Abol is h2. Each second, Mike waters Abol and Xaniar.
<image>
So, if height of Xaniar is h1 and height of Abol is h2, after one second height of Xaniar will become <image> an... | ```python
def main():
m, tt = int(input()), [0] * 4
for i in 0, 2:
h, a = map(int, input().split())
x, y = map(int, input().split())
ha = (h, a)
for t in range(1, m * 2):
h = (h * x + y) % m
if h in ha:
if h == ha[0]:
if... |
595_A. Vitaly and Night | One day Vitaly was going home late at night and wondering: how many people aren't sleeping at that moment? To estimate, Vitaly decided to look which windows are lit in the house he was passing by at that moment.
Vitaly sees a building of n floors and 2·m windows on each floor. On each floor there are m flats numbered ... | ```python
etaj, kvart = map(int, input().split())
Okna = []
notsleep = 0
for i in range(0, etaj):
Okna.append(list(map(int, input().split())))
for i in range(0, etaj):
for j in range(0, (kvart*2)-1, 2):
if Okna[i][j] or Okna[i][j+1] == 1:
notsleep += 1
print(notsleep)
``` |
616_D. Longest k-Good Segment | The array a with n integers is given. Let's call the sequence of one or more consecutive elements in a segment. Also let's call the segment k-good if it contains no more than k different values.
Find any longest k-good segment.
As the input/output can reach huge size it is recommended to use fast input/output methods... | ```python
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=en... |
689_B. Mike and Shortcuts | Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of n intersections numbered from 1 to n. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking... | ```python
def amount_of_total_energy(n, a):
dist = [-1] * n
dist[0] = 0
pos = [0]
for u in pos:
for v in [u - 1, u + 1, a[u] - 1]:
if v >= 0 and v < n and dist[v] == -1:
dist[v] = dist[u] + 1
pos.append(v)
return dist
n = int(input())
a = list(map(int,input().split()... |
731_F. Video Cards | Little Vlad is fond of popular computer game Bota-2. Recently, the developers announced the new add-on named Bota-3. Of course, Vlad immediately bought only to find out his computer is too old for the new game and needs to be updated.
There are n video cards in the shop, the power of the i-th video card is equal to in... | ```python
n = int(input())
s = list(map(int, input().split()))
h = max(s)
ss = [0] * (h + 1)
for i in s:
ss[i] += 1
f, x = [0] * h, 0
for j in reversed(ss):
x += j
f.append(x)
f.reverse()
res = []
for i, x in enumerate(ss):
if x:
summ, x = 0, f[i]
for j in range(i, h + 1, i):
... |
756_A. Pavel and barbecue | Pavel cooks barbecue. There are n skewers, they lay on a brazier in a row, each on one of n positions. Pavel wants each skewer to be cooked some time in every of n positions in two directions: in the one it was directed originally and in the reversed direction.
Pavel has a plan: a permutation p and a sequence b1, b2, ... | ```python
import sys
input = sys.stdin.readline
n = int(input())
permutation = list(map(int, input().split()))
go = set(range(1,n+1))
reached = set()
ans = 0
while go:
x = go.pop()
while x not in reached:
reached.add(x)
x = permutation[x-1]
if x in go:
go.remove(x)
ans += 1
if ans == 1:
ans ... |
777_B. Game of Credit Cards | After the fourth season Sherlock and Moriary have realized the whole foolishness of the battle between them and decided to continue their competitions in peaceful game of Credit Cards.
Rules of this game are simple: each player bring his favourite n-digit credit card. Then both players name the digits written on their... | ```python
n = int(input())
s = list(map(int, list(input())))
m = map(int, list(input()))
ma = [0] * 10
for dig in m:
ma[dig] += 1
ma2 = list(ma)
min_f = 0
for nu in s:
for x in range(nu, 10):
if ma[x] > 0:
ma[x] -= 1
break
else:
min_f += 1
for z in range(le... |
822_B. Crossword solving | Erelong Leha was bored by calculating of the greatest common divisor of two factorials. Therefore he decided to solve some crosswords. It's well known that it is a very interesting occupation though it can be very difficult from time to time. In the course of solving one of the crosswords, Leha had to solve a simple ta... | ```python
n, m = map(int, input().split())
s = input()
t = input()
res = 1001
res_ind = []
b = 0
e = len(s)
while b <= len(t)-len(s):
sr = t[b:e]
k = 0
ind = []
for i in range(len(s)):
if s[i] != sr[i]:
k += 1
else:
ind.append(i+1)
if k < res:
res = ... |
847_G. University Classes | There are n student groups at the university. During the study day, each group can take no more than 7 classes. Seven time slots numbered from 1 to 7 are allocated for the classes.
The schedule on Monday is known for each group, i. e. time slots when group will have classes are known.
Your task is to determine the mi... | ```python
n = int(input())
schedules = []
for i in range(n):
schedules.append(input())
minimum = 0
for i in range(7):
activeSlots = 0
for j in range(n):
activeSlots += int(schedules[j][i])
if activeSlots > minimum:
minimum = activeSlots
print(minimum)
``` |
869_B. The Eternal Immortality | Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every a! years. Here a! denotes ... | ```python
# Main maut ko takiya, aur kafan ko chaadar banakkar audhta hoon!
a,b=input().split()
if a[:-1]!=b[:-1]:
print("0")
else:
ans=1
for i in range(int(a[-1])+1,int(b[-1])+1):
ans*=i
ans=ans%10
print(ans)
``` |
895_A. Pizza Separation | Students Vasya and Petya are studying at the BSU (Byteland State University). At one of the breaks they decided to order a pizza. In this problem pizza is a circle of some radius. The pizza was delivered already cut into n pieces. The i-th piece is a sector of angle equal to ai. Vasya and Petya want to divide all piece... | ```python
n=int(input())
a=list(map(int,input().split()))
print(2*min(abs(180-sum(a[l:r])) for l in range(n) for r in range(l,n)))
``` |
916_B. Jamie and Binary Sequence (changed after round) | Jamie is preparing a Codeforces round. He has got an idea for a problem, but does not know how to solve it. Help him write a solution to the following problem:
Find k integers such that the sum of two to the power of each number equals to the number n and the largest integer in the answer is as small as possible. As t... | ```python
n, k = map(int, input().split())
cnt = [0] * 200010
ans = ''
for i in range(64):
if (n >> i)&1:
k -= 1
cnt[i] = 1;
if k < 0:
print("No")
else:
print("Yes")
for i in range(64, -64, -1):
if k >= cnt[i]:
cnt[i - 1] += cnt[i] * 2
k -= cnt[i]
cnt[i] = 0
else: break
for i... |
939_C. Convenient For Everybody | In distant future on Earth day lasts for n hours and that's why there are n timezones. Local times in adjacent timezones differ by one hour. For describing local time, hours numbers from 1 to n are used, i.e. there is no time "0 hours", instead of it "n hours" is used. When local time in the 1-st timezone is 1 hour, lo... | ```python
# Problem D
n = int(input())
inp = input().split(" ")
people = [ int(x) for x in inp ]
inp = input().split(" ")
s, f = int(inp[0]), int(inp[1])
r = f-s#+1 # tamaño de la ventana
max_s, idx_max = sum( people[i] for i in range(r) ), 0
sum_ac = max_s
res = (n-idx_max+s)%n if (n-idx_max+s)%n else n
for j in rang... |
991_F. Concise and clear | Vasya is a regular participant at programming contests and is already experienced in finding important sentences in long statements. Of course, numbers constraints are important — factorization of a number less than 1000000 is easier than of a number less than 1000000000. However, sometimes it's hard to understand the ... | ```python
import math
import itertools
pow10 = [1]
for i in range(10):
pow10.append(pow10[-1] * 10)
def getlen(x):
"""length of the decimal representation of integer x"""
return int(math.log10(x)) + 1
class ShortestRepresentation:
def __init__(self, n):
self.n = n
self._m = {}
... |
p02621 AtCoder Beginner Contest 172 - Calc | Given an integer a as input, print the value a + a^2 + a^3.
Constraints
* 1 \leq a \leq 10
* a is an integer.
Input
Input is given from Standard Input in the following format:
a
Output
Print the value a + a^2 + a^3 as an integer.
Examples
Input
2
Output
14
Input
10
Output
1110 | ```python
a= int(input())
eq= a+(a**2)+(a**3)
print(eq)
``` |
p02752 Social Infrastructure Information Systems Division Hitachi Programming Contest 2020 - Preserve Diameter | We have a tree G with N vertices numbered 1 to N. The i-th edge of G connects Vertex a_i and Vertex b_i.
Consider adding zero or more edges in G, and let H be the graph resulted.
Find the number of graphs H that satisfy the following conditions, modulo 998244353.
* H does not contain self-loops or multiple edges.
* ... | ```python
import sys
input = sys.stdin.readline
mod=998244353
N=int(input())
E=[[] for i in range(N+1)]
for i in range(N-1):
x,y=map(int,input().split())
E[x].append(y)
E[y].append(x)
Q=[1]
D=[-1]*(N+1)
D[1]=0
while Q:
x=Q.pop()
for to in E[x]:
if D[to]==-1:
D[to]=D[x]+1
... |
p02887 AtCoder Beginner Contest 143 - Slimes | There are N slimes lining up from left to right. The colors of these slimes will be given as a string S of length N consisting of lowercase English letters. The i-th slime from the left has the color that corresponds to the i-th character of S.
Adjacent slimes with the same color will fuse into one larger slime withou... | ```python
n=int(input())
cnt=0
s=input()
for i in range(1,n):
if s[i]!=s[i-1]:
cnt+=1
print(cnt+1)
``` |
p03022 AtCoder Grand Contest 034 - RNG and XOR | Snuke found a random number generator. It generates an integer between 0 and 2^N-1 (inclusive). An integer sequence A_0, A_1, \cdots, A_{2^N-1} represents the probability that each of these integers is generated. The integer i (0 \leq i \leq 2^N-1) is generated with probability A_i / S, where S = \sum_{i=0}^{2^N-1} A_i... | ```python
# Σ(i ^ j = k) ai * bj = ckという形で式が表されるとき
# fwht(a)*fwht(b)=fwht(c)が成り立ち高速化できる
# すごく必死に考えると
# a = [p0 p1 p2 ... p2^N-1]
# b = [x0 x1 x2 ... x2^N-1]
# c = [2^N-1 -1 -1 -1 .... -1]
# とするとうまいことaとcに変数が入らない形になるのでfwht(c)/fwht(a)を計算し
# fwht(b)がわかるのでこれを逆変換すればbが求められる
# なお逆変換は b = fwht(fwht(b)) / 要素数で求められる、なぜかは知らない
# また... |
p03162 Educational DP Contest - Vacation | Taro's summer vacation starts tomorrow, and he has decided to make plans for it now.
The vacation consists of N days. For each i (1 \leq i \leq N), Taro will choose one of the following activities and do it on the i-th day:
* A: Swim in the sea. Gain a_i points of happiness.
* B: Catch bugs in the mountains. Gain b_i... | ```python
n=int(input())
a,b,c=map(int,input().split())
for _ in range(1,n):
aa,bb,cc=map(int,input().split())
a,b,c=aa+max(b,c),bb+max(a,c),cc+max(a,b)
print(max(a,b,c))
``` |
p03305 SoundHound Inc. Programming Contest 2018 -Masters Tournament- - Saving Snuuk | Kenkoooo is planning a trip in Republic of Snuke. In this country, there are n cities and m trains running. The cities are numbered 1 through n, and the i-th train connects City u_i and v_i bidirectionally. Any city can be reached from any city by changing trains.
Two currencies are used in the country: yen and snuuk.... | ```python
import math, string, itertools, fractions, collections, re, array, bisect, sys, random, time, copy, functools
from heapq import heappush, heappop, heappushpop, heapify, heapreplace
N, M, S, T = [int(_) for _ in input().split()]
UVAB = [[int(_) for _ in input().split()] for _ in range(M)]
G1 = collections.def... |
p03465 AtCoder Grand Contest 020 - Median Sum | You are given N integers A_1, A_2, ..., A_N.
Consider the sums of all non-empty subsequences of A. There are 2^N - 1 such sums, an odd number.
Let the list of these sums in non-decreasing order be S_1, S_2, ..., S_{2^N - 1}.
Find the median of this list, S_{2^{N-1}}.
Constraints
* 1 \leq N \leq 2000
* 1 \leq A_i \... | ```python
n = int(input())
a = list(map(int, input().split()))
d = (sum(a)+1)//2
c = 1
for x in a:
c |= c << x
c >>= d
for i in range(d+5):
if c & (1 << i):
print(d+i)
break
``` |
p03625 AtCoder Beginner Contest 071 - Make a Rectangle | We have N sticks with negligible thickness. The length of the i-th stick is A_i.
Snuke wants to select four different sticks from these sticks and form a rectangle (including a square), using the sticks as its sides. Find the maximum possible area of the rectangle.
Constraints
* 4 \leq N \leq 10^5
* 1 \leq A_i \leq ... | ```python
N = int(input())
A = sorted([int(_) for _ in input().split()], reverse=True)
e = []
pre = 0
for i in range(N):
if pre == A[i]:
e.append(A[i])
if len(e) >= 2: break
pre = 0
else:
pre = A[i]
if len(e) < 2: print(0)
else: print(e[0] * e[1])
``` |
p03785 AtCoder Grand Contest 011 - Airport Bus | Every day, N passengers arrive at Takahashi Airport. The i-th passenger arrives at time T_i.
Every passenger arrived at Takahashi airport travels to the city by bus. Each bus can accommodate up to C passengers. Naturally, a passenger cannot take a bus that departs earlier than the airplane arrives at the airport. Also... | ```python
N,C,K=map(int,input().split())
T=[int(input()) for i in range(N)]
T.sort()
S=[[T[0]]]
t=T[0]
k=0
for i in range(1,N):
if T[i]<=t+K and len(S[k])<C:
S[k].append(T[i])
else:
k+=1
S.append([T[i]])
t=T[i]
print(len(S))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.