name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1419_B. Stairs | Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.
A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase ha... | ```python
ty=[1]
p=2
while(True):
p=p*2
ty.append(p-1)
if(p>10**18):
break
t=int(input())
for j in range(0,t):
x=int(input())
s=0
c=0
for o in ty:
s=s+((o)*(o+1))//2
if(s<=x):
c=c+1
else:
break
print(c)
``` |
1437_B. Reverse Binary Strings | You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's.
String s has exactly n/2 zeroes and n/2 ones (n is even).
In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string.
What is the minimum number of... | ```python
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#New Imports
def solution():
n = int(input())
s = input()
val = s.count('10')
a1 = n//2 - val
val = s.count('01')
a2 = n//2 - val
print(min(a1,a2))
return
def main():
testcases = 1
testcases... |
1461_F. Mathematical Expression | Barbara was late for her math class so as a punishment the teacher made her solve the task on a sheet of paper. Barbara looked at the sheet of paper and only saw n numbers a_1, a_2, …, a_n without any mathematical symbols. The teacher explained to Barbara that she has to place the available symbols between the numbers ... | ```python
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
ops = input().strip()
if len(ops) == 1:
print(ops.join(map(str, a)))
elif '+' in ops and '*' in ops:
seqs = [[a[0]]]
output = []
# split into seqs of all 0's or non 0's
# every seq in seqs is a li... |
1487_A. Arena | n heroes fight against each other in the Arena. Initially, the i-th hero has level a_i.
Each minute, a fight between two different heroes occurs. These heroes can be chosen arbitrarily (it's even possible that it is the same two heroes that were fighting during the last minute).
When two heroes of equal levels fight,... | ```python
tests = int(input())
for t in range(tests):
n = int(input())
heroes = list(map(int, input().split(' ')))
m = min(heroes)
print(sum([1 for x in heroes if x > m]))
``` |
1538_C. Number of Pairs | You are given an array a of n integers. Find the number of pairs (i, j) (1 ≤ i < j ≤ n) where the sum of a_i + a_j is greater than or equal to l and less than or equal to r (that is, l ≤ a_i + a_j ≤ r).
For example, if n = 3, a = [5, 1, 2], l = 4 and r = 7, then two pairs are suitable:
* i=1 and j=2 (4 ≤ 5 + 1 ≤ 7... | ```python
# Author: Javier Bórquez
import os
import sys
import bisect
def main():
fastReadInt = sys.stdin.buffer.readline
def fastReadStr(): return sys.stdin.buffer.readline().decode('utf-8').strip()
def fastWrite(ans): return sys.stdout.buffer.write(str(str(ans) + "\n").encode('utf-8'))
def fastWriteList(ans... |
231_E. Cactus | A connected undirected graph is called a vertex cactus, if each vertex of this graph belongs to at most one simple cycle.
A simple cycle in a undirected graph is a sequence of distinct vertices v1, v2, ..., vt (t > 2), such that for any i (1 ≤ i < t) exists an edge between vertices vi and vi + 1, and also exists an ed... | ```python
from collections import defaultdict
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
... |
257_D. Sum | Vasya has found a piece of paper with an array written on it. The array consists of n integers a1, a2, ..., an. Vasya noticed that the following condition holds for the array ai ≤ ai + 1 ≤ 2·ai for any positive integer i (i < n).
Vasya wants to add either a "+" or a "-" before each number of array. Thus, Vasya will ge... | ```python
#!/usr/bin/python3
n = int(input())
a = list(map(int, input().split()))
s = a[-1]
ans = ['+']
for v in reversed(a[:-1]):
if s > 0:
s -= v
ans.append('-')
else:
s += v
ans.append('+')
if 0 <= s <= a[-1]:
print(''.join(reversed(ans)))
else:
s = -a[-1]
ans = [... |
32_D. Constellation | A star map in Berland is a checked field n × m squares. In each square there is or there is not a star. The favourite constellation of all Berland's astronomers is the constellation of the Cross. This constellation can be formed by any 5 stars so, that for some integer x (radius of the constellation) the following is t... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, k = map(int, input().split())
a = [tuple(map(lambda c: c == '*', input().rstrip())) for _ in range(n)]
cnt = [0] * 400
for i in range(1, n - 1):
for j in range(1, m - 1):
... |
351_B. Jeff and Furik | Jeff has become friends with Furik. Now these two are going to play one quite amusing game.
At the beginning of the game Jeff takes a piece of paper and writes down a permutation consisting of n numbers: p1, p2, ..., pn. Then the guys take turns to make moves, Jeff moves first. During his move, Jeff chooses two adjace... | ```python
from sys import *
n=int(stdin.readline().strip())
s1=stdin.readline().strip()
a=list(map(int,s1.split()))
if n==1:
print('0')
else:
x=0
n0=1
while n0<n:
n0=n0*2
b=[0]*(2*n0+10)
'''for i in range (n-1):
for j in range (i+1,n):
if a[i]>a[j]:
... |
420_A. 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
'''input
XO
'''
s = input()
if all(s[x] == s[~x] for x in range(len(s)//2)):
if any(y not in "AHIMOTUVWXY" for y in s[:len(s)//2+1]):
print("NO")
else:
print("YES")
else:
print("NO")
``` |
490_E. Restoring Increasing Sequence | Peter wrote on the board a strictly increasing sequence of positive integers a1, a2, ..., an. Then Vasil replaced some digits in the numbers of this sequence by question marks. Thus, each question mark corresponds to exactly one lost digit.
Restore the the original sequence knowing digits remaining on the board.
Inpu... | ```python
def solve(s, t, i, l):
if i == l:
return False
if s[i] == "?":
if solve(s, t, i + 1, l):
s[i] = t[i]
return True
elif t[i] == "9":
return False
s[i] = nxt[t[i]]
for j in range(i, l):
if s[j] == "?":
... |
514_E. Darth Vader and Tree | When Darth Vader gets bored, he sits down on the sofa, closes his eyes and thinks of an infinite rooted tree where each node has exactly n sons, at that for each node, the distance between it an its i-th left child equals to di. The Sith Lord loves counting the number of nodes in the tree that are at a distance at most... | ```python
# fast io
from sys import stdin
_data = iter(stdin.read().split('\n'))
input = lambda: next(_data)
N = 101
MOD = 1000000007
def mul_vec_mat(v, a):
c = [0] * N
for i in range(N):
c[i] = sum(a[j][i] * v[j] % MOD for j in range(N)) % MOD
return c
def mul_vec_sparse_mat(v, a):
c = [0] *... |
569_B. Inventory | Companies always have a lot of equipment, furniture and other things. All of them should be tracked. To do this, there is an inventory number assigned with each item. It is much easier to create a database by using those numbers and keep the track of everything.
During an audit, you were surprised to find out that the... | ```python
n = int(input())
fix = list()
factors = set(range(1, n + 1))
for i in map(int, input().split()):
if i in factors:
factors.remove(i)
fix.append(i)
else:
fix.append(None)
print(' '.join(str(factors.pop()) if i is None else str(i) for i in fix))
``` |
631_D. Messenger | Each employee of the "Blake Techologies" company uses a special messaging app "Blake Messenger". All the stuff likes this app and uses it constantly. However, some important futures are missing. For example, many users want to be able to search through the message history. It was already announced that the new feature ... | ```python
def ziped(a):
p = []
for i in a:
x = int(i.split('-')[0])
y = i.split('-')[1]
if len(p) > 0 and p[-1][1] == y:
p[-1][0] += x
else:
p.append([x, y])
return p
def solve(a, b , c):
ans = 0
if len(b) == 1:
for token ... |
660_B. Seating On Bus | Consider 2n rows of the seats in a bus. n rows of the seats on the left and n rows of the seats on the right. Each row can be filled by two people. So the total capacity of the bus is 4n.
Consider that m (m ≤ 4n) people occupy the seats in the bus. The passengers entering the bus are numbered from 1 to m (in the order... | ```python
n,m = map(int,input().split())
for k in range(1,2*n +1):
num = 2 *n +k
if num <= m:
print(num, end=" ")
num = k
if num <= m:
print(num, end=" ")
``` |
74_C. Chessboard Billiard | Let's imagine: there is a chess piece billiard ball. Its movements resemble the ones of a bishop chess piece. The only difference is that when a billiard ball hits the board's border, it can reflect from it and continue moving.
More formally, first one of four diagonal directions is chosen and the billiard ball moves ... | ```python
import math
n,m=map(int,input().split())
print(math.gcd(n-1,m-1)+1)
``` |
773_B. Dynamic Problem Scoring | Vasya and Petya take part in a Codeforces round. The round lasts for two hours and contains five problems.
For this round the dynamic problem scoring is used. If you were lucky not to participate in any Codeforces round with dynamic problem scoring, here is what it means. The maximum point value of the problem depends... | ```python
import sys
inf = 10**9 + 7
def solve():
n = int(sys.stdin.readline())
v = [int(vi) for vi in sys.stdin.readline().split()] # Vesya
p = [int(pi) for pi in sys.stdin.readline().split()] # Petya
cnt = [0]*5
for i in range(5):
if v[i] != -1:
cnt[i] += 1
if p[i]... |
798_A. Mike and palindrome | Mike has a string s consisting of only lowercase English letters. He wants to change exactly one character from the string so that the resulting one is a palindrome.
A palindrome is a string that reads the same backward as forward, for example strings "z", "aaa", "aba", "abccba" are palindromes, but strings "codeforc... | ```python
import sys
import math
import itertools
import collections
def getdict(n):
d = {}
if type(n) is list or type(n) is str:
for i in n:
if i in d:
d[i] += 1
else:
d[i] = 1
else:
for i in range(n):
t = ii()
... |
818_C. Sofa Thief | Yet another round on DecoForces is coming! Grandpa Maks wanted to participate in it but someone has stolen his precious sofa! And how can one perform well with such a major loss?
Fortunately, the thief had left a note for Grandpa Maks. This note got Maks to the sofa storehouse. Still he had no idea which sofa belongs ... | ```python
import sys
from collections import defaultdict as dd
from collections import deque
pl=1
from math import *
import copy
#sys.setrecursionlimit(10**6)
if pl:
input=sys.stdin.readline
def li():
return [int(xxx) for xxx in input().split()]
def fi():
return int(input())
def si():
return list(input().rstrip()... |
864_B. Polycarp and Letters | Polycarp loves lowercase letters and dislikes uppercase ones. Once he got a string s consisting only of lowercase and uppercase Latin letters.
Let A be a set of positions in the string. Let's call it pretty if following conditions are met:
* letters on positions from A in the string are all distinct and lowercase; ... | ```python
import re
input()
print(max(map(lambda s: len(set(s)), re.split('[A-Z]', input()))))
``` |
88_A. Chord | Vasya studies music.
He has learned lots of interesting stuff. For example, he knows that there are 12 notes: C, C#, D, D#, E, F, F#, G, G#, A, B, H. He also knows that the notes are repeated cyclically: after H goes C again, and before C stands H. We will consider the C note in the row's beginning and the C note aft... | ```python
# Problem: 88A
# Time Created: August 10(Monday) 2020 || 11:37:58
#>-------------------------<#
import sys
input = sys.stdin.readline
#>-------------------------<#
from itertools import permutations
# Helper Functions. -> Don't cluster your code.
def check_chord(tup):
notes = ['C', 'C#', 'D', 'D#', 'E... |
912_D. Fishes | While Grisha was celebrating New Year with Ded Moroz, Misha gifted Sasha a small rectangular pond of size n × m, divided into cells of size 1 × 1, inhabited by tiny evil fishes (no more than one fish per cell, otherwise they'll strife!).
The gift bundle also includes a square scoop of size r × r, designed for fishing.... | ```python
n, m, r, k = map(int, input().split())
def count(y, x):
minx = max(0, x-(r-1))
maxx = min(m-1-(r-1), x)
miny = max(0, y-(r-1))
maxy = min(n-1-(r-1), y)
res = (maxy-miny+1)*(maxx-minx+1)
return res
#X = [[0]*m for i in range(n)]
#for i in range(n):
#for j in range(m):
#X[i... |
934_D. A Determined Cleanup | In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric... | ```python
p, k = input().split()
p, k = int(p), int(k)
s = k - 1
ls = [0]
while s < p:
ls.append(0)
ls.append(0)
s = s * k * k + k - 1
n = len(ls)
for i in range(n):
if (i & 1) == 0:
ls[i] = k - 1
res = s - p
for i in range(n):
t = res % k
if i & 1:
ls[i] += t
else:
l... |
988_C. Equal Sums | You are given k sequences of integers. The length of the i-th sequence equals to n_i.
You have to choose exactly two sequences i and j (i ≠ j) such that you can remove exactly one element in each of them in such a way that the sum of the changed sequence i (its length will be equal to n_i - 1) equals to the sum of the... | ```python
k = int(input())
arr = []
for _ in range(k):
n = int(input())
arr.append(list(map(int,input().split())))
d = {}
for i in range(k):
s = sum(arr[i])
used = set()
for j,c in enumerate(arr[i]):
if c in used:
continue
used.add(c)
if s-c in d:
prin... |
p02595 AtCoder Beginner Contest 174 - Distance | We have N points in the two-dimensional plane. The coordinates of the i-th point are (X_i,Y_i).
Among them, we are looking for the points such that the distance from the origin is at most D. How many such points are there?
We remind you that the distance between the origin and the point (p, q) can be represented as \... | ```python
N, D = map(int, input().split())
P = [tuple(map(int, input().split())) for i in range(N)]
print(sum([p * p + q * q <= D * D for p, q in P]))
``` |
p02726 AtCoder Beginner Contest 160 - Line++ | We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:
* For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.
* There is an edge between Vertex X and Vertex Y.
For each k=1,2,...,N-1, solve the problem below:
* Find the number of pairs of integers (i,j) (1 \leq i... | ```python
n,x,y = map(int, input().split())
x = x-1
y = y-1
k=[0]*n
for i in range(n-1):
for j in range(i+1,n):
m = min(j-i,abs(x-i)+1+abs(y-j))
k[m] += 1
for i in range(1,n):
print(k[i])
``` |
p02993 AtCoder Beginner Contest 131 - Security | The door of Snuke's laboratory is locked with a security code.
The security code is a 4-digit number. We say the security code is hard to enter when it contains two consecutive digits that are the same.
You are given the current security code S. If S is hard to enter, print `Bad`; otherwise, print `Good`.
Constraint... | ```python
S=input()
for i in range(3):
if S[i]==S[i+1]:
print('Bad')
exit(0)
print('Good')
``` |
p03134 Yahoo Programming Contest 2019 - Pass | There are N Snukes lining up in a row. You are given a string S of length N. The i-th Snuke from the front has two red balls if the i-th character in S is `0`; one red ball and one blue ball if the i-th character in S is `1`; two blue balls if the i-th character in S is `2`.
Takahashi has a sequence that is initially ... | ```python
s = input()
n = len(s)
red = [0]
blue = [0]
mod = 998244353
red = [-1]*(2*n)
blue = [-1]*(2*n)
cntr = 0
cntb = 0
for i in range(n):
cntr = max(cntr,i)
cntb = max(cntb,i)
if s[i] == "0":
red[cntr] = 1
red[cntr+1] = 1
cntr += 2
if s[i] == "1":
red[cntr] = 1
cntr += 1
blue[cntb] =... |
p03279 AtCoder Regular Contest 101 - Robots and Exits | There are N robots and M exits on a number line. The N + M coordinates of these are all integers and all distinct. For each i (1 \leq i \leq N), the coordinate of the i-th robot from the left is x_i. Also, for each j (1 \leq j \leq M), the coordinate of the j-th exit from the left is y_j.
Snuke can repeatedly perform ... | ```python
from bisect import bisect
from collections import defaultdict
class Bit:
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
self.depth = n.bit_length()
def sum(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
... |
p03434 AtCoder Beginner Contest 088 - Card Game for Two | We have N cards. A number a_i is written on the i-th card.
Alice and Bob will play a game using these cards. In this game, Alice and Bob alternately take one card. Alice goes first.
The game ends when all the cards are taken by the two players, and the score of each player is the sum of the numbers written on the cards... | ```python
input()
card=sorted(map(int,input().split()))[::-1]
print(sum(card[::2])-sum(card[1::2]))
``` |
p03593 CODE FESTIVAL 2017 qual A - Palindromic Matrix | We have an H-by-W matrix. Let a_{ij} be the element at the i-th row from the top and j-th column from the left. In this matrix, each a_{ij} is a lowercase English letter.
Snuke is creating another H-by-W matrix, A', by freely rearranging the elements in A. Here, he wants to satisfy the following condition:
* Every ro... | ```python
from collections import Counter
H, W = map(int, input().split())
cntA = Counter()
for _ in range(H):
cntA += Counter(list(input()))
four = (H // 2) * (W // 2)
for a, c in cntA.items():
if four <= 0:
break
while c >= 4 and four > 0:
c -= 4
four -= 1
cntA[a] = c
if fou... |
p03914 CODE FESTIVAL 2016 Final - Road of the King | There are N towns in Takahashi Kingdom. They are conveniently numbered 1 through N.
Takahashi the king is planning to go on a tour of inspection for M days. He will determine a sequence of towns c, and visit town c_i on the i-th day. That is, on the i-th day, he will travel from his current location to town c_i. If he... | ```python
mod=10**9+7
N,M=map(int,input().split())
dp=[[0 for i in range(N+1)] for j in range(N+1)]
dp[N][N]=1
for i in range(M-1,-1,-1):
for k in range(1,N+1):
for j in range(k,N+1):
if j==k:
if j<N:
dp[j][k]=(j*dp[j][k]+(N-j)*dp[j+1][k])%mod
... |
p00016 Treasure Hunt | When a boy was cleaning up after his grand father passing, he found an old paper:
<image>
In addition, other side of the paper says that "go ahead a number of steps equivalent to the first integer, and turn clockwise by degrees equivalent to the second integer".
His grand mother says that Sanbonmatsu was standing ... | ```python
import math
def calc(x, y, r, d, nd):
x = x + r * math.cos(math.radians(d))
y = y + r * math.sin(math.radians(d))
d -= nd
return x, y, d
x = y = 0
d = 90
while True:
r, nd = map(int, input().split(","))
if r == nd == 0: break
x, y, d = calc(x, y, r, d, nd)
print(int(x))
print(int(y))
``` |
p00148 Candy and Class Flag | In Group C of the 3rd year, we decided to use the "class flag" used at the sports festival on November 10, 2007 at future class reunions. So, in order to decide which students to keep the "class flag", I decided to play the following game using a large amount of candy that the teacher gave me the other day.
* Each stu... | ```python
while True:
try:
n = int(input())
except:
break
ans = n % 39
if ans == 0:
ans = "39"
else:
ans = "{0:02d}".format(ans)
print("3C"+ans)
``` |
p00469 Lining up the cards | problem
Hanako is playing with n (4 ≤ n ≤ 10) cards side by side. Each card has one integer between 1 and 99. Hanako chose k cards (2 ≤ k ≤ 4) from these cards and arranged them in a horizontal row to make an integer. How many kinds of integers can Hanako make in total?
For example, consider that you are given five c... | ```python
import itertools
while(True):
n = int(input())
k = int(input())
if (n,k) == (0,0):
break
num_lis = []
for _ in range(n):
num_lis.append(input())
word_list = []
for item in list(itertools.permutations(num_lis,k)):
word_list.append("".join(item))
print(len(set(word_list)))
``... |
p00661 Time Manipulation | She is an apprentice wizard. She first learned the magic of manipulating time. And she decided to open a liquor store to earn a living. It has to do with the fact that all the inhabitants of the country where she lives love alcohol. Residents especially like sake that has been aged for many years, and its value increas... | ```python
# AOJ 1076 Time Manipulation
# Python3 2018.7.10 bal4u
while True:
n, m = map(int, input().split())
if n == 0: break
p = list(map(int, input().split()))
if 1 in p: n = 0
print(n/2)
``` |
p00935 Decimal Sequences | Example
Input
3
3 0 1
Output
2 | ```python
j=''.join
u=input
n=int(u())
d=j(j(u().split())for i in[0]*(n//19+(n%19>0)))
i=0
while 1:
if d.find(str(i))<0:
print(i)
exit()
i+=1
``` |
p01676 Tree Reconstruction | J - Tree Reconstruction
Problem Statement
You have a directed graph. Some non-negative value is assigned on each edge of the graph. You know that the value of the graph satisfies the flow conservation law That is, for every node v, the sum of values on edges incoming to v equals to the sum of values of edges outgoing... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
s, t = map(int, readline().split())
G[s-1].append(t-1)
used = [0]*N
cnt = 0
an... |
p02240 Connected Components | Write a program which reads relations in a SNS (Social Network Service), and judges that given pairs of users are reachable each other through the network.
Constraints
* $2 \leq n \leq 100,000$
* $0 \leq m \leq 100,000$
* $1 \leq q \leq 10,000$
Input
In the first line, two integer $n$ and $m$ are given. $n$ is the ... | ```python
# -*- coding: utf-8 -*-
import sys
sys.setrecursionlimit(10**6)
class LinkedList:
def __init__(self, n):
self.n = n
self.ll = [[] for _ in range(self.n)]
def link(self, u, v, direction=False):
self.ll[u].append(v)
if not direction:
self.ll[v].append(u)
... |
p02386 Dice IV | Write a program which reads $n$ dices constructed in the same way as Dice I, and determines whether they are all different. For the determination, use the same way as Dice III.
Constraints
* $2 \leq n \leq 100$
* $0 \leq $ the integer assigned to a face $ \leq 100$
Input
In the first line, the number of dices $n$ i... | ```python
ptn=[
[1,2,3,4,5,6],
[2,6,3,4,1,5],
[3,6,5,2,1,4],
[4,6,2,5,1,3],
[5,6,4,3,1,2],
[6,2,4,3,5,1]
]
def diffDice(orgDice, newDice):
flg = False # diff
tmpDice = [0,0,0,0,0,0]
for i in range(6):
#newDiceをptn1で並べ替え
for idx, j in enumerate(ptn[i]):
tmpDice[idx] = newDice[j-1]
... |
1077_E. Thematic Contests | Polycarp has prepared n competitive programming problems. The topic of the i-th problem is a_i, and some problems' topics may coincide.
Polycarp has to host several thematic contests. All problems in each contest should have the same topic, and all contests should have pairwise distinct topics. He may not use all the ... | ```python
# from collections import Counter as C
# n, k_ = map(int, input().split())
# l = [*map(int, input().split())]
# c = C(l)
# d = {}
# for k, v in c.items():
# d[v] = d.get(v, []) + [str(k)]
# ld = sorted([(k, v) for k, v in d.items()], reverse = True)
# res = []
# # print(ld)
# for e in ld:
# res += ... |
1119_E. Pavel and Triangles | Pavel has several sticks with lengths equal to powers of two.
He has a_0 sticks of length 2^0 = 1, a_1 sticks of length 2^1 = 2, ..., a_{n-1} sticks of length 2^{n-1}.
Pavel wants to make the maximum possible number of triangles using these sticks. The triangles should have strictly positive area, each stick can be ... | ```python
n = int(input())
a = list(map(int, input().split()))
ans = 0
last = 0
for q in range(len(a)):
while last > 0 and a[q] >= 2:
ans += 1
a[q] -= 2
last -= 1
ans += a[q]//3
last += a[q] % 3
print(ans)
``` |
1146_B. Hate "A" | Bob has a string s consisting of lowercase English letters. He defines s' to be the string after removing all "a" characters from s (keeping all other characters in the same order). He then generates a new string t by concatenating s and s'. In other words, t=s+s' (look at notes for an example).
You are given a string... | ```python
s = input()
s1 = ""
a = 0
for i in s:
if i == 'a':
a -= -1
else:
s1 += i
if len(s1) % 2:
print(":(")
exit()
t = len(s1) // 2
ch = 1
x = len(s) - 1
for i in range(t - 1, -1, -1):
if s1[i] != s[x]:
ch = 0
break
x += -1
if ch:
for i in range(len(s) - ... |
1167_B. Lost Numbers | This is an interactive problem. Remember to flush your output while communicating with the testing program. You may use fflush(stdout) in C++, system.out.flush() in Java, stdout.flush() in Python or flush(output) in Pascal to flush the output. If you use some other programming language, consult its documentation. You m... | ```python
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 15 18:26:08 2019
@author: Hamadeh
"""
class LLNode:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
# Class to create a Doubly Linked List
class LL:
# Constructor for empty Doubly Linked Li... |
1185_E. Polycarp and Snakes | After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size n × m (where n is the number of rows, m is the number of columns) and starts to draw snakes in cells.
Polycarp draws snakes with lowercase Latin letters. ... | ```python
def naiveSolve():
return
from collections import defaultdict
def charToInt(c): #'a'->0
if c=='.':
return -1
return ord(c)-ord('a')
def main():
t=int(input())
allans=[]
for _ in range(t):
n,m=readIntArr()
grid=[] # convert all chars to int
... |
1204_C. Anna, Svyatoslav and Maps | The main characters have been omitted to be short.
You are given a directed unweighted graph without loops with n vertexes and a path in it (that path is not necessary simple) given by a sequence p_1, p_2, …, p_m of m vertexes; for each 1 ≤ i < m there is an arc from p_i to p_{i+1}.
Define the sequence v_1, v_2, …, v... | ```python
from collections import deque
n = int(input())
graph = [list(map(lambda bit: bit == '1', list(input()))) for _ in range(n)]
m = int(input())
way = list(map(lambda i: int(i) - 1, input().split()))
#print(graph)
def dfs(start):
queue = deque([start])
d = [-1] * n
d[start] = 0
while len(queue) !... |
1221_A. 2048 Game | You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two.
You may perform any number (possibly, zero) operations with this multiset.
During each operation you choose two equal integers from s, remove them from s and insert the number eq... | ```python
q=int(input())
for i in range(q):
n=int(input())
lst2=[]
lst1=list(map(int,input().split()))
for i in range(len(lst1)):
if lst1[i]<=2048:
lst2.append(lst1[i])
sum1=sum(lst2)
if sum1>=2048:
print("YES")
else:
print("NO")
``` |
1266_B. Dice Tower | Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
Fo... | ```python
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 18 14:08:47 2020
@author: Varun
"""
from sys import stdin, stdout
stdin.readline()
numbers = map(int, stdin.readline().split())
def check(n):
if n < 15:
return False
m = n%14
return 1 <= m <= 6
for el in numbers:
if check(e... |
1287_D. Numbers on Tree | Evlampiy was gifted a rooted tree. The vertices of the tree are numbered from 1 to n. Each of its vertices also has an integer a_i written on it. For each vertex i, Evlampiy calculated c_i — the number of vertices j in the subtree of vertex i, such that a_j < a_i.
<image>Illustration for the second example, the first... | ```python
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
n = int(input())
cs = [0] * (n + 1)
ps = [0] * (n + 1)
children = [[] for _ in range(n+1)]
for i in range(1, n+1):
p, c = map(int, input().split())
... |
1307_D. Cow and Fields | Bessie is out grazing on the farm, which consists of n fields connected by m bidirectional roads. She is currently at field 1, and will return to her home at field n at the end of the day.
The Cowfederation of Barns has ordered Farmer John to install one extra bidirectional road. The farm has k special fields and he h... | ```python
import sys
from collections import deque
reader = (line.rstrip() for line in sys.stdin)
input = reader.__next__
# v(G), e(G), special v
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
# adjacency lists
g = [[] for _ in range(n + 1)]
for _ in range(m):
v, to = map(int, inpu... |
1330_D. Dreamoon Likes Sequences | Dreamoon likes sequences very much. So he created a problem about the sequence that you can't find in OEIS:
You are given two integers d, m, find the number of arrays a, satisfying the following constraints:
* The length of a is n, n ≥ 1
* 1 ≤ a_1 < a_2 < ... < a_n ≤ d
* Define an array b of length n as foll... | ```python
t = int(input())
for _ in range(t):
d, m = map(int, input().split())
a = []
i = 0
while d > (1<<(i+1))-1:
a.append(1<<i)
i += 1
a.append((1<<i) - (1<<(i+1)) + d + 1)
#print(a)
ans = 1
for x in a:
ans *= x+1
ans %= m
print((ans-1)%m)
``` |
1350_D. Orac and Medians | Slime has a sequence of positive integers a_1, a_2, …, a_n.
In one operation Orac can choose an arbitrary subsegment [l … r] of this sequence and replace all values a_l, a_{l + 1}, …, a_r to the value of median of \\{a_l, a_{l + 1}, …, a_r\}.
In this problem, for the integer multiset s, the median of s is equal to th... | ```python
# Template 1.0
import sys, re, math
from collections import deque, defaultdict, Counter, OrderedDict
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, gcd
from heapq import heappush, heappop, heapify, nlargest, nsmallest
def STR(): return list(input())
def INT(): return int(input())
def MA... |
1393_C. Pinkie Pie Eats Patty-cakes | Pinkie Pie has bought a bag of patty-cakes with different fillings! But it appeared that not all patty-cakes differ from one another with filling. In other words, the bag contains some patty-cakes with the same filling.
Pinkie Pie eats the patty-cakes one-by-one. She likes having fun so she decided not to simply eat t... | ```python
def solve(n,ar):
freq = [0] * 200000
for i in range(n):
freq[ar[i]] += 1
maxi = 0
max_freq = 0
for i in range(len(freq)):
if maxi < freq[i]:
maxi = max(maxi,freq[i])
max_freq = 1
elif freq[i] == maxi:
max_freq += 1
print... |
1418_B. Negative Prefixes | You are given an array a, consisting of n integers.
Each position i (1 ≤ i ≤ n) of the array is either locked or unlocked. You can take the values on the unlocked positions, rearrange them in any order and place them back into the unlocked positions. You are not allowed to remove any values, add the new ones or rearra... | ```python
import sys
from sys import stdin
import math
import fractions
#Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))
def iinput():
return int(input())
def minput():
return map(int,input().split())
def linput():
return list(map(int,input().split()))
def fiinput():
return int(stdin.readline())
de... |
1436_A. Reorder | For a given array a consisting of n integers and a given integer m find if it is possible to reorder elements of the array a in such a way that ∑_{i=1}^{n}{∑_{j=i}^{n}{(a_j)/(j)}} equals m? It is forbidden to delete elements as well as insert new elements. Please note that no rounding occurs during division, for exampl... | ```python
#import numpy as np
#import collections
#import sys
# =============================================================================
#def get_primeFactor(n):
# res=[1]
# x=2
# while x*x<=n:
# while n%x==0:
# res.append(x)
# n//=x
# x+=1
# if n>1:res.append(n)
# ... |
1485_F. Copy or Prefix Sum | You are given an array of integers b_1, b_2, …, b_n.
An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true:
* b_i = a_i, or
* b_i = ∑_{j=1}^{i} a_j.
Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should pri... | ```python
for s in[*open(0)][2::2]:
C=[0];N=0;D={0:1};S=1
for n in map(int,s.split()):C+=C[-1]+n,;N+=1
for i in range(1,N):D[C[i]],S=S,(2*S-D.get(C[i],0))%(10**9+7)
print(S)
``` |
1536_B. Prinzessin der Verurteilung | I, Fischl, Prinzessin der Verurteilung, descend upon this land by the call of fate an — Oh, you are also a traveler from another world? Very well, I grant you permission to travel with me.
It is no surprise Fischl speaks with a strange choice of words. However, this time, not even Oz, her raven friend, can interpret h... | ```python
# abc = 'abcdefghijklmnopqrstuvwxy'
# test1_previous = [x + y for x in abc for y in abc if x!='m']
def nextchr(c):
return chr(ord(c)+1)
def next(s):
if s == '':
ans = '.'
elif s[-1] == 'z':
ans = next(s[:-1]) + 'a'
else:
ans = s[:-1] + nextchr(s[-1])
return ans
... |
163_A. Substring and Subsequence | One day Polycarpus got hold of two non-empty strings s and t, consisting of lowercase Latin letters. Polycarpus is quite good with strings, so he immediately wondered, how many different pairs of "x y" are there, such that x is a substring of string s, y is a subsequence of string t, and the content of x and y is the s... | ```python
from sys import stdin
s=[ord(i)-97 for i in stdin.readline().strip()]
s1=[ord(i)-97 for i in stdin.readline().strip()]
n=len(s)
m=len(s1)
mod=1000000007
dp=[[0 for i in range(n)] for j in range(26)]
for i in range(m):
arr=[0 for j in range(n)]
for j in range(n):
if s1[i]==s[j] :
ar... |
183_B. Zoo | The Zoo in the Grid Kingdom is represented by an infinite grid. The Zoo has n observation binoculars located at the OX axis. For each i between 1 and n, inclusive, there exists a single binocular located at the point with coordinates (i, 0). There are m flamingos in the Zoo, located at points with positive coordinates.... | ```python
def gcd(a,b):
if b == 0:
return a
return gcd(b, a % b)
def normalize_rational(num,den):
#associate the -ve with the num or cancel -ve sign when both are -ve
if num ^ den < 0 and num > 0 or num ^ den > 0 and num < 0:
num = -num; den = -den
#put it in its simplest form
... |
230_C. Shifts | You are given a table consisting of n rows and m columns. Each cell of the table contains a number, 0 or 1. In one move we can choose some row of the table and cyclically shift its values either one cell to the left, or one cell to the right.
To cyclically shift a table row one cell to the right means to move the valu... | ```python
def solve(rows):
all_dists = [0 for _ in range(len(rows[0]))]
for r in rows:
dists = [len(r) for _ in r]
if '1' not in r:
return -1
start = r.index('1')
for i in range(len(r)):
right = (i+start)%len(r) # going right
left = (start+2*le... |
256_B. Mr. Bender and Square | Mr. Bender has a digital table of size n × n, each cell can be switched on or off. He wants the field to have at least c switched on squares. When this condition is fulfilled, Mr Bender will be happy.
We'll consider the table rows numbered from top to bottom from 1 to n, and the columns — numbered from left to right f... | ```python
x, y, n, c = 0, 0, 0, 0
def suma_impares(m):
return m * m
def suma_n(m):
return m * (m - 1) // 2
def cnt(t):
u, d, l, r = x + t, x - t, y - t, y + t
suma = t ** 2 + (t + 1) ** 2
if u > n: suma -= suma_impares(u - n)
if d < 1: suma -= suma_impares(1 - d)
if l < 1: suma -= suma_impares(1 - l)
if r > n: ... |
27_B. Tournament | The tournament «Sleepyhead-2010» in the rapid falling asleep has just finished in Berland. n best participants from the country have participated in it. The tournament consists of games, each of them is a match between two participants. n·(n - 1) / 2 games were played during the tournament, and each participant had a m... | ```python
a = int(input())
d = {}
f = {}
for i in range(a*(a-1)//2-1):
v, c = map(int, input().split())
if v not in f:
f[v] = []
f[v].append(c)
if v in d:
d[v] += 1
else:
d[v] = 1
if c in d:
d[c] += 1
else:
d[c] = 1
s = []
m = 0
for i in range(1, a + 1... |
302_A. Eugeny and Array | Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + a... | ```python
from collections import Counter
num, cases = map(int, input().split())
arr = list(map(int, input().split()))
count = Counter(arr)
minus = count[-1]
plus = count[1]
mn = min(plus, minus)
ans = []
while cases:
cases -= 1
a, b = map(int, input().split())
if (b - a + 1) % 2 != 0:
ans.append(... |
34_E. Collisions | On a number line there are n balls. At time moment 0 for each ball the following data is known: its coordinate xi, speed vi (possibly, negative) and weight mi. The radius of the balls can be ignored.
The balls collide elastically, i.e. if two balls weighing m1 and m2 and with speeds v1 and v2 collide, their new speeds... | ```python
class Ball:
def __init__(self, x, v, m):
self.v = v
self.x = x
self.m = m
def move(self, time):
self.x += self.v * time
def collisionTime(self, other):
if self.v == other.v:
return float("inf")
t = - (self.x - other.x) / (self.v - othe... |
374_A. Inna and Pink Pony | Dima and Inna are doing so great! At the moment, Inna is sitting on the magic lawn playing with a pink pony. Dima wanted to play too. He brought an n × m chessboard, a very tasty candy and two numbers a and b.
Dima put the chessboard in front of Inna and placed the candy in position (i, j) on the board. The boy said h... | ```python
n, m, i, j, a, b = map(int, input().split())
corners = [(1, 1), (1, m), (n, 1), (n, m)]
result = False
ans = -1
for cnt in corners:
if (abs(cnt[0] - i) % a == 0) and (abs(cnt[1] - j) % b == 0):
result = True
t1, t2 = abs(cnt[0] - i) // a, abs(cnt[1] - j) // b
if (t1 + t2) % 2 == 0:... |
445_B. DZY Loves Chemistry | DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pour... | ```python
def iterative_dfs(graph, start, path=[]):
visited = {}
for i in graph:
visited[i] = []
q=[start]
while q:
v=q.pop(0)
if not visited[v]:
visited[v] = True
path=path+[v]
q=graph[v]+q
return path
nodes, edges = map(int, input().... |
467_C. George and Job | The new ITone 6 has been released recently and George got really keen to buy it. Unfortunately, he didn't have enough money, so George was going to work as a programmer. Now he faced the following problem at the work.
Given a sequence of n integers p1, p2, ..., pn. You are to choose k pairs of integers:
[l1, r1], [l2... | ```python
n, m, k = list(map(int, input().split()))
a = list(map(int, input().split()))
p_a = [0 for _ in range(n)]
p_a[0] = a[0]
for i in range(1, n):
p_a[i] = p_a[i - 1] + a[i]
INF = -1e10
# print(p_a)
dp = {}
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
... |
513_G1. Inversions problem | You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
In... | ```python
n, k = map(int, input().split())
p = list(map(int, input().split()))
def count_invs(a):
ans = 0
for i in range(n-1):
for j in range(i + 1, n):
if a[i] > a[j]:
ans += 1
return ans
def inv_in_perms(a, count):
if count > 0:
ans = 0
for l... |
53_D. Physical Education | Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line... | ```python
import sys
n = int(sys.stdin.readline ())
a= [int (x) for x in sys.stdin.readline ().split ()]
assert len(a) == n
b = [int (x) for x in sys.stdin.readline ().split ()]
assert len(b) == n
ans = []
for i in range (n):
j = i;
while b[j] != a[i] :
j += 1
while j > i:
ans += [(j, j ... |
567_F. Mausoleum | King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has th... | ```python
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if a==b:
continue
if (e[a] and e[a]!=b) or (e[b] and e[b]!=a):
ok = 0
... |
630_O. Arrow | Petya has recently started working as a programmer in the IT city company that develops computer games.
Besides game mechanics implementation to create a game it is necessary to create tool programs that can be used by game designers to create game levels. Petya's first assignment is to create a tool that allows to pa... | ```python
from math import atan2, pi
EPS = 0.00000001
def eq(a, b):
return abs(a - b) < EPS
class Vector:
def __init__(self, x2, y2, x1=0, y1=0):
self.x = (x2 - x1)
self.y = y2 - y1
self.s = (self.x ** 2 + self.y ** 2) ** 0.5
def __add__(self, other):
return Vector(self... |
659_G. Fence Divercity | Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily de... | ```python
mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
ans = x = 0
for i in range(n):
ans += h[i] + min(h[i], h[i - 1]) * x
if i < n - 1:
x *= min(h[i - 1], h[i], h[i + 1])
x += min(h[i], h[i + 1])
ans %= mod
x %= mod
print(ans)
``` |
682_D. Alyona and Strings | After returned from forest, Alyona started reading a book. She noticed strings s and t, lengths of which are n and m respectively. As usual, reading bored Alyona and she decided to pay her attention to strings s and t, which she considered very similar.
Alyona has her favourite positive integer k and because she is to... | ```python
n, m, k = map(int, input().split())
s, t = input(), input()
n += 1
m += 1
p = [i for i in range(n * m - n) if (i + 1) % n]
r = p[::-1]
d = [0] * n * m
for i in p:
if s[i % n] == t[i // n]: d[i] = d[i - n - 1] + 1
f = d[:]
for y in range(k - 1):
for i in p: f[i] = max(f[i], f[i - 1], f[i - n])
... |
705_C. Thor | Thor is getting used to the Earth. As a gift Loki gave him a smartphone. There are n applications on this phone. Thor is fascinated by this phone. He has only one minor issue: he can't count the number of unread notifications generated by those applications (maybe Loki put a curse on it so he can't).
q events are abou... | ```python
import collections
import copy
n, q = map(int, input().split())
Q = collections.deque()
A = n * [0]
B = copy.copy(A)
L = []
s = n = 0
for _ in range(q):
y, x = map(int, input().split())
if 2 > y:
x -= 1
Q.append(x)
B[x] += 1
A[x] += 1
s += 1
elif 3 > y:
... |
749_A. Bachgold Problem | Bachgold problem is very easy to formulate. Given a positive integer n represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer k is called prime if it is greater than 1 and has exactly two positive integer divi... | ```python
n=int(input())
c=0
if(n%2==1):
n-=3
l=[2]*(n//2)
l.append(3)
print(len(l))
print(*l)
else:
l=[2]*(n//2)
print(len(l))
print(*l)
``` |
817_B. Makes And The Product | After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the... | ```python
n=int(input())
a=list(map(int,(input().split(' '))))
a=sorted(a)
a.append(0)
ans=1
t=0
while a[3+t]==a[2]:t=t+1
if a[3]==a[0]:ans=(t+3)*(t+2)*(t+1)/6
elif a[3]==a[1]:ans=(t+2)*(t+1)/2
elif a[3]==a[2]:ans=t+1
print(int(ans))
``` |
842_B. Gleb And Pizza | Gleb ordered pizza home. When the courier delivered the pizza, he was very upset, because several pieces of sausage lay on the crust, and he does not really like the crust.
The pizza is a circle of radius r and center at the origin. Pizza consists of the main part — circle of radius r - d with center at the origin, an... | ```python
'''input
8 4
7
7 8 1
-7 3 2
0 2 1
0 -2 2
-3 -3 1
0 6 2
5 3 1
'''
r, d = map(int, input().split())
n = int(input())
c = 0
for _ in range(n):
x, y, r1 = map(int, input().split())
s = (x**2 + y**2)**0.5
if r-d <= s-r1 and s+r1 <= r:
c += 1
print(c)
``` |
863_B. Kayaking | Vadim is really keen on travelling. Recently he heard about kayaking activity near his town and became very excited about it, so he joined a party of kayakers.
Now the party is ready to start its journey, but firstly they have to choose kayaks. There are 2·n people in the group (including Vadim), and they have exactly... | ```python
n = int(input())
n = 2*n
w = [int(i) for i in input().split()]
w.sort()
import math
res = math.inf
for x in range(n):
for y in range(x+1, n):
wc = w[:]
wc.pop(y); wc.pop(x)
# print(wc)
s = 0
for i in range(0, n-3, 2):
s += wc[i+1]-wc[i]
res = min(s, res)
print(re... |
888_F. Connecting Vertices | There are n points marked on the plane. The points are situated in such a way that they form a regular polygon (marked points are its vertices, and they are numbered in counter-clockwise order). You can draw n - 1 segments, each connecting any two marked points, in such a way that all points have to be connected with e... | ```python
import sys
from array import array
n = int(input())
edge = [list(map(int, input().split())) for _ in range(n)]
mod = 10**9 + 7
dp_f = [array('i', [-1])*n for _ in range(n)]
dp_g = [array('i', [-1])*n for _ in range(n)]
for i in range(n):
dp_f[i][i] = dp_g[i][i] = 1
for i in range(n-1):
dp_f[i][i+1... |
911_D. Inversion Counting | A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a per... | ```python
def solve():
n=int(input())
a=list(map(int,input().split()))
cl=['odd','even']
m=int(input())
ans=True
b=[]
ap=b.append
for i in range(n):
for j in range(i):
if a[j]>a[i]:
ans=not ans
for i in range(m):
left,right=map(int,input()... |
933_B. A Determined Cleanup | In order to put away old things and welcome a fresh new year, a thorough cleaning of the house is a must.
Little Tommy finds an old polynomial and cleaned it up by taking it modulo another. But now he regrets doing this...
Given two integers p and k, find a polynomial f(x) with non-negative integer coefficients stric... | ```python
s = input()
# s = '46 2'
p, k = list(map(int, s.split()))
res = []
f = True
while p != 0:
if f:
n = p % k
m = (p - n) // k
f = False
else:
n = (-p) % k
m = (p + n) // k
f = True
res.append(n)
p = m
print(len(res))
print(' '.join(list(map(str, ... |
987_B. High School: Become Human | Year 2118. Androids are in mass production for decades now, and they do all the work for humans. But androids have to go to school to be able to solve creative tasks. Just like humans before.
It turns out that high school struggles are not gone. If someone is not like others, he is bullied. Vasya-8800 is an economy-cl... | ```python
import math
x,y=map(lambda x:math.log(int(x))/int(x),input().split())
print('<=>'[(x>=y)+(x>y)])
``` |
p02588 AtCoder Grand Contest 047 - Integer Product | You are given N real values A_1, A_2, \ldots, A_N. Compute the number of pairs of indices (i, j) such that i < j and the product A_i \cdot A_j is integer.
Constraints
* 2 \leq N \leq 200\,000
* 0 < A_i < 10^4
* A_i is given with at most 9 digits after the decimal.
Input
Input is given from Standard Input in the fol... | ```python
import collections
N=int(input())
A=[]
PRECISION_DIGITS=9
cnt=collections.defaultdict(int)
for n in range(N):
tmpA = float(input())
tmpA = round(tmpA*10**PRECISION_DIGITS)
#print(tmpA)
five = 0
two = 0
while (tmpA % 2) == 0:
two += 1
tmpA //= 2
while (tmpA % 5) == 0:
five += 1
tmpA //= 5
... |
p02719 AtCoder Beginner Contest 161 - Replacing Integer | Given any integer x, Aoki can do the operation below.
Operation: Replace x with the absolute difference of x and K.
You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.
Constraints
* 0 ≤ N ≤ 10^{18}
* 1 ≤ K ≤ 10^{18}
* All valu... | ```python
n,k= map(int,input().split())
a=n%k
b=abs(k-a)
print(min(a,b))
``` |
p02848 AtCoder Beginner Contest 146 - ROT N | We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | ```python
N = int(input())
S = input()
print(''.join(chr((ord(c) - ord('A') + N) % 26 + ord('A')) for c in S))
``` |
p02986 AtCoder Beginner Contest 133 - Colorful Tree | There is a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i, and the color and length of that edge are c_i and d_i, respectively. Here the color of each edge is represented by an integer between 1 and N-1 (inclusive). The same integer corresponds to the same color, and... | ```python
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10**9)
class LCA:
def __init__(self,V,edges,depth,parent,root=0):
self.edges=edges
self.maxLog=18
self.parent=[[-1]*V for _ in range(self.maxLog+1)]
self.parent[0]=parent
self.depth=depth
for i in ran... |
p03127 AtCoder Beginner Contest 118 - Monsters Battle Royale | There are N monsters, numbered 1, 2, ..., N.
Initially, the health of Monster i is A_i.
Below, a monster with at least 1 health is called alive.
Until there is only one alive monster, the following is repeated:
* A random alive monster attacks another random alive monster.
* As a result, the health of the monster a... | ```python
from fractions import gcd
from functools import reduce
n, *A = map(int, open(0).read().split())
print(reduce(gcd, A))
``` |
p03270 AtCoder Regular Contest 102 - Stop. Otherwise... | Takahashi throws N dice, each having K sides with all integers from 1 to K. The dice are NOT pairwise distinguishable. For each i=2,3,...,2K, find the following value modulo 998244353:
* The number of combinations of N sides shown by the dice such that the sum of no two different sides is i.
Note that the dice are ... | ```python
from sys import exit, setrecursionlimit, stderr
from functools import reduce
from itertools import *
from collections import defaultdict
from bisect import bisect
def read():
return int(input())
def reads():
return [int(x) for x in input().split()]
K, N = reads()
MOD = 998244353
MAXN = 4020
fact = [1... |
p03427 AtCoder Grand Contest 021 - Digit Sum 2 | Find the maximum possible sum of the digits (in base 10) of a positive integer not greater than N.
Constraints
* 1\leq N \leq 10^{16}
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output
Print the maximum possible sum of the digits (in base 10) of a positive integer not... | ```python
N=input()
NL=len(N)
if N[1:]=='9'*(NL-1):
ans=int(N[0])+9*(NL-1)
else:
ans=int(N[0])+9*(NL-1)-1
print(ans)
``` |
p03585 Tenka1 Programmer Contest - CARtesian Coodinate | There are N lines in the xy-plane. The i-th line is represented by A_ix+B_iy=C_i. Any two lines among the N+2 lines, the above N lines plus the x-axis and y-axis, cross each other at exactly one point.
For each pair 1 \leq i < j \leq N, there is a car at the cross point of the i-th and j-th lines. Even where three or ... | ```python
def addbit(i):
i += 1
while i <= N:
BIT[i] += 1
i += i & (-i)
def getsum(i):
ret = 0
i += 1
while i != 0:
ret += BIT[i]
i -= i&(-i)
return ret
def bit(L):
global BIT
BIT=[0] * (N+1)
re = 0
for l in L:
re += getsum(l)
addbi... |
p03743 AtCoder Regular Contest 072 - Alice in linear land | Alice lives on a line. Today, she will travel to some place in a mysterious vehicle. Initially, the distance between Alice and her destination is D. When she input a number x to the vehicle, it will travel in the direction of the destination by a distance of x if this move would shorten the distance between the vehicle... | ```python
N, D = map(int, input().split())
d = list(map(int, input().split()))
Q = int(input())
q = list(map(lambda x : int(x)-1 , input().split()))
dis = [0 for i in range(N+1)]
dis[0] = D
for i in range(N):
dis[i+1] = min(dis[i], abs(dis[i] - d[i]))
dp = [0 for i in range(N+1)]
dp[N] = 1
for i in range(N-1, -1,... |
p03903 CODE FESTIVAL 2016 Elimination Tournament Round 1 (Parallel) - Graph | Takahashi found an undirected connected graph with N vertices and M edges. The vertices are numbered 1 through N. The i-th edge connects vertices a_i and b_i, and has a weight of c_i.
He will play Q rounds of a game using this graph. In the i-th round, two vertices S_i and T_i are specified, and he will choose a subse... | ```python
from collections import deque
import sys
sys.setrecursionlimit(10**5)
N, M = map(int, input().split())
E = []
for i in range(M):
a, b, c = map(int, input().split())
E.append((c, a-1, b-1))
E.sort()
*p, = range(N)
def root(x):
if x == p[x]:
return x
p[x] = y = root(p[x])
return y
... |
p00009 Prime Number | Write a program which reads an integer n and prints the number of prime numbers which are less than or equal to n. A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.
Input
Input consists of several da... | ```python
import sys
import math
LIMIT = 1000000
p = 2
pList = [True] * (LIMIT + 1)
while p ** 2 <= LIMIT:
if(pList[p]):
for i in range(p * 2, LIMIT + 1 , p):
pList[i] = False
p += 1
# print(pList)
lines = str(sys.stdin.read()).strip().split("\n")
for line in lines:
line = int(li... |
p00141 Spiral Pattern | I decided to create a program that displays a "round and round pattern". The "round and round pattern" is as follows.
* If the length of one side is n, it is displayed as a character string with n rows and n columns.
* A spiral pattern that rotates clockwise with the lower left corner as the base point.
* The part wit... | ```python
vector = ((0, -1), (1, 0), (0, 1), (-1, 0))
def make_guruguru(d):
lst = [["#"] * (d + 4)]
for _ in range(d + 2):
lst.append(["#"] + [" "] * (d + 2) + ["#"])
lst.append(["#"] * (d + 4))
x, y = 2, d + 1
lst[y][x] = "#"
direct = 0
vx, vy = vector[0]
cnt = 1
while True:
while lst[y + vy... |
p00274 A Pair of Prizes | Jou and Yae are a good couple. Jou is collecting prizes for capsule toy vending machines (Gachapon), and even when they go out together, when they find Gachapon, they seem to get so hot that they try it several times. Yae was just looking at Jou, who looked happy, but decided to give him a Gachapon prize for his upcomi... | ```python
# AOJ 0279: A Pair of Prizes
# Python3 2018.6.25 bal4u
while True:
n = int(input())
if n == 0: break
k = list(map(int, input().split()))
one, many = 0, 0
for i in k:
if i == 1: one += 1
elif i > 1: many += 1
print(one+many+1 if many > 0 else "NA")
``` |
p00462 Pizza | problem
JOI Pizza sells pizza home delivery along the d-meter-long ring road that runs through the city center.
JOI Pizza has n stores S1, ..., Sn on the loop line. The head office is S1. The distance from S1 to Si when moving the loop line clockwise is set to di meters. D2 , ..., dn is an integer greater than or equ... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0539
AC
"""
import sys
from sys import stdin
from bisect import bisect_right
input = stdin.readline
def main(args):
while True:
d = int(input()) # ??°??¶????????????
if d == 0:
break
... |
p00652 Cutting a Chocolate | Turtle Shi-ta and turtle Be-ko decided to divide a chocolate. The shape of the chocolate is rectangle. The corners of the chocolate are put on (0,0), (w,0), (w,h) and (0,h). The chocolate has lines for cutting. They cut the chocolate only along some of these lines.
The lines are expressed as follows. There are m poi... | ```python
# AOJ 1067 Cutting a Chocolate
# Python3 2018.7.10 bal4u
from bisect import bisect_left
while True:
n, m, w, h, S = map(int, input().split())
if n == 0: break
m, wh2 = m+1, 2*(w*h)
S = wh2-2*S
tbl, s = [[0,0,0,0]], [0]
for i in range(1, m):
l, r = map(int, input().split())
tbl.append([l, r, 0, r-l... |
p00928 Automotive Navigation | Example
Input
4 2 1 1
1 1 1 2
2 2 2 1
2 2 1 2
1 1 2 1
9 N
Output
1 1
2 2 | ```python
# coding: utf-8
import sys
sys.setrecursionlimit(50000000)
max_c=101
vec=[(0,2),(2,0),(0,-2),(-2,0)]
try:
while True:
log=[-1 for i in range(10001)]
n,x0,y0,t=map(int,input().split())
field=[[0 for i in range(max_c)]for i in range(max_c)]
for i in range(n):
a,b,... |
p01061 Community Integration | Problem
There are N villages. Each village is numbered from 1 to N. Due to the recent merger boom, several villages have been merged. Two or more merged villages will become one new city, and villages that are not merged with any village will remain villages.
You will be given multiple pieces of information that two ... | ```python
n, m = map(int, input().split())
q = []
for _ in range(m):
a, b = map(int, input().split())
i, j = -1, -1
for k in range(len(q)):
if i == -1:
if a in q[k]:
i = k
if j == -1:
if b in q[k]:
j = k
if i >= 0 and j >= 0:
... |
p01498 King Slime | There is a grid of size W × H surrounded by walls. Some cells in the grid are occupied by slimes. The slimes want to unite with each other and become a "King Slime".
In each move, a slime can move to east, west, south and north direction until it enters a cell occupied by another slime or hit the surrounding wall. If ... | ```python
import sys
class UnionFind:
def __init__(self,sz):
self.__ranks = [1] * sz
self.__parents = [ i for i in range(sz) ]
def find_parent(self, x):
if x == self.__parents[x]:
return x
else:
self.__parents[x] = self.find_parent(self.__parents[x])
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.