name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
315_B. Sereja and Array | Sereja has got an array, consisting of n integers, a1, a2, ..., an. Sereja is an active boy, so he is now going to complete m operations. Each operation will have one of the three forms:
1. Make vi-th array element equal to xi. In other words, perform the assignment avi = xi.
2. Increase each array element by yi.... | ```python
import sys,math
from collections import deque,defaultdict
import operator as op
from functools import reduce
from itertools import permutations
import heapq
#sys.setrecursionlimit(10**7)
# OneDrive\Documents\codeforces
I=sys.stdin.readline
alpha="abcdefghijklmnopqrstuvwxyz"
mod=10**9 + 7
"""
x_move=[-1,... |
337_D. Book of Evil | Paladin Manao caught the trail of the ancient Book of Evil in a swampy area. This area contains n settlements numbered from 1 to n. Moving through the swamp is very difficult, so people tramped exactly n - 1 paths. Each of these paths connects some pair of settlements and is bidirectional. Moreover, it is possible to r... | ```python
from collections import defaultdict
import sys
input=sys.stdin.readline
class graph:
def __init__(self,n,mark):
self.d=defaultdict(list)
self.n=n
self.mark=mark
def add(self,s,d):
self.d[s].append(d)
self.d[d].append(s)
def bfs(self,s,dis):
... |
360_A. Levko and Array Recovery | Levko loves array a1, a2, ... , an, consisting of integers, very much. That is why Levko is playing with array a, performing all sorts of operations with it. Each operation Levko performs is of one of two types:
1. Increase all elements from li to ri by di. In other words, perform assignments aj = aj + di for all j ... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if ... |
383_D. Antimatter | Iahub accidentally discovered a secret lab. He found there n devices ordered in a line, numbered from 1 to n from left to right. Each device i (1 ≤ i ≤ n) can create either ai units of matter or ai units of antimatter.
Iahub wants to choose some contiguous subarray of devices in the lab, specify the production mode f... | ```python
import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(2*10**5+10)
write = lambda x: sys.stdout.write(x+"\n")
debug = lambda x: sys.stderr.write(x+"\n")
writef = lambda x: print("{:.12f}".format(x))
n = int(input())
a = list(map(int, input().split()))
m = sum(a)
M = 10**9+7
dp = [0... |
404_C. Restore Graph | Valera had an undirected connected graph without self-loops and multiple edges consisting of n vertices. The graph had an interesting property: there were at most k edges adjacent to each of its vertices. For convenience, we will assume that the graph vertices were indexed by integers from 1 to n.
One day Valera count... | ```python
from sys import exit
n, k = map(int, input().split())
nodes = [[] for _ in range(n+1)]
edges = []
for node, dist in enumerate(map(int, input().split())):
nodes[dist].append(node)
if len(nodes[0]) != 1 or len(nodes[1]) > k:
print(-1)
else:
for i in range(1, n):
if len(nodes[i])*(k-1) < ... |
431_D. Random Task | One day, after a difficult lecture a diligent student Sasha saw a graffitied desk in the classroom. She came closer and read: "Find such positive integer n, that among numbers n + 1, n + 2, ..., 2·n there are exactly m numbers which binary representation contains exactly k digits one".
The girl got interested in the t... | ```python
def dfs(n, k, cache = {}):
# if number of bits is bigger than the number's bits of the number's bits is less than 0
if k > n or k < 0: return 0
# if num bits is 0 or num bits is equivalent to the number's bits
if k == 0 or k == n: return 1
# This optimization is not necessary but flips the... |
454_A. Little Pony and Crystal Mine | Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | ```python
n=int(input())
a=int(n/2)
b=1
for i in range(int(n/2)):
for j in range(a):
print("*",end="")
for j in range(b):
print('D',end="")
b=b+2
for j in range(a):
print("*",end="")
a=a-1
print()
for i in range(b):
print("D",end="")
print()
a=a+1
b=b-2
for i in range... |
476_D. Dreamoon and Sets | Dreamoon likes to play with sets, integers and <image>. <image> is defined as the largest positive integer that divides both a and b.
Let S be a set of exactly four distinct integers greater than 0. Define S to be of rank k if and only if for all pairs of distinct elements si, sj from S, <image>.
Given k and n, Dream... | ```python
n,k = [int(i) for i in input().split()]
print((6*n-1)*k)
for a in range(n):
val = 6*a
print((val+1)*k,(val+2)*k,(val+3)*k,(val+5)*k)
``` |
49_E. Common ancestor | The DNA sequence for every living creature in Berland can be represented as a non-empty line consisting of lowercase Latin letters. Berland scientists found out that all the creatures evolve by stages. During one stage exactly one symbol of the DNA line is replaced by exactly two other ones. At that overall there are n... | ```python
#!/usr/bin/env python3
import itertools
import collections
# Read input strings
s1 = input()
s2 = input()
# Read evolution rules, use a mapping from the 2 target characters to the source character
rules = collections.defaultdict(set)
n = int(input())
for i in range(n):
rule = input()
target = rule[-2:]... |
577_A. Multiplication Table | Let's consider a table consisting of n rows and n columns. The cell located at the intersection of i-th row and j-th column contains number i × j. The rows and columns are numbered starting from 1.
You are given a positive integer x. Your task is to count the number of cells in a table that contain number x.
Input
T... | ```python
import sys
n, x = map(int, sys.stdin.readline().split())
s = 0
for i in range(1, n + 1):
if (x % i == 0 and x / i <= n):
s += 1
print(s)
``` |
599_D. Spongebob and Squares | Spongebob is already tired trying to reason his weird actions and calculations, so he simply asked you to find all pairs of n and m, such that there are exactly x distinct squares in the table consisting of n rows and m columns. For example, in a 3 × 5 table there are 15 squares with side one, 8 squares with side two a... | ```python
n,i,t,r=int(input()),0,0,[]
while 1:
i+=1
n-=i*i
if n<0:break
t+=i
m=n//t
r+=[(m+i,i),(i,m+i)][m==0:]*(m*t==n)
print(len(r))
for p in sorted(r):print("%d %d"%p)
``` |
620_C. Pearls in a Row | There are n pearls in a row. Let's enumerate them with integers from 1 to n from the left to the right. The pearl number i has the type ai.
Let's call a sequence of consecutive pearls a segment. Let's call a segment good if it contains two pearls of the same type.
Split the row of the pearls to the maximal number of ... | ```python
n=int(input())
d={}
b=[]
e=1
a=list(map(int,input().split()))
for i in range(n):
if a[i] in d:
b.append([e,i+1])
e=i+2
d.clear()
else:
d[a[i]]=i+1
if len(b)==0:
print(-1)
exit()
print(len(b))
k=b[-1]
b[-1]=[k[0],n]
for i in b:
print(*i)
``` |
641_B. Little Artem and Matrix | Little Artem likes electronics. He can spend lots of time making different schemas and looking for novelties in the nearest electronics store. The new control element was delivered to the store recently and Artem immediately bought it.
That element can store information about the matrix of integers size n × m. There a... | ```python
import itertools
import bisect
import math
from collections import *
import os
import sys
from io import BytesIO, IOBase
ii = lambda: int(input())
lmii = lambda: list(map(int, input().split()))
li = lambda: list(input())
mii = lambda: map(int, input().split())
msi = lambda: map(str, input().split())
def ma... |
669_E. Little Artem and Time Machine | Little Artem has invented a time machine! He could go anywhere in time, but all his thoughts of course are with computer science. He wants to apply this time machine to a well-known data structure: multiset.
Artem wants to create a basic multiset of integers. He wants these structure to support operations of three typ... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
new = lambda xx: (xx|xx-1)+1
def buildBIT(bit,n):
for i in range(1,n+1):
x = new(i)
if x <= n:
bit[x] += bit[i]
def pointUpdate(bit,point,n,diff):
while point <= n:
... |
690_E2. Photographs (II) | Zombies seem to have become much more intelligent lately – a few have somehow wandered into the base through the automatic gate. Heidi has had to beef up security, and a new gate has been installed. Unfortunately, now the questions being asked are more complicated, and even humans have trouble answering them. Can you s... | ```python
print("""2 1
2 3 1
4 3 2 1
1 3 4 2 5
1 6 11 3 10 9 15 12 7 13 2 5 4 14 8
5 1 3 11 10 7 6 9 13 15 12 4 14 2 8
9 7 2 5 1 10 8 3 4 6
2 1 4 3
4 12 8 2 9 14 5 7 1 6 10 13 15 3 11
11 5 6 8 10 12 7 2 1 4 9 3 13 14 15
11 7 8 4 5 15 13 14 3 9 12 2 1 10 6
12 7 11 4 10 2 5 14 13 1 6 3 9 8 15 16
3 2 1
4 2 1 ... |
715_B. Complete The Graph | ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer.
The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edg... | ```python
import heapq
from collections import defaultdict
class Graph:
def __init__(self, n):
self.nodes = set(range(n))
self.edges = defaultdict(list)
self.distances = {}
def add_edge(self, from_node, to_node, distance):
self.edges[from_node].append(to_node)
self.edg... |
735_D. Taxes | Mr. Funt now lives in a country with a very specific tax laws. The total income of mr. Funt during this year is equal to n (n ≥ 2) burles and the amount of tax he has to pay is calculated as the maximum divisor of n (not equal to n, of course). For example, if n = 6 then Funt has to pay 3 burles, while for n = 25 he ne... | ```python
def isPrime(n):
i=2
while i*i<=n:
if n%i==0:
return False
i+=1
return True
n=int(input())
if isPrime(n):
print(1)
elif n&1==0:
print(2)
else:
if isPrime(n-2):
print(2)
else:
print(3)
``` |
75_D. Big Maximum Sum | Ahmed and Mostafa used to compete together in many programming contests for several years. Their coach Fegla asked them to solve one challenging problem, of course Ahmed was able to solve it but Mostafa couldn't.
This problem is similar to a standard problem but it has a different format and constraints.
In the stand... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def prepare(n, *a):
acc = 0
sub_max = -10**9
left_min = 0
left_max = 0
lmin2, lmax2 = 0, -10**9
for i, x in enumerate(a):
acc += x
sub_max = max(sub... |
780_C. Andryusha and Colored Balloons | Andryusha goes through a park each day. The squares and paths between them look boring to Andryusha, so he decided to decorate them.
The park consists of n squares connected with (n - 1) bidirectional paths in such a way that any square is reachable from any other using these paths. Andryusha decided to hang a colored... | ```python
n=int(input())
g=[[] for i in range(n)]
for _ in range(n-1):
x,y=map(int,input().split())
g[x-1].append(y-1)
g[y-1].append(x-1)
l=0
for i in range(n):
l=max(l,len(g[i])+1)
q=[0]
paint=[-1]*n
paint[0]=1
while q:
ver=q.pop()
use=set()
use.add(paint[ver])
for to in g[ver]:
use.add(paint[to])
... |
850_A. Five Dimensional Points | You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide.
We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,... | ```python
n=int(input())
A=[]
js=0
B=[]
for i in range(n):
A.append(list(map(int,input().split())))
def product(a,b,c):
pr=0
for m in range(5):
pr=pr+(A[b][m]-A[a][m])*(A[c][m]-A[a][m])
return (pr)
if(n>11):
print(0)
else:
for j in range(n):
k=0
l=0
flag=0
... |
873_C. Strange Game On Matrix | Ivan is playing a strange game.
He has a matrix a with n rows and m columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
1. Initially Ivan's scor... | ```python
n,m,k=input().split()
n=int(n)
m=int(m)
k=int(k)
array=[]
for x in range(n):
a=input().split()
fin=[]
for i in a:
fin.append(int(i))
array.append(fin)
cumm=[[0 for x in range(m)] for y in range(n)]
i=0
while(i<m):
j=n-1
while(j>=0):
if(j==n-1):
cumm[j][i]=ar... |
899_B. Months and Years | Everybody in Russia uses Gregorian calendar. In this calendar there are 31 days in January, 28 or 29 days in February (depending on whether the year is leap or not), 31 days in March, 30 days in April, 31 days in May, 30 in June, 31 in July, 31 in August, 30 in September, 31 in October, 30 in November, 31 in December.
... | ```python
a1 = '31 28 31 30 31 30 31 31 30 31 30 31 '
a2 = '31 29 31 30 31 30 31 31 30 31 30 31 '
s = a1 + a1 + a1 + a2 + a1 + a1
n = input()
ss = input().strip()
print(["NO",'YES'][ss in s])
``` |
91_C. Ski Base | A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.
In the constructing process m bidirectional ski r... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1] * n
def find(self, x: int) -> int:
if self.nodes[x] < 0:
... |
948_A. Protect Sheep | Bob is a farmer. He has a large pasture with many sheep. Recently, he has lost some of them due to wolf attacks. He thus decided to place some shepherd dogs in such a way that all his sheep are protected.
The pasture is a rectangle consisting of R × C cells. Each cell is either empty, contains a sheep, a wolf or a dog... | ```python
R,C=map(int, input().split())
m=[[str(j) for j in input()] for i in range(R)]
row=0
for i in range(R):
if row == 1:
break
for j in range(C):
if m[i][j] == ".":
m[i][j] = "D"
elif m[i][j] == "S":
if j > 0 and m[i][j-1] == "W":
row=1
... |
976_A. Minimum Binary Number | String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001".
You are given a correct string s.
You can perform two different operations on this string:
1. swap any pair of adjacent characters (for example, "101" <image>... | ```python
n=int(input())
a=input()
count1=0
for item in a:
if(item=='1'):
count1=count1+1
if(count1>=1):
print(1,end="")
for i in range(0,len(a)-count1):
print(0,end="")
``` |
p02645 Tokio Marine & Nichido Fire Insurance Programming Contest 2020 - Nickname | When you asked some guy in your class his name, he called himself S, where S is a string of length between 3 and 20 (inclusive) consisting of lowercase English letters. You have decided to choose some three consecutive characters from S and make it his nickname. Print a string that is a valid nickname for him.
Constra... | ```python
import sys
s = input()
print(s[:3])
``` |
p02774 AtCoder Beginner Contest 155 - Pairs | We have N integers A_1, A_2, ..., A_N.
There are \frac{N(N-1)}{2} ways to choose two of them and form a pair. If we compute the product of each of those pairs and sort the results in ascending order, what will be the K-th number in that list?
Constraints
* All values in input are integers.
* 2 \leq N \leq 2 \times 1... | ```python
N,K,*A = map(int, open(0).read().split())
Ap = []
An = []
Az = []
for c in A:
if c>0:
Ap.append(c)
elif c<0:
An.append(c)
else:
Az.append(c)
l = -10**20
r = 10**20
Ap.sort(reverse=True)
An.sort()
while l+1<r:
s = (l+r)//2
cnt = 0
j = len(Ap)-1
for i in range(len(Ap)):
while j>-1 ... |
p02909 AtCoder Beginner Contest 141 - Weather Prediction | The weather in Takahashi's town changes day by day, in the following cycle: Sunny, Cloudy, Rainy, Sunny, Cloudy, Rainy, ...
Given is a string S representing the weather in the town today. Predict the weather tomorrow.
Constraints
* S is `Sunny`, `Cloudy`, or `Rainy`.
Input
Input is given from Standard Input in the... | ```python
S=input()
L=["Sunny","Cloudy","Rainy"]
print(L[(L.index(S)+1)%3])
``` |
p03044 AtCoder Beginner Contest 126 - Even Relation | We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices p... | ```python
n=int(input())
path=[[] for i in range(n)]
for i in range(n-1):
a,b,c=map(int, input().split())
path[a-1].append([b-1,c%2])
path[b-1].append([a-1,c%2])
ans=[-1]*n
ans[0]=0
q=[0]
while q:
nq=[]
for k in q:
for i,j in path[k]:
if ans[i]==-1:
ans[i]=(ans[k]... |
p03186 AtCoder Grand Contest 030 - Poisonous Cookies | Takahashi has A untasty cookies containing antidotes, B tasty cookies containing antidotes and C tasty cookies containing poison.
Eating a cookie containing poison results in a stomachache, and eating a cookie containing poison while having a stomachache results in a death. As he wants to live, he cannot eat one in su... | ```python
a,b,c=map(int,input().split())
if b+a+1>=c:
print(b+c)
else:
print(b+a+b+1)
``` |
p03333 AtCoder Grand Contest 025 - Interval Game | Takahashi and Aoki will play a game with a number line and some segments. Takahashi is standing on the number line and he is initially at coordinate 0. Aoki has N segments. The i-th segment is [L_i,R_i], that is, a segment consisting of points with coordinates between L_i and R_i (inclusive).
The game has N steps. The... | ```python
import heapq
N=int(input())
rque=[]
rque2=[]
lque=[]
lque2=[]
for i in range(N):
l,r=map(int,input().split())
rque.append((-l,i))
rque2.append((-l,i))
lque.append((r,i))
lque2.append((r,i))
heapq.heapify(rque)
heapq.heapify(lque)
used=set([])
pos=0
dir="R"
ans=0
check=set([i for i in ran... |
p03492 AtCoder Regular Contest 087 - Squirrel Migration | There is a tree with N vertices. The vertices are numbered 1 through N. The i-th edge (1 \leq i \leq N - 1) connects Vertex x_i and y_i. For vertices v and w (1 \leq v, w \leq N), we will define the distance between v and w d(v, w) as "the number of edges contained in the path v-w".
A squirrel lives in each vertex of ... | ```python
from collections import defaultdict
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def main():
def k_fix_way(com_n, com_r):
if (com_n, com_r) in kmemo:
return kmemo[(com_n, com_r)]
res = kmemo[(com_n, com_r)] = fac[co... |
p03654 AtCoder Grand Contest 018 - Tree and Hamilton Path | There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i.
Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the ... | ```python
import sys
input = sys.stdin.readline
from collections import defaultdict
n = int(input())
abd = [list(map(int,input().split())) for i in range(n-1)]
if n == 2:
print(abd[0][2])
exit()
graph = [[] for i in range(n+1)]
deg = [0 for i in range(n+1)]
for a,b,d in abd:
graph[a].append((b,d))
graph[b].appe... |
p03810 AtCoder Grand Contest 010 - Decrementing | There are N integers written on a blackboard. The i-th integer is A_i, and the greatest common divisor of these integers is 1.
Takahashi and Aoki will play a game using these integers. In this game, starting from Takahashi the two player alternately perform the following operation:
* Select one integer on the blackbo... | ```python
#d
#the niumbers of evens is important
#the point is, there is no influence to odd/even if you divide them by odd numbers.
#You should do simulation only in the case where there is one odd over 3 and even numbers of even numbers
from fractions import gcd
def count(a):
odd, even = 0,0
for x in a:
... |
p00067 The Number of Island | There is a plan view consisting of 12 vertical and 12 horizontal squares showing the terrain. Each square is painted white or black. White represents the sea and black represents the land. When two black squares touch each other vertically or horizontally, they are said to be continuous. In this plan view, the area cre... | ```python
c=0
def f(a,x,y):
if 0<=x<12 and 0<=y<12 and a[y][x]=='1':
a[y][x]='0'
for dx,dy in [[-1,0],[1,0],[0,-1],[0,1]]:f(a,x+dx,y+dy)
while 1:
try:
if c:input()
except:break
a = [list(input()) for _ in [0]*12]
c=1;b=0
for i in range(12):
for j in range(12):
... |
p00199 Chairs Where Demanding People Sit | The neutral city of Eyes City, in the heart of the four countries, is home to the transcontinental train Bandai. The platform has a row of chairs for passengers waiting for the Bandai, and people who enter the platform can use the chairs freely.
The Bandai is cheap, fast and comfortable, so there are a constant number... | ```python
INF = 10 ** 20
while True:
n, m = map(int, input().split())
if not n:
break
chairs = list("#" * n)
def sit(s):
if s == "A":
chairs[chairs.index("#")] = "A"
elif s == "B":
for i in range(n - 1, -1, -1):
if chairs[i] == "#" and (i == 0 or chairs[i - 1] != "A") and... |
p00353 Shopping | You are now in a bookshop with your friend Alice to buy a book, "The Winning Strategy for the Programming Koshien Contest,” just released today. As you definitely want to buy it, you are planning to borrow some money from Alice in case the amount you have falls short of the price. If the amount you receive from Alice s... | ```python
m,a,b=map(int,input().split())
if m>=b:
print(0)
elif m+a<b:
print("NA")
else:
print(b-m)
``` |
p00560 Semiexpress | The JOI Railways is the only railway company in the Kingdom of JOI. There are $N$ stations numbered from $1$ to $N$ along a railway. Currently, two kinds of trains are operated; one is express and the other one is local.
A local train stops at every station. For each $i$ ($1 \leq i < N$), by a local train, it takes $A... | ```python
from heapq import heapify, heappop, heappush
N, M, K = map(int, input().split())
A, B, C = map(int, input().split())
T = int(input())
S = [int(input())-1 for i in range(M)]
def f(rt, rn):
return min(rt // A, rn-1)
ans = 0
que = []
for i in range(M-1):
s0 = S[i]; s1 = S[i+1]
if B*s0 <= T:
... |
p00713 Circle and Points | You are given N points in the xy-plane. You have a circle of radius one and move it on the xy-plane, so as to enclose as many of the points as possible. Find how many points can be simultaneously enclosed at the maximum. A point is considered enclosed by a circle when it is inside or on the circle.
<image>
Fig 1. Cir... | ```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**13
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 ... |
p01415 Starting Line | Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well.
Today's training is to develop physical strength and judgment by running on a straight road. The rabbit is now standing at the starting line and looking out over a long, long road.
There... | ```python
N, K, T, U, V, L = map(int, input().split())
ans = 0
l = 0
t = 0
k = 0
for _ in range(N + 1):
if _ == N:
d = L
else:
d = int(input())
length = d - l
l = d
while t > 0 or k > 0:
if t > 0:
if t * V >= length:
tmp = (t * V - length) / V
... |
p01731 Thread Tree | Nathan O. Davis has been running an electronic bulletin board system named JAG-channel. He is now having hard time to add a new feature there --- threaded view.
Like many other bulletin board systems, JAG-channel is thread-based. Here a thread (also called a topic) refers to a single conversation with a collection of ... | ```python
import sys
sys.setrecursionlimit(1010)
N = int(input())
src = []
for i in range(N):
k = int(input())
s = input()
src.append((s,[]))
if i == 0: continue
src[k-1][1].append(i)
def dfs(i,depth):
s,ch = src[i]
print('.'*depth + s)
for c in ch:
dfs(c,depth+1)
dfs(0,0)
``` |
p01869 28 | Problem statement
Cards with ranks of $ 2 $ and $ 8 $ are powerful in card game millionaires. Therefore, we call an integer consisting of only the numbers $ 2 $ and $ 8 $ in $ 10 $ decimal notation a good integer. The best integers are listed from the smallest to $ 2, 8, 22, 28, 82, 88, \ cdots $.
Let $ n $ be a posi... | ```python
import bisect
import sys
sys.setrecursionlimit(10000)
a=[]
def f(a,bin,n):
if bin>n:return
if bin:a+=[bin]
f(a,bin*10+2,n)
f(a,bin*10+8,n)
def g(n,p):
m=-1<<20
x=bisect.bisect_left(a,n)
if x!=len(a) and a[x]==n:m=1
if a[p]**2>n:return m
if n%a[p]==0:m=g(n//a[p],p)+1
re... |
p02150 Milk | Problem
If you bring an empty bottle of $ a $ milk, you can exchange it for a new bottle of $ b $ milk.
How many bottles of milk can Mr. Kawabayashi, who initially has a bottle of $ x $ milk, drink? Output the remainder after dividing by $ 1000000007 $.
Constraints
The input satisfies the following conditions.
* $ ... | ```python
a, b, x = map(int, input().split())
print((x+max(0, x-b)//(a-b)*b)%1000000007)
``` |
p02291 Reflection | For given three points p1, p2, p, find the reflection point x of p onto p1p2.
<image>
Constraints
* 1 ≤ q ≤ 1000
* -10000 ≤ xi, yi ≤ 10000
* p1 and p2 are not identical.
Input
xp1 yp1 xp2 yp2
q
xp0 yp0
xp1 yp1
...
xpq−1 ypq−1
In the first line, integer coordinates of p1 and p2 are given. Then, q queries are giv... | ```python
import math
def equals(a, b):
return abs(a - b) < 1e-10
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def _... |
p02438 Splice | For $n$ lists $L_i$ $(i = 0, 1, ..., n-1)$, perform a sequence of the following operations.
* insert($t$, $x$): Insert an integer $x$ at the end of $L_t$.
* dump($t$): Print all elements in $L_t$.
* splice($s$, $t$): Transfer elements of $L_s$ to the end of $L_t$. $L_s$ becomes empty.
In the initial state, $L_i$ $(... | ```python
import sys
from collections import defaultdict, deque
sys.stdin.readline().split()
A = defaultdict(deque)
ans = []
for query in sys.stdin:
if query[0] == '0':
t, x = query[2:].split()
A[t].append(x)
elif query[0] == '1':
ans.append(' '.join(A[query[2:-1]]) + '\n')
else:
... |
1006_E. Military Problem | In this problem you will have to help Berland army with organizing their command delivery system.
There are n officers in Berland army. The first officer is the commander of the army, and he does not have any superiors. Every other officer has exactly one direct superior. If officer a is the direct superior of officer... | ```python
"""
Satwik_Tiwari ;) .
30th july , 2020 - Thursday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io impor... |
102_D. Buses | Little boy Gerald studies at school which is quite far from his house. That's why he has to go there by bus every day. The way from home to school is represented by a segment of a straight line; the segment contains exactly n + 1 bus stops. All of them are numbered with integers from 0 to n in the order in which they f... | ```python
a,b=map(int,input().split())
z=[]
g=10**9+7
def f():
return map(int,input().split())
if b==0:
print (0)
else:
s=set()
for i in range(b):
x,y=f()
z.append((x,y))
s.add(x)
s.add(y)
s.add (0)
s.add (a)
s = sorted(list(s))
a=len(s)-1
s=dict([(s[j... |
1051_D. Bicolorings | You are given a grid, consisting of 2 rows and n columns. Each cell of this grid should be colored either black or white.
Two cells are considered neighbours if they have a common border and share the same color. Two cells A and B belong to the same component if they are neighbours, or if there is a neighbour of A tha... | ```python
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self... |
1073_E. Segment Sum | You are given two integers l and r (l ≤ r). Your task is to calculate the sum of numbers from l to r (including l and r) such that each number contains at most k different digits, and print this sum modulo 998244353.
For example, if k = 1 then you have to calculate all numbers from l to r such that each number is form... | ```python
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
l, r, k = map(int, input().split())
valid_bits, is_valid_bits = [], [0] * 1024
for bit in range(1024):
if bin(bit).count(... |
1095_E. Almost Regular Bracket Sequence | You are given a bracket sequence s consisting of n opening '(' and closing ')' brackets.
A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters '1' and '+' between the original characters of the sequence. For example, bracket sequences "()(... | ```python
n = int(input())
lis = list(input())
if n%2:
print(0)
else:
st=[]
for i in range(n):
if lis[i]==')' and len(st)>0 and st[-1]=='(':
st.pop()
else:
st.append(lis[i])
if len(st)==2 and st[0]==st[1]:
if st[0]=='(':
pre=[0]*(n+2)
... |
1143_B. Nirvana | Kurt reaches nirvana when he finds the product of all the digits of some positive integer. Greater value of the product makes the nirvana deeper.
Help Kurt find the maximum possible product of digits among all integers from 1 to n.
Input
The only input line contains the integer n (1 ≤ n ≤ 2⋅10^9).
Output
Print the... | ```python
l = list(int(c) for c in str(int(input())))
def prod(l):
p = 1
for d in l:
p *= max(d, 1)
return p
m = prod(l)
i = len(l) - 1
while i >= 0:
while i >= 0 and l[i] == 9:
i -= 1
if i < 0:
break
l[i] = 9
while i > 0 and l[i - 1] == 0:
l[i - 1] = 9
... |
1163_B2. Cat Party (Hard Edition) | This problem is same as the previous one, but has larger constraints.
Shiro's just moved to the new house. She wants to invite all friends of her to the house so they can play monopoly. However, her house is too small, so she can only invite one friend at a time.
For each of the n days since the day Shiro moved to th... | ```python
n = int(input())
a = list(map(int,input().split()))
if(n == 1 or n == 2):
print(n)
exit()
notpar = 0
occ = [0 for i in range(10**5 + 1)]
base = 1
gotone = False
leader = -1
leadby = 0
best = 0
occ[a[0]] += 1
cnt = 1
at1 = 1
for i in range(1, n):
occ[a[i]] +=1
if(occ[a[i]] == 1):
... |
1183_H. Subsequences (hard version) | The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between th... | ```python
def main():
from sys import stdin
input = stdin.readline
# input = open('25-B.txt', 'r').readline
n, k = map(int, input().split())
s = input()[:-1]
dp = [[0] * 26 for i in range(n + 1)]
dp[0][0] = 1
for ch in s:
j = ord(ch) - ord('a')
for i in range(n, 0, -1):
... |
1201_C. Maximum Median | You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The... | ```python
n , k =map(int,input().split())
arr = list(map(int,input().split()))
arr.sort()
def check(x):
moves = 0
for i in range(n//2,n):
if x - arr[i] > 0:
moves += x - arr[i]
if moves > k:
return False
if moves <= k:
return True
else:
return Fals... |
1243_B2. Character Swap (Hard Version) | This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many ... | ```python
t = int(input())
def equal(s, t):
s = [x for x in s]
t = [x for x in t]
# diff = [x for x in range(len(s)) if s[x] != t[x]]
ans = []
for i in range(len(s)):
for j in range(i+1, len(s)):
if s[i] == s[j]:
s[j], t[i] = t[i], s[j]
ans.append... |
1263_A. Sweet Problem | You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats... | ```python
from math import ceil
for T in range(int(input())):
r , g , b = sorted(list(map(int ,input().split())))
t = b -g
if t >= r :
print(r +g)
else :
print(r + g - ceil((r-t)/2))
``` |
1284_D. New Year and Conference | Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is s... | ```python
import sys
input = sys.stdin.readline
import heapq
n=int(input())
C=[tuple(map(int,input().split())) for i in range(n)]
CA=[]
CB=[]
for ind,(a,b,c,d) in enumerate(C):
CA.append((a,0,ind))
CA.append((b,1,ind))
CB.append((c,0,ind))
CB.append((d,1,ind))
CA.sort()
CB.sort()
SMAX=[]
EMIN=[]... |
138_B. Digits Permutations | Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so o... | ```python
import itertools
def countZeroes(s):
ret = 0
for i in s:
if i != '0':
break
ret += 1
return ret
def stupid(n):
ansMax = 0
bn1 = n
bn2 = n
for n1 in itertools.permutations(n):
for n2 in itertools.permutations(n):
val = str(int(''.joi... |
1454_F. Array Partition | You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + ... | ```python
# Author : nitish420 --------------------------------------------------------------------
import math
import os
import sys
from io import BytesIO, IOBase
# mod=10**9+7
from collections import defaultdict
from bisect import bisect_left
def main():
for _ in range(int(input())):
n=int(input())
arr=list(map... |
1479_A. Searching Local Minimum | This is an interactive problem.
Homer likes arrays a lot and he wants to play a game with you.
Homer has hidden from you a permutation a_1, a_2, ..., a_n of integers 1 to n. You are asked to find any index k (1 ≤ k ≤ n) which is a local minimum.
For an array a_1, a_2, ..., a_n, an index i (1 ≤ i ≤ n) is said to be... | ```python
from collections import deque
from typing import List
from sys import stdout
class ContestParser:
"""Helper module to read/write
Commonly in programming competition input for a problem is given with space separated numbers and strings.
Standard python input() functionality is clunky when dealin... |
1505_G. Encoded message |
Input
The first line of the input contains a single integer N (1 ≤ N ≤ 24). The next N lines contain 5 space-separated integers each. The first three integers will be between 0 and 2, inclusive. The last two integers will be between 0 and 3, inclusive. The sum of the first three integers will be equal to the sum of ... | ```python
A = [
'a 1 0 0 1 0',
'b 1 1 0 2 0',
'c 2 0 0 1 1',
'd 2 1 0 1 2',
'e 1 1 0 1 1',
'f 2 1 0 2 1',
'g 2 2 0 2 2',
'h 1 2 0 2 1',
'i 1 1 0 1 1',
'j 1 2 0 1 2',
'k 1 0 1 2 0',
'l 1 1 1 3 0',
'm 2 0 1 2 1',
'n 2 1 1 2 2',
'o 1 1 1 2 1',
'p 2 1 1 3 1',
'q 2 2 1 3 2',
'r 1 2 1 3 1',
's 1 1 1 2 1',
't 1 2 1 2 2',
'u 1... |
1529_A. Eshag Loves Big Arrays | Eshag has an array a consisting of n integers.
Eshag can perform the following operation any number of times: choose some subsequence of a and delete every element from it which is strictly larger than AVG, where AVG is the average of the numbers in the chosen subsequence.
For example, if a = [1 , 4 , 3 , 2 , 4] and ... | ```python
import sys
#import random
from bisect import bisect_right as rb
from collections import deque
#sys.setrecursionlimit(10**8)
from queue import PriorityQueue
#from math import *
input_ = lambda: sys.stdin.readline().strip("\r\n")
ii = lambda : int(input_())
il = lambda : list(map(int, input_().split()))
ilf = l... |
160_A. Twins | Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like.
Now let's imagine a typical morning in your family. You haven't w... | ```python
n = int(input())
a = sorted(list(map(int, input().split())))[::-1]
b = sum(a)//2
sum1 = count = 0
for i in a:
sum1+=i
count+=1
if sum1>b:
break
print(count)
``` |
227_C. Flying Saucer Segments | An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the... | ```python
def binpow(a,n):
res = 1
while(n>0):
if(n&1):
res = (res*a)%m
a = (a*a)%m
n>>=1
return res
n,m = map(int,input().split())
ans = binpow(3,n)-1
if(ans%m ==0 and ans != 0):
print(m-1)
else:
print(ans%m)
``` |
251_A. Points on Line | Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen point... | ```python
from sys import stdin
a,b=map(int,stdin.readline().split());a+=1
z=[1]+list(map(int,stdin.readline().split()));i,j=1,1;ans=0
r=lambda x:(x*(x+1))//2
while i<a:
if j<=i:j=i
while j<a and abs(z[j]-z[i])<=b:j+=1
if j-i-1>=2:ans+=r(j-i-2)
i+=1
print(ans)
``` |
276_B. Little Girl and Game | The Little Girl loves problems on games very much. Here's one of them.
Two players have got a string s, consisting of lowercase English letters. They play a game that is described by the following rules:
* The players move in turns; In one move the player can remove an arbitrary letter from string s.
* If the pl... | ```python
import sys
#sys.stdin = open('in', 'r')
#sys.stdout = open('out', 'w')
def Out(x):
sys.stdout.write(str(x) + '\n')
def In():
return sys.stdin.readline().strip()
def main():
s = str(input())
Map = {}
for word in s:
if word not in Map:
Map[word] = 1
else:... |
322_B. Ciel and Flowers | Fox Ciel has some flowers: r red flowers, g green flowers and b blue flowers. She wants to use these flowers to make several bouquets. There are 4 types of bouquets:
* To make a "red bouquet", it needs 3 red flowers.
* To make a "green bouquet", it needs 3 green flowers.
* To make a "blue bouquet", it needs 3 ... | ```python
a,b,c = map(int,input().split())
max_mix = min(a,b,c)
res = -99999999999999
for i in range (0,min(3,max_mix)+1):
pos = (i+(a-i)//3 + (b-i)//3 + (c-i)//3)
res=max(res,pos)
print(res)
``` |
370_A. Rook, Bishop and King | Little Petya is learning to play chess. He has already learned how to move a king, a rook and a bishop. Let us remind you the rules of moving chess pieces. A chessboard is 64 square fields organized into an 8 × 8 table. A field is represented by a pair of integers (r, c) — the number of the row and the number of the co... | ```python
def benteng(x1,y1,x2,y2):
if(x1==x2 or y1==y2):
return 1
else:
return 2
def mentri(x1,y1,x2,y2):
if(abs(x1-x2)==abs(y1-y2)):
return 1
if((abs(x1-x2)+abs(y1-y2))%2==0):
return 2
return 0
def raja(x1,y1,x2,y2):
a=abs(x1-x2)
b=abs(y1-y2)
if(a>b):
... |
391_F1. Stock Trading | This problem consists of three subproblems: for solving subproblem F1 you will receive 8 points, for solving subproblem F2 you will receive 15 points, and for solving subproblem F3 you will receive 10 points.
Manao has developed a model to predict the stock price of a company over the next n days and wants to design a... | ```python
import sys
ammount_prices, days_for_trading=map(int, input().split())
stonks=[]
for i in range (0, ammount_prices):
price=int(sys.stdin.readline())
stonks.append(price)
def get_max(days_for_trading, stonks):
size_prices = len(stonks)
if size_prices == 0 or size_prices == 1 or days_for_tradi... |
441_B. Valera and Fruits | Valera loves his garden, where n fruit trees grow.
This year he will enjoy a great harvest! On the i-th tree bi fruit grow, they will ripen on a day number ai. Unfortunately, the fruit on the tree get withered, so they can only be collected on day ai and day ai + 1 (all fruits that are not collected in these two days,... | ```python
frukti_po_dnyam = {}
n, resurs =map(int,input().split(' '))
for i in range(n):
den, chislo_fruktov = map(int, input().split(' '))
if den in frukti_po_dnyam:
frukti_po_dnyam[den] += chislo_fruktov
else:
frukti_po_dnyam[den] = chislo_fruktov
if den + 1 not in frukti_po_dnyam:
... |
463_C. Gargari and Bishops | Gargari is jealous that his friend Caisa won the game from the previous problem. He wants to prove that he is a genius.
He has a n × n chessboard. Each cell of the chessboard has a number written on it. Gargari wants to place two bishops on the chessboard in such a way that there is no cell that is attacked by both of... | ```python
import sys
input=sys.stdin.buffer.readline
t=1
for __ in range(t):
a=[]
n=int(input())
for i in range(n):
b=list(map(int,input().split()))
a.append(b)
dr={}
di={}
for i in range(n):
for j in range(n):
dr[i+j]=dr.get(i+j,0)+a[i][j]
di[... |
487_B. Strip | Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece... | ```python
def split(a,n,s,l):
pieces = []
i = 1
tmpmin = a[0]
tmpmax = a[0]
tmppc = [a[0]]
while i<n:
if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
tmppc.append(a[i])
if a[i]<tmpmin: tmpmin=a[i]
elif a[i]>tmpmax: tmpmax = a[i]
else:
... |
510_A. Fox And Snake | Fox Ciel starts to learn programming. The first task is drawing a fox! However, that turns out to be too hard for a beginner, so she decides to draw a snake instead.
A snake is a pattern on a n by m table. Denote c-th cell of r-th row as (r, c). The tail of the snake is located at (1, 1), then it's body extends to (1,... | ```python
n,m=map(int,input().split())
s="."*(m-1)+"#"
#print(s)
for i in range(n):
if i%2==0:print("#"*m)
else:
print(s)
s=s[::-1]
``` |
535_B. Tavas and SaDDas | Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
<image>
The problem is:... | ```python
a = input().replace("4",'0').replace("7",'1')
sumA = 0
for x in range(len(a)) : sumA += 2**x
print((int(a,2)+sumA))
``` |
55_C. Pie or die | Volodya and Vlad play the following game. There are k pies at the cells of n × m board. Each turn Volodya moves one pie to the neighbouring (by side) cell. If the pie lies at the border of the board then Volodya can move it outside the board, get the pie and win. After Volodya's move, Vlad bans some edge at the border ... | ```python
n, m, k = [int(x) for x in input().split()]
canwin = False
for i in range(k):
x, y = [int(x) for x in input().split()]
canwin |= x < 6 or n - x < 5
canwin |= y < 6 or m - y < 5
print("YES" if canwin else "NO")
``` |
608_A. Saitama Destroys Hotel | Saitama accidentally destroyed a hotel again. To repay the hotel company, Genos has volunteered to operate an elevator in one of its other hotels. The elevator is special — it starts on the top floor, can only move down, and has infinite capacity. Floors are numbered from 0 to s and elevator initially starts on floor s... | ```python
I=lambda:map(int,input().split())
n,s=I()
print(max(max(sum(I()),s)for _ in '0'*n))
``` |
792_F. Mages and Monsters | Vova plays a computer game known as Mages and Monsters. Vova's character is a mage. Though as he has just started, his character knows no spells.
Vova's character can learn new spells during the game. Every spell is characterized by two values xi and yi — damage per second and mana cost per second, respectively. Vova ... | ```python
#!/usr/bin/env python3
# solution after hint
# (instead of best hit/mana spell store convex hull of spells)
# O(n^2) instead of O(n log n)
[q, m] = map(int, input().strip().split())
qis = [tuple(map(int, input().strip().split())) for _ in range(q)]
mod = 10**6
j = 0
spell_chull = [(0, 0)] # lower hull _... |
813_C. The Tag Game | Alice got tired of playing the tag game by the usual rules so she offered Bob a little modification to it. Now the game should be played on an undirected rooted tree of n vertices. Vertex 1 is the root of the tree.
Alice starts at vertex 1 and Bob starts at vertex x (x ≠ 1). The moves are made in turns, Bob goes first... | ```python
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from collections import defaultdict,deque
n,x=list(map(int,input().split()))
edge=defaultdict(list)
child=defaultdict(list)
for i in range(n-1):
u,v=list(map(int,input().split()))
edge[u].append(v)
edge[v].append(u)
def bfsD... |
839_B. Game of the Rows | Daenerys Targaryen has an army consisting of k groups of soldiers, the i-th group contains ai soldiers. She wants to bring her army to the other side of the sea to get the Iron Throne. She has recently bought an airplane to carry her army through the sea. The airplane has n rows, each of them has 8 seats. We call two s... | ```python
n,m=map(int,input().split())
l=list(map(int,input().split()))
p=n
for i in range(m) :
b=l[i]//4
l[i]=l[i]-4*min(p,l[i]//4)
p=p-min(p,b)
p1=n*2
for i in range(m) :
b=l[i]//2
l[i]=l[i]-2*min(p1,l[i]//2)
p1=p1-min(p1,b)
p2=p+p1
p3=p
for i in range(m) :
b=l[i]//2
l[i]=l[i]-2*min(p... |
859_E. Desk Disorder | A new set of desks just arrived, and it's about time! Things were getting quite cramped in the office. You've been put in charge of creating a new seating chart for the engineers. The desks are numbered, and you sent out a survey to the engineering team asking each engineer the number of the desk they currently sit at,... | ```python
n = int(input())
m = 2 * n + 1
u = [[] for i in range(m)]
v = [0] * m
s = [0] * m
d = 10 ** 9 + 7
y = 1
for j in range(n):
a, b = map(int, input().split())
v[a] = b
if a != b:
s[b] += 1
u[b].append(a)
for b in range(m):
if not v[b]:
x = 0
p = [b]
while... |
884_D. Boxes And Balls | Ivan has n different boxes. The first of them contains some balls of n different colors.
Ivan wants to play a strange game. He wants to distribute the balls into boxes in such a way that for every i (1 ≤ i ≤ n) i-th box will contain all balls with color i.
In order to do this, Ivan will make some turns. Each turn he ... | ```python
from heapq import *
n = int(input())
a = list(map(int, input().split()))
heap = []
res = 0
for i in range(n):
heappush(heap, a[i])
if n % 2 == 0:
heappush(heap, 0)
while n > 1:
cur = heappop(heap)
cur += heappop(heap)
cur += heappop(heap)
res += cur
heappush(heap, cur)
n -= 2
p... |
908_F. New Year and Rainbow Roads | Roy and Biv have a set of n points on the infinite number line.
Each point has one of 3 colors: red, green, or blue.
Roy and Biv would like to connect all the points with some edges. Edges can be drawn between any of the two of the given points. The cost of an edge is equal to the distance between the two points it c... | ```python
def F1():
n = int(input())
ans = 0
allc = 0
bigr = 0
bigb = 0
lastr = -1
lastb = -1
lastg = -(1 << 60)
for i in range(n):
x = input().split()
pos, col = int(x[0]), x[1]
if col == 'R' or col == 'G':
if lastr != -1:
bigr... |
92_E. Ski Base | A ski base is planned to be built in Walrusland. Recently, however, the project is still in the constructing phase. A large land lot was chosen for the construction. It contains n ski junctions, numbered from 1 to n. Initially the junctions aren't connected in any way.
In the constructing process m bidirectional ski r... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
class UnionFind(object):
__slots__ = ['nodes']
def __init__(self, n: int):
self.nodes = [-1] * n
def find(self, x: int) -> int:
if self.nodes[x] < 0:
... |
958_C1. Encryption (easy) | Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted – the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one lo... | ```python
n,p = map(int,input().split())
a = list(map(int,input().split()))
forward = [a[0]]
for i in range(1,n):
forward.append(forward[-1] + a[i])
sm = sum(a)
mx = -float('inf')
for i in range(n-1):
mx = max(mx,(forward[i]%p) + ((sm -forward[i] )%p))
print(mx)
``` |
p02568 AtCoder Library Practice Contest - Range Affine Range Sum | You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
* `0 l r b c`: For each i = l, l+1, \dots, {r - 1}, set a_i \gets b \times a_i + c.
* `1 l r`: Print \sum_{i = l}^{r - 1} a_i \bmod 998244353.
Constraints
* 1 \leq N, Q \leq 500000
* 0 \leq a_i, c < 998244353
* 1 \le... | ```python
#!usr/bin/env python3
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import bisect_left, bisect_right
from functools import reduce, lru_cache
from heapq import heappush, heappop, heapify
import itertools
import math, fractions
import sys, copy
def L(): return sys.stdin.readline... |
p02699 AtCoder Beginner Contest 164 - Sheep and Wolves | There are S sheep and W wolves.
If the number of wolves is greater than or equal to that of sheep, the wolves will attack the sheep.
If the wolves will attack the sheep, print `unsafe`; otherwise, print `safe`.
Constraints
* 1 \leq S \leq 100
* 1 \leq W \leq 100
Input
Input is given from Standard Input in the fol... | ```python
s,w = map(int, input().split())
print("safe" if w<s else "unsafe")
``` |
p02965 AtCoder Grand Contest 036 - GP 2 | We have a sequence of N integers: x=(x_0,x_1,\cdots,x_{N-1}). Initially, x_i=0 for each i (0 \leq i \leq N-1).
Snuke will perform the following operation exactly M times:
* Choose two distinct indices i, j (0 \leq i,j \leq N-1,\ i \neq j). Then, replace x_i with x_i+2 and x_j with x_j+1.
Find the number of differe... | ```python
n,m=map(int,input().split())
w,u=3*m,n-1
o,f,i=998244353,[1],1
while i<w+n:f+=[f[-1]*i%o];i+=1
c=lambda n,k=u:f[n]*pow(f[n-k],o-2,o)*pow(f[k],o-2,o)
a=c(w+u)-n*c(n+m-2)
while~-n>m<w:m+=2;a-=c(n,m)*c(2*u+w-m>>1)
print(a%o)
``` |
p03248 AtCoder Regular Contest 103 - Tr/ee | You are given a string s of length n. Does a tree with n vertices that satisfies the following conditions exist?
* The vertices are numbered 1,2,..., n.
* The edges are numbered 1,2,..., n-1, and Edge i connects Vertex u_i and v_i.
* If the i-th character in s is `1`, we can have a connected component of size i by rem... | ```python
def die(): print(-1); exit()
s = input()
n = len(s)
if s[-1] == '1': die()
if s[0] == '0': die()
for i in range(n-1):
if s[i] != s[-i-2]: die()
root = last = 1
for i in range(n-1):
last+= 1
print(root, last)
if s[i] == '1': root = last
``` |
p03399 AtCoder Beginner Contest 092 - Traveling Budget | You planned a trip using trains and buses. The train fare will be A yen (the currency of Japan) if you buy ordinary tickets along the way, and B yen if you buy an unlimited ticket. Similarly, the bus fare will be C yen if you buy ordinary tickets along the way, and D yen if you buy an unlimited ticket.
Find the minimu... | ```python
A = [int(input()) for i in range(4)]
print(min(A[0],A[1]) + min(A[2],A[3]))
``` |
p03564 AtCoder Beginner Contest 076 - Addition and Multiplication | Square1001 has seen an electric bulletin board displaying the integer 1. He can perform the following operations A and B to change this value:
* Operation A: The displayed value is doubled.
* Operation B: The displayed value increases by K.
Square1001 needs to perform these operations N times in total. Find the min... | ```python
n=int(input())
k=int(input())
s=1
for i in range(n): s=min(s+k, s*2)
print(s)
``` |
p03719 AtCoder Beginner Contest 061 - Between Two Integers | You are given three integers A, B and C. Determine whether C is not less than A and not greater than B.
Constraints
* -100≤A,B,C≤100
* A, B and C are all integers.
Input
Input is given from Standard Input in the following format:
A B C
Output
If the condition is satisfied, print `Yes`; otherwise, print `No`.
... | ```python
a,b,c=map(int,input().split());print('YNeos'[a>c or b<c::2])
``` |
p03879 CODE FESTIVAL 2016 Grand Final(Parallel) - Inscribed Bicycle | Snuke received a triangle as a birthday present. The coordinates of the three vertices were (x_1, y_1), (x_2, y_2), and (x_3, y_3).
He wants to draw two circles with the same radius inside the triangle such that the two circles do not overlap (but they may touch). Compute the maximum possible radius of the circles.
C... | ```python
from math import hypot
x1, y1, x2, y2, x3, y3 = map(int, open(0).read().split())
a = hypot(x1 - x2, y1 - y2)
b = hypot(x2 - x3, y2 - y3)
c = hypot(x3 - x1, y3 - y1)
R = abs((x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)) / (a + b + c)
m = max(a, b, c)
r = m / (2 + m / R)
print("{:.12f}".format(r))
``` |
p04040 AtCoder Regular Contest 058 - Iroha and a Grid | We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.
However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there ... | ```python
from sys import stdin, stdout, stderr, setrecursionlimit
from functools import lru_cache
setrecursionlimit(10**7)
mod = 10**9 + 7
def solve():
def binom(n, k):
res = (modfact[n] * factinv[k]) % mod
res = (res * factinv[n - k]) % mod
return res
h, w, a, b = map(int, input().... |
p00121 Seven Puzzle | The 7 puzzle consists of 8 square cards and a frame that fits them snugly. Each card is numbered 0, 1, 2, ..., 7 to distinguish them from each other. You can arrange two cards vertically and four cards horizontally in the frame.
7 When you start the puzzle, first put all the cards in the frame. Only 0 cards in the fra... | ```python
from collections import deque
import copy
swap = [[1, 4], [0, 2, 5], [1, 3, 6], [2, 7], [0, 5], [1, 4, 6], [2, 5, 7], [3, 6]]
def bfs():
ia = list(range(8))
count = {str(ia): 0}
que = deque()
que.append((ia, 0))
while len(que) != 0:
state, cnt = que.popleft()
# pos:0????... |
p00254 All Numbers Lead to 6174 | Do the following for a four-digit number N consisting of numbers 0-9.
1. Let L be the number obtained as a result of arranging the numerical values of each of the N digits in descending order.
2. Let S be the number obtained as a result of arranging the numerical values of each of the N digits in ascending order.
... | ```python
while True:
number=int(input())
if number==0000:
break
trial=0
while True:
if number==6174:
print(trial)
break
box=[]
for i in range(4):
a=number%10
number=int(number/10)
box.append(a)
if bo... |
p00440 Longest Steps | problem
There are n cards with one integer from 1 to n and one blank card. Of these n + 1 cards, k cards are given, but 1 ≤ k ≤ n. You can write one integer from 1 to n on a blank card. I want to make a continuous sequence of integers as long as possible with just a given card.
Write a program that outputs the maximu... | ```python
anss = []
flag = False
def main():
N, K = [int(i) for i in input().split()]
if N == K == 0:
global flag
flag = True
return
A = [int(input()) for _ in range(K)]
A.sort()
zero = False
if A[0] == 0:
zero = True
prev = -1
last_island = -1
current... |
p00631 Split Up! | Brave Ponta and his best friend, Brave Gonta, have come to Luida's bar in search of friends to embark on an epic adventure. There are many warriors, monks and wizards in the tavern who are itching to go on an adventure.
Gonta, who is kind-hearted, cared for Ponta and said, "You can choose your friends first."
On the ... | ```python
def main():
while True:
n = int(input())
if n == 0:
break
alst = list(map(int, input().split()))
s = sum(alst)
alst = [a * 2 for a in alst]
lst = [-s]
for a in alst:
lst.extend([i + a for i in lst])
print(min(map(abs, lst)))
main()
``` |
p00775 Vampire | Vampire
Mr. C is a vampire. If he is exposed to the sunlight directly, he turns into ash. Nevertheless, last night, he attended to the meeting of Immortal and Corpse Programmers Circle, and he has to go home in the near dawn. Fortunately, there are many tall buildings around Mr. C's home, and while the sunlight is blo... | ```python
while True:
r, n = list(map(int, input().split()))
if r==0:
break
b = [0 for i in range(60)]
for i in range(n):
ll, rr, x = list(map(int, input().split()))
for j in range(ll, rr):
b[30+j] = max(b[30+j], x)
b[30-r-1], b[30+r] = 1e9, 1e9
ans = 1e9
for x in range(30-r, 30+r+1):
... |
p00906 One-Dimensional Cellular Automaton | There is a one-dimensional cellular automaton consisting of N cells. Cells are numbered from 0 to N − 1.
Each cell has a state represented as a non-negative integer less than M. The states of cells evolve through discrete time steps. We denote the state of the i-th cell at time t as S(i, t). The state at time t + 1 is... | ```python
from operator import mul
def dot(v1, v2):
return sum(map(mul, v1, v2))
def mat_mul(A, B, m):
tB = tuple(zip(*B))
return [[dot(A_i, B_j) % m for B_j in tB] for A_i in A]
def mat_pow(X, n, m):
s = len(X)
A = [[0] * s for i in range(s)]
for i in range(s):
A[i][i] = 1
wh... |
p01040 Friday the 13th | Problem
"Ritsumeikan University Competitive Programming Camp" will be held this year as well. I am very much looking forward to this annual training camp. However, I couldn't stand my desires and splurged before the training camp, so I couldn't afford it. So I decided to use the cheapest Seishun 18 Ticket to get to Mi... | ```python
def check_uruu(y):
if y % 400 == 0:
return True
elif y % 100 == 0:
return False
elif y % 4 == 0:
return True
else:
return False
nouruu = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
uruu = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
Y1, M1, D1, Y2, M2,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.