name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
907_A. Masha and Bears | A family consisting of father bear, mother bear and son bear owns three cars. Father bear can climb into the largest car and he likes it. Also, mother bear can climb into the middle car and she likes it. Moreover, son bear can climb into the smallest car and he likes it. It's known that the largest car is strictly larg... | ```python
sizes=[int(x) for x in str(input()).split(" ")]
l=(sizes[0],2*sizes[0])
m=(max(2*sizes[3]+1,sizes[1]),2*sizes[1])
s=(max(sizes[2],sizes[3]),min(2*sizes[2],2*sizes[3]))
if m[1]>=m[0] and s[1]>=s[0]:
print(l[1])
print(max(m[0],s[0])+1)
print(s[0])
else:
print(-1)
``` |
926_H. Endless Roses Most Beautiful | Arkady decided to buy roses for his girlfriend.
A flower shop has white, orange and red roses, and the total amount of them is n. Arkady thinks that red roses are not good together with white roses, so he won't buy a bouquet containing both red and white roses. Also, Arkady won't buy a bouquet where all roses have the... | ```python
n,k=map(int,input().split())
b=list(map(int,input().split()))
s=input()
a=[]
if k==1:
print(-1)
exit()
for i in range(n):
a.append((b[i],s[i]))
a.sort(reverse=True)
i=0
j=0
m1=0
q1=False
q2=False
while i!=k:
if a[j][1]!='R':
m1+=a[j][0]
g=j+0
if a[j][1]=='W':
... |
p02557 AtCoder Beginner Contest 178 - Contrast | Given are two sequences A and B, both of length N. A and B are each sorted in the ascending order. Check if it is possible to reorder the terms of B so that for each i (1 \leq i \leq N) A_i \neq B_i holds, and if it is possible, output any of the reorderings that achieve it.
Constraints
* 1\leq N \leq 2 \times 10^5
*... | ```python
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from math import gcd
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factori... |
p02688 AtCoder Beginner Contest 166 - Trick or Treat | N Snukes called Snuke 1, Snuke 2, ..., Snuke N live in a town.
There are K kinds of snacks sold in this town, called Snack 1, Snack 2, ..., Snack K. The following d_i Snukes have Snack i: Snuke A_{i, 1}, A_{i, 2}, \cdots, A_{i, {d_i}}.
Takahashi will walk around this town and make mischief on the Snukes who have no s... | ```python
n, k = map(int,input().split())
d = []
a = []
for _ in range(k):
d.append(int(input()))
a += input().split()
print(n - len(set(a)))
``` |
p02817 AtCoder Beginner Contest 149 - Strings | Given are two strings S and T consisting of lowercase English letters. Concatenate T and S in this order, without space in between, and print the resulting string.
Constraints
* S and T are strings consisting of lowercase English letters.
* The lengths of S and T are between 1 and 100 (inclusive).
Input
Input is gi... | ```python
a = input().split()
print(f"{a[1]}{a[0]}")
``` |
p02953 AtCoder Beginner Contest 136 - Build Stairs | There are N squares arranged in a row from left to right. The height of the i-th square from the left is H_i.
For each square, you will perform either of the following operations once:
* Decrease the height of the square by 1.
* Do nothing.
Determine if it is possible to perform the operations so that the heights ... | ```python
n=int(input())
a=list(map(int,input().split()))
ans="Yes"
for i in range(n-1):
if a[i]>a[i+1]:
ans="No"
elif a[i]<a[i+1]:
a[i+1]-=1
print(ans)
``` |
p03089 AtCoder Grand Contest 032 - Limited Insertion | Snuke has an empty sequence a.
He will perform N operations on this sequence.
In the i-th operation, he chooses an integer j satisfying 1 \leq j \leq i, and insert j at position j in a (the beginning is position 1).
You are given a sequence b of length N. Determine if it is possible that a is equal to b after N oper... | ```python
N = int(input())
b = list(map(int, input().split()))
a = []
for i in range(N):
x = b[i]
if x > (i+1):
print(-1)
exit()
a.insert(x-1, x)
else:
for x in a:
print(x)
``` |
p03234 AtCoder Grand Contest 028 - Chords | There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them.
Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are... | ```python
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
"""
AGC028 D
"""
import itertools
from functools import reduce
from functools import lru_cache
nn, k = map(int, input().split())
n = 2*nn
abli = []
for i in range(k):
a, b = map(int, input().split())
if a < b:
abli.append((a,... |
p03385 AtCoder Beginner Contest 093 - abc of ABC | You are given a string S of length 3 consisting of `a`, `b` and `c`. Determine if S can be obtained by permuting `abc`.
Constraints
* |S|=3
* S consists of `a`, `b` and `c`.
Input
Input is given from Standard Input in the following format:
S
Output
If S can be obtained by permuting `abc`, print `Yes`; otherwis... | ```python
print('Yes' if set(list(input()))==set(['a','b','c']) else 'No')
``` |
p03549 AtCoder Beginner Contest 078 - HSI | Takahashi is now competing in a programming contest, but he received TLE in a problem where the answer is `YES` or `NO`.
When he checked the detailed status of the submission, there were N test cases in the problem, and the code received TLE in M of those cases.
Then, he rewrote the code to correctly solve each of th... | ```python
N,M = map(int,input().split())
print(int(((N-M)*100+M*1900)/(0.5**M)))
``` |
p03705 AtCoder Grand Contest 015 - A+...+B Problem | Snuke has N integers. Among them, the smallest is A, and the largest is B. We are interested in the sum of those N integers. How many different possible sums there are?
Constraints
* 1 ≤ N,A,B ≤ 10^9
* A and B are integers.
Input
Input is given from Standard Input in the following format:
N A B
Output
Print th... | ```python
p,n,m=map(int,input().split())
if p==1:print(int(m==n))
elif n>m:print(0)
else:print((m-n)*(p-2)+1)
``` |
p03860 AtCoder Beginner Contest 048 - AtCoder *** Contest | Snuke is going to open a contest named "AtCoder s Contest". Here, s is a string of length 1 or greater, where the first character is an uppercase English letter, and the second and subsequent characters are lowercase English letters.
Snuke has decided to abbreviate the name of the contest as "AxC". Here, x is the uppe... | ```python
str = input()
print("A" + str[8] + "C")
``` |
p04026 AtCoder Regular Contest 059 - Unbalanced | Given a string t, we will call it unbalanced if and only if the length of t is at least 2, and more than half of the letters in t are the same. For example, both `voodoo` and `melee` are unbalanced, while neither `noon` nor `a` is.
You are given a string s consisting of lowercase letters. Determine if there exists a (... | ```python
S=input()
s,e=-1,-1
if len(S)==2 and S[0]==S[1]:
s,e=1,2
for i in range(len(S)-2):
if S[i]==S[i+1] or S[i]==S[i+2] or S[i+1]==S[i+2]:
s,e=i+1,i+3
break
print(s,e)
``` |
p00109 Smart Calculator | Your task is to write a program which reads an expression and evaluates it.
* The expression consists of numerical values, operators and parentheses, and the ends with '='.
* The operators includes +, - , *, / where respectively represents, addition, subtraction, multiplication and division.
* Precedence of the operat... | ```python
from collections import deque
priority = {"*":1,"/":1, "+":0, "-":0, "(":-1, ")":-1}
n = int(input())
for i in range(n):
s = input()
out = []
ope = deque([])
for j in range(len(s)):
inp = s[j]
if inp == "=":
while len(ope):
out.append(ope.pop())
... |
p00243 Filling Game | The tablet interface technology, which can be operated by touching the screen with a finger, has also been applied in the field of games, and various types of games with new operability have been created. The game currently being developed by AZ is one of them.
The requirements for this software (game) are as follows.... | ```python
def paintout_graph(s, g, color):
cnt, pre_color = 0, s[0]
que = [0]
for pos in que:
if s[pos] == pre_color:
s[pos] = color
cnt +=1
que.extend(g[pos])
return cnt
def bfs(s, graph):
que = deque([(s,0,0)])
while True:
s,pre_cnt,depth = q... |
p00424 Data Conversion | Create a program that converts data based on the given conversion table.
The characters used in the data are letters or numbers, and the letters are case sensitive. There is no regularity in the order of the characters that appear in the conversion table.
The conversion table has two characters (not a string), one be... | ```python
n=int(input())
while(n!=0):
list={}
sum=""
for i in range(n):
a,b=input().split()
list[a]=b.rstrip()
n=int(input())
for i in range(n):
s=input().rstrip()
if s in list:
sum+=list[s]
else:
sum+=s
print(sum)
n=int(input()... |
p00763 Railway Connection | Tokyo has a very complex railway system. For example, there exists a partial map of lines and stations as shown in Figure D-1.
<image>
Figure D-1: A sample railway network
Suppose you are going to station D from station A. Obviously, the path with the shortest distance is A->B->D. However, the path with the shortes... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in ... |
p00895 The Sorcerer's Donut | Your master went to the town for a day. You could have a relaxed day without hearing his scolding. But he ordered you to make donuts dough by the evening. Loving donuts so much, he can't live without eating tens of donuts everyday. What a chore for such a beautiful day.
But last week, you overheard a magic spell that ... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split... |
p01028 Yu-kun Likes an Integer | Hint
In solving this problem, the following may be referred to. Shows how to convert an integer value to a string. Assign value as a string to str.
For C
include <stdio.h>
int main () {
int value = 123; // Convert this value to a string
char str [6]; // This variable contains a string of value
sprintf (str, "% d",... | ```python
from itertools import combinations_with_replacement as cwr
n, m = map(int, input().split())
c_lst = list(map(int, input().split()))
for t in cwr((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), n):
out = ""
cost = 0
for n in t:
cost += c_lst[n]
out += str(n)
if cost <= m:
print(out)
... |
p01298 Water Tank | You built an apartment. The apartment has a water tank with a capacity of L in order to store water for the residents. The tank works as a buffer between the water company and the residents.
It is required to keep the tank "not empty" at least during use of water. A pump is used to provide water into the tank. From th... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, L = map(int, readline().split())
if N == 0:
return False
ma = 0
P = [list(map(int, readline().split())) for i in range(N)]
ma = max(u for s, t, u in P)
K = 86400
EPS = 1e-8
def check(x, M... |
p01627 Seishun 18 Kippu 2013 | Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, has a poor house and does not have much money. Therefore, he is trying to save money by using the Seishun 18 Ticket. With only one 18 ticket, you can ride a local train all day long, and you can enter and exit the ticket gates f... | ```python
N,T=map(int,input().split())
a,b,s,name1=input().split()
def func(s):
a=s[:2]
b=s[3:]
return int(a)*60+int(b)
s=func(s)
l=[]
for i in range(N-1):
t,name1,s2,name2=input().split()
t=func(t)
s2=func(s2)
if t-s>=T:
l.append([name1,t-s])
s=s2
print(len(l))
for i,j in l:
... |
p02052 Hokkaido University Easy | A: Hokkaido University Easy
Note
Please note that the problem settings are the same as problem B, except for the constraints.
story
Homura-chan, who passed Hokkaido University and is excited about the beginning of a new life. But in front of her, a huge campus awaits ...
"Eh ... I'm not in time for the next class ... | ```python
H, W = map(int, input().split())
lst = [list(input()) for _ in range(H)]
ans = 0
for ia in range(H):
for ja in range(W):
for ib in range(H):
for jb in range(W):
if lst[ia][ja] == 'B' and lst[ib][jb] == 'B':
tmp = abs(ia-ib) + abs(ja-jb)
... |
p02348 Range Update Query (RUQ) | Write a program which manipulates a sequence A = {a0, a1, . . . , an−1} with the following operations:
* update(s, t, x): change as, as+1, ..., at to x.
* find(i): output the value of ai.
Note that the initial values of ai (i = 0, 1, . . . , n−1) are 231-1.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* 0 ≤ s ≤ ... | ```python
import sys
# 区間更新一点取得
class RangeUpdateQuery:
def __init__(self, n, initial=2 ** 31 - 1):
self.n = 1 << (n - 1).bit_length()
self.INT = (-1, initial)
# 更新時刻, 値
self.segtree = [self.INT] * (2 * self.n)
# 区間[l, r)をv(時刻, 値)で更新
def update(self, l, r, v):
L, R... |
1068_A. Birthday | Ivan is collecting coins. There are only N different collectible coins, Ivan has K of them. He will be celebrating his birthday soon, so all his M freinds decided to gift him coins. They all agreed to three terms:
* Everyone must gift as many coins as others.
* All coins given to Ivan must be different.
* Not l... | ```python
N, M, K, L = map(int, input().split())
if N < M or K + L > N:
print(-1)
else:
print((L + K - 1) // M + 1 if ((L + K - 1) // M + 1) * M <= N else -1)
``` |
108_D. Basketball Team | As a German University in Cairo (GUC) student and a basketball player, Herr Wafa was delighted once he heard the news. GUC is finally participating in the Annual Basketball Competition (ABC).
A team is to be formed of n players, all of which are GUC students. However, the team might have players belonging to differen... | ```python
import sys
import math
n,m,h = [int(x) for x in input().split()]
arr = [int(x) for x in input().split()]
total = sum(arr)
if (total < n):
print ("-1")
sys.exit()
total1 = total - arr[h-1]
rem = total - total1-1
total = total - 1
ans = 1
'''
#start = total - (n-1)
#print (start)
x = start
#print (rem... |
1157_A. Reachable Numbers | Let's denote a function f(x) in such a way: we add 1 to x, then, while there is at least one trailing zero in the resulting number, we remove that zero. For example,
* f(599) = 6: 599 + 1 = 600 → 60 → 6;
* f(7) = 8: 7 + 1 = 8;
* f(9) = 1: 9 + 1 = 10 → 1;
* f(10099) = 101: 10099 + 1 = 10100 → 1010 → 101.
... | ```python
def f(n):
n = n + 1
while n % 10 == 0:
n = n // 10
return n
n = int(input())
ctr = 0
nums = {}
while n not in nums:
# print(n)
nums[n] = True
ctr += 1
n = f(n)
print(ctr)
``` |
1179_B. Tolik and His Uncle | This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | ```python
inp = list(map(int,input().split(" ")))
n = int(inp[0])
m = int(inp[1])
x = 1
y = 1
cells = n * m
up = n
down = 1
upiter = m
downiter = 1
flag = 0
count = 0
Ans = []
while(up >= down):
# print("up and down are ", up, down)
while(upiter >= 1 or downiter <= m):
if(flag == 0):
# print(str(down) + " "... |
1197_D. Yet Another Subarray Problem | You are given an array a_1, a_2, ... , a_n and two integers m and k.
You can choose some subarray a_l, a_{l+1}, ..., a_{r-1}, a_r.
The cost of subarray a_l, a_{l+1}, ..., a_{r-1}, a_r is equal to ∑_{i=l}^{r} a_i - k ⌈ (r - l + 1)/(m) ⌉, where ⌈ x ⌉ is the least integer greater than or equal to x.
The cost of empty... | ```python
#Bhargey Mehta (Junior)
#DA-IICT, Gandhinagar
import sys, math, queue
#sys.stdin = open('input.txt', 'r')
MOD = 998244353
sys.setrecursionlimit(1000000)
n, m, k = map(int, input().split())
a = list(map(int, input().split()))
dp = [[-10**20 for i in range(m)] for i in range(n)]
dp[0][0] = a[0]-k
for i in ra... |
1214_E. Petya and Construction Set | It's Petya's birthday party and his friends have presented him a brand new "Electrician-n" construction set, which they are sure he will enjoy as he always does with weird puzzles they give him.
Construction set "Electrician-n" consists of 2n - 1 wires and 2n light bulbs. Each bulb has its own unique index that is an ... | ```python
# https://codeforces.com/contest/1214/problem/E
n = int(input())
d = map(int, input().split())
d = [[2*i+1, di] for i, di in enumerate(d)]
d = sorted(d, key=lambda x:x[1], reverse = True)
edge = []
arr = [x[0] for x in d]
for i, [x, d_] in enumerate(d):
if i + d_ - 1 == len(arr) - 1:
arr.appen... |
129_D. String | One day in the IT lesson Anna and Maria learned about the lexicographic order.
String x is lexicographically less than string y, if either x is a prefix of y (and x ≠ y), or there exists such i (1 ≤ i ≤ min(|x|, |y|)), that xi < yi, and for any j (1 ≤ j < i) xj = yj. Here |a| denotes the length of the string a. The le... | ```python
from heapq import *
l=input()
k=int(input())
n=len(l)
if k>n*(n+1)/2:
print("No such line.")
quit()
ss=[(l[i],i) for i in range(n)]
heapify(ss)
while k:
k-=1
t=heappop(ss)
if k==0:
print(t[0])
else:
if t[1]<n-1:
heappush(ss,(t[0]+l[t[1]+1],t[... |
1323_A. Even Subset Sum Problem | You are given an array a consisting of n positive integers. Find a non-empty subset of its elements such that their sum is even (i.e. divisible by 2) or determine that there is no such subset.
Both the given array and required subset may contain equal values.
Input
The first line contains a single integer t (1 ≤ t ≤... | ```python
for x in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
b=[]
i=0
count=0
s=0
while i<n:
if a[i]%2==0:
count=1
s=i
break
else:
b.append(i)
i+=1
if count==1:
print(1)
pri... |
1363_F. Rotating Substrings | You are given two strings s and t, each of length n and consisting of lowercase Latin alphabets. You want to make s equal to t.
You can perform the following operation on s any number of times to achieve it —
* Choose any substring of s and rotate it clockwise once, that is, if the selected substring is s[l,l+1..... | ```python
def read_int():
return int(input())
def read_ints():
return map(int, input().split(' '))
t = read_int()
for case_num in range(t):
n = read_int()
cnt = [0 for i in range(26)]
ps = [[0 for j in range(n + 1)] for i in range(26)]
pt = [[0 for j in range(n + 1)] for i in range(26)]
... |
1384_B1. Koa and the Beach (Easy Version) | The only difference between easy and hard versions is on constraints. In this version constraints are lower. You can make hacks only if all versions of the problem are solved.
Koa the Koala is at the beach!
The beach consists (from left to right) of a shore, n+1 meters of sea and an island at n+1 meters from the shor... | ```python
ans = []
for stp in range(int(input())):
n, k, L = map(int, input().split())
u = list(map(int, input().split()))
p = list(range(k)) + list(range(k, 0, -1))#prilivy
w = [1] * (2 * k) #mogno li doplit' v etu fasu priliva
#if u[i] + p[(i + j) % len(p)] > L:
#print(*p)
#print()
for... |
1405_C. Balanced Bitstring | A bitstring is a string consisting only of the characters 0 and 1. A bitstring is called k-balanced if every substring of size k of this bitstring has an equal amount of 0 and 1 characters (k/2 of each).
You are given an integer k and a string s which is composed only of characters 0, 1, and ?. You need to determine w... | ```python
for _ in range(int(input())):
n,k = map(int,input().split())
s = input()
l = [-1]*k
f = 0
for i in range(len(s)):
if s[i] != "?":
if l[i%k] == -1:
l[i%k] = int(s[i])
else:
if l[i%k] != int(s[i]):
f = 1
... |
1426_E. Rock, Paper, Scissors | Alice and Bob have decided to play the game "Rock, Paper, Scissors".
The game consists of several rounds, each round is independent of each other. In each round, both players show one of the following things at the same time: rock, paper or scissors. If both players showed the same things then the round outcome is a ... | ```python
def maximum_wins(a1,a2,a3,rock,scissor,paper):
ans=0
mini1=min(a1,scissor)
ans+=mini1
scissor-=mini1
mini2=min(a2,paper)
ans+=mini2
paper-=mini2
mini3=min(a3,rock)
rock-=mini3
ans+=mini3
return ans
def minimum_wins(rock,paper,scissor,a1,a2,a3):
return max(0,a1-... |
144_D. Missile Silos | A country called Berland consists of n cities, numbered with integer numbers from 1 to n. Some of them are connected by bidirectional roads. Each road has some length. There is a path from each city to any other one by these roads. According to some Super Duper Documents, Berland is protected by the Super Duper Missile... | ```python
import sys
n,m,s=map(int,sys.stdin.readline().split())
p=[[] for i in range(n+1)]
for i in range(m):
u, v, w = map(int, input().split())
p[u].append((v, w))
p[v].append((u, w))
l = int(input())
t = [l + 1] * (n + 1)
t[s], q = 0, {s}
while q:
u = q.pop()
r = t[u]
for v, w in p[... |
1473_D. Program | You are given a program that consists of n instructions. Initially a single variable x is assigned to 0. Afterwards, the instructions are of two types:
* increase x by 1;
* decrease x by 1.
You are given m queries of the following format:
* query l r — how many distinct values is x assigned to if all the... | ```python
import sys
for iter in range(int(sys.stdin.readline())):
n, m = map(int, sys.stdin.readline().split())
s = input()
balance = [0] * (n + 1)
for i in range(n):
if s[i] == '+':
balance[i + 1] = balance[i] + 1
else:
balance[i + 1] = balance[i] - 1
max_p... |
1499_F. Diameter Cuts | You are given an integer k and an undirected tree, consisting of n vertices.
The length of a simple path (a path in which each vertex appears at most once) between some pair of vertices is the number of edges in this path. A diameter of a tree is the maximum length of a simple path between all pairs of vertices of thi... | ```python
import sys
from collections import deque
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
mod = 998244353
N,K = mi()
edge = [[] for i in range(N)]
for _ in range(N-1):
a,b = mi()
edge[a-1].append(b-1)
edge[b-1].append(a-1)
parent = [-1 f... |
1521_D. Nastia Plays with a Tree | Nastia has an unweighted tree with n vertices and wants to play with it!
The girl will perform the following operation with her tree, as long as she needs:
1. Remove any existing edge.
2. Add an edge between any pair of vertices.
What is the minimum number of operations Nastia needs to get a bamboo from a tr... | ```python
def dfs(x, e, v, g):
v[x] = True
c = 0
for y in e[x]:
if not y in v:
if dfs(y, e, v, g):
c += 1
if c > 2:
g.append((x, y))
else:
g.append((x, y))
if c < 2:
return True
if x != 1:
return False
def leaf(x, e):
p = 0
while True:
u = 0... |
1550_D. Excellent Arrays | Let's call an integer array a_1, a_2, ..., a_n good if a_i ≠ i for each i.
Let F(a) be the number of pairs (i, j) (1 ≤ i < j ≤ n) such that a_i + a_j = i + j.
Let's say that an array a_1, a_2, ..., a_n is excellent if:
* a is good;
* l ≤ a_i ≤ r for each i;
* F(a) is the maximum possible among all good arra... | ```python
import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
for t in range(int(input())):
n, l, r = map(int, input().split())
F = [0] * (n + 1)
F[0] = 1
for i in range(1, n + 1):
F[i] = i * F[i - 1] % mod
iF = [0] * (n + 1)
iF[-1] = pow(F[-1], mod - 2, mod)
for i in range(n - ... |
177_A2. Good Matrix Elements | The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exac... | ```python
n=int(input())
l=[list(map(int,input().split())) for i in range(n)]
z=[[False]*n for i in range(n)]
summ=0
for i in range(n):
for j in range(n):
if i==j and z[i][j]==False:
summ+=l[i][j]
z[i][j]=True
elif i==n//2 and z[i][j]==False:
summ+=l[i][j]
... |
220_E. Little Elephant and Inversions | The Little Elephant has array a, consisting of n positive integers, indexed from 1 to n. Let's denote the number with index i as ai.
The Little Elephant wants to count, how many pairs of integers l and r are there, such that 1 ≤ l < r ≤ n and sequence b = a1a2... alarar + 1... an has no more than k inversions.
An in... | ```python
'''
Created on 19/07/2018
@author: ernesto
'''
# XXX: http://codeforces.com/problemset/problem/220/E
# XXX: https://practice.geeksforgeeks.org/problems/magic-triplets/0
# XXX: https://gist.github.com/robert-king/5660418
class RangeBit:
def __init__(self, n):
sz = 1
while n >= sz:
... |
245_A. System Administrator | Polycarpus is a system administrator. There are two servers under his strict guidance — a and b. To stay informed about the servers' performance, Polycarpus executes commands "ping a" and "ping b". Each ping command sends exactly ten packets to the server specified in the argument of the command. Executing a program re... | ```python
n = int(input())
ab = [0,0]
for i in range(n):
t,x,y = map(int,input().split())
ab[t-1]+=x-y
print('LIVE' if ab[0]>=0 else 'DEAD')
print('LIVE' if ab[1]>=0 else 'DEAD')
``` |
26_D. Tickets | As a big fan of Formula One, Charlie is really happy with the fact that he has to organize ticket sells for the next Grand Prix race in his own city. Unfortunately, the finacial crisis is striking everywhere and all the banknotes left in his country are valued either 10 euros or 20 euros. The price of all tickets for t... | ```python
# METO Bot 0.9.9
n,m,k=map(int,input().split())
if k<m<=k+n:
t=1
for i in range(k+1):
t*=(m-i)/(n+k-(i-1))
print(1-t)
else:
print(0 if m>n+k else 1)
``` |
293_A. Weird Game | Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game.
Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fir... | ```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 i... |
340_D. Bubble Sort Graph | Iahub recently has learned Bubble Sort, an algorithm that is used to sort a permutation with n elements a1, a2, ..., an in ascending order. He is bored of this so simple algorithm, so he invents his own graph. The graph (let's call it G) initially has n vertices and 0 edges. During Bubble Sort execution, edges appear a... | ```python
def CeilIndex(A, l, r, key):
while (r - l > 1):
m = l + (r - l)//2
if (A[m] >= key):
r = m
else:
l = m
return r
def LongestIncreasingSubsequenceLength(A, size):
# Add boundary case,
# when array size is one
tail... |
364_A. Matrix | You have a string of decimal digits s. Let's define bij = si·sj. Find in matrix b the number of such rectangles that the sum bij for all cells (i, j) that are the elements of the rectangle equals a in each rectangle.
A rectangle in a matrix is a group of four integers (x, y, z, t) (x ≤ y, z ≤ t). The elements of the r... | ```python
a = int(input())
s = input()
d = {}
for i in range(len(s)):
for j in range(i, len(s)):
if j == i: t = int(s[j])
else: t += int(s[j])
d[t] = d.get(t, 0) + 1
if a == 0:
if 0 in d:
cnt_pairs = (len(s) * (len(s) + 1)) // 2
print((d[0] * cnt_pairs) + (d[0] * (cnt_pai... |
408_C. Triangle | There is a right triangle with legs of length a and b. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the app... | ```python
def pitagoras(k):
casos_possiveis = []
for n in range(1,k):
m = int((k**2 - n**2)**(0.5))
if((n**2 + m**2) == k**2):
casos_possiveis.append([n, m])
return casos_possiveis
def possivelRepresntar(k):
for n in range(1, k):
m = int((k**2 - n**2)**(0.5))
... |
47_D. Safe | Vasya tries to break in a safe. He knows that a code consists of n numbers, and every number is a 0 or a 1. Vasya has made m attempts to enter the code. After each attempt the system told him in how many position stand the right numbers. It is not said in which positions the wrong numbers stand. Vasya has been so unluc... | ```python
import os,io
from sys import stdout
# import collections
# import random
# import math
# from operator import itemgetter
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# from collections import Counter
# from decimal import Decimal
# import heapq
# from functools import lru_cache
# import sys
# ... |
504_D. Misha and XOR | After Misha's birthday he had many large numbers left, scattered across the room. Now it's time to clean up and Misha needs to put them in a basket. He ordered this task to his pet robot that agreed to complete the task at certain conditions. Before the robot puts a number x to the basket, Misha should answer the quest... | ```python
m = int(input())
values = []
idx = []
for i in range(m):
x = int(input())
ans = 0
for j,xx in enumerate(values):
if (xx^x) < x:
x^=xx
ans^=idx[j]
if x == 0:
anss = []
for j in range(i):
if (ans&1)!=0:
anss.append(j)
... |
528_B. Clique Problem | The clique problem is one of the most well-known NP-complete problems. Under some simplification it can be formulated as follows. Consider an undirected graph G. It is required to find a subset of vertices C of the maximum size such that any two of them are connected by an edge in graph G. Sounds simple, doesn't it? No... | ```python
import sys
readline = sys.stdin.readline
def main():
N = int(input())
itvs = []
for _ in range(N):
x, w = map(int, input().split())
itvs.append((x - w, x + w))
itvs.sort(key=lambda x: x[1])
ans = 0
end = -(10**9 + 1)
for l, r in itvs:
if end <= l:
... |
624_A. Save Luke | Luke Skywalker got locked up in a rubbish shredder between two presses. R2D2 is already working on his rescue, but Luke needs to stay alive as long as possible. For simplicity we will assume that everything happens on a straight line, the presses are initially at coordinates 0 and L, and they move towards each other wi... | ```python
#!/usr/bin/python3
import math
def main():
d,L,v1,v2 = [int(i) for i in input().split()]
v = v1+v2
t = (L-d) / v
print(t)
if __name__ == '__main__':
main()
``` |
672_C. Recycling Bottles | It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.
We can think Central Perk as coordinate plane. There are n bottles on the ground, the i-th bottle is located at position (xi, yi). Both Adil and Bera can c... | ```python
#!/usr/bin/env python3
# 672C_bottles.py - Codeforces.com/problemset/problem/672/C by Sergey 2016
import unittest
import sys
###############################################################################
# Bottles Class (Main Program)
########################################################################... |
697_E. PLEASE | As we all know Barney's job is "PLEASE" and he has not much to do at work. That's why he started playing "cups and key". In this game there are three identical cups arranged in a line from left to right. Initially key to Barney's heart is under the middle cup.
<image>
Then at one turn Barney swaps the cup in the midd... | ```python
from functools import reduce
mod = 1000000007
n = input()
numbers = list(map(int,input().split()))
flag = 1 if len(list(filter(lambda x: x%2 == 0,numbers))) else -1
b = reduce(lambda x,y:pow(x,y,mod),numbers,2)
b = b*pow(2,mod-2,mod)%mod # b = 2^n-1
a = (b+flag)*pow(3,mod-2,mod)%mod #a = (2^n-1 -/+ 1) / 3
pri... |
73_C. LionAge II | Vasya plays the LionAge II. He was bored of playing with a stupid computer, so he installed this popular MMORPG, to fight with his friends. Vasya came up with the name of his character — non-empty string s, consisting of a lowercase Latin letters. However, in order not to put up a front of friends, Vasya has decided to... | ```python
from math import inf
s,k= input().split()
k=int(k)
dict=[[0]*26 for i in range(26)]
for i in range(int(input())):
x=input().split()
# print(ord(x[0])-97,ord(x[1])-97)
dict[ord(x[0])-97][ord(x[1])-97]=int(x[2])
dp=[[[-inf]*26 for j in range(k+2)]for i in range(len(s))]
m=-1
for i in range(26):
... |
763_A. Timofey and a tree | Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci.
Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some verte... | ```python
n = int(input())
a = {}
color = {}
sec = []
for i in range(1, n+1):
a[i] = []
for i in range(n-1):
u, v = map(int, input().split())
a[u].append(v)
a[v].append(u)
sec.append((u, v))
b = list(map(int, input().split()))
def check_sub_color(current_node, color=0, parent=0):
if not colo... |
808_B. Average Sleep Time | It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kep... | ```python
n,k = map(int, input().split())
a = list(map(int, input().split()))
slide = a[:k]
current = sum(slide)
ans = current
for x in range(1,n-k+1):
current = current - a[x-1] + a[x + k-1]
ans += current
print("{0:.6f}".format(ans/(n-k+1)))
``` |
832_C. Strange Radiation | n people are standing on a coordinate axis in points with positive integer coordinates strictly less than 106. For each person we know in which direction (left or right) he is facing, and his maximum speed.
You can put a bomb in some point with non-negative integer coordinate, and blow it up. At this moment all people... | ```python
import math
leftpeople = set()
rightpeople = set()
n, vl = map(int, input().split())
def leftinterval(x0, v0, t):
if x0 / v0 <= t:
return (0, 10**6)
if x0 / (vl + v0) > t:
return (-1, -2)
leftbound = x0
rightbound = (vl * vl - v0 * v0) * t + x0 * v0
rightbound /= vl
r... |
853_A. Planning | Helen works in Metropolis airport. She is responsible for creating a departure schedule. There are n flights that must depart today, the i-th of them is planned to depart at the i-th minute of the day.
Metropolis airport is the main transport hub of Metropolia, so it is difficult to keep the schedule intact. This is e... | ```python
import heapq
n,k = map(int,input().split())
l = list(map(int,input().split()))
ans = [0]*n
h = []
for i in range(k):
h.append((-1*l[i],i))
heapq.heapify(h)
som = 0
for i in range(k,n+k):
if i < n:
heapq.heappush(h, (-1 * l[i], i))
x = heapq.heappop(h)
s = -1*x[0]*(i-x[1])
som += ... |
877_E. Danil and a Part-time Job | Danil decided to earn some money, so he had found a part-time job. The interview have went well, so now he is a light switcher.
Danil works in a rooted tree (undirected connected acyclic graph) with n vertices, vertex 1 is the root of the tree. There is a room in each vertex, light can be switched on or off in each ro... | ```python
class LazySegTree:
def __init__(self, init_val, seg_ide, lazy_ide, f, g, h):
self.n = len(init_val)
self.num = 2**(self.n-1).bit_length()
self.seg_ide = seg_ide
self.lazy_ide = lazy_ide
self.f = f #(seg, seg) -> seg
self.g = g #(seg, lazy, size) -> seg
... |
901_A. Hashing Trees | Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of tree... | ```python
''' Hey stalker :) '''
INF = 10**10
def main():
print = out.append
''' Cook your dish here! '''
h = get_int()
li = get_list()
possible = False
for i in range(h):
if li[i]>1 and li[i+1]>1:
possible = True
break
if not possible:
print("perfect"... |
923_D. Picking Strings | Alice has a string consisting of characters 'A', 'B' and 'C'. Bob can use the following transitions on any substring of our string in any order any number of times:
* A <image> BC
* B <image> AC
* C <image> AB
* AAA <image> empty string
Note that a substring is one or more consecutive characters. For give... | ```python
def pref_counts(string, char):
result = [0]
for c in string:
result.append(result[-1] + (c == char))
return result
def left_counts(string, char):
result = [0]
for c in string:
result.append(result[-1] + 1 if c == char else 0)
return result
s = input().replace("C", "B"... |
979_B. Treasure Hunt | After the big birthday party, Katie still wanted Shiro to have some more fun. Later, she came up with a game called treasure hunt. Of course, she invited her best friends Kuro and Shiro to play with her.
The three friends are very smart so they passed all the challenges very quickly and finally reached the destination... | ```python
from collections import Counter
n = int(input())
def score(s):
return Counter(s).most_common()[0][1];
a = [input() for i in range(3)]
l = len(a[0])
a = list(map(score, a))
if n == 1:
a = list(map(lambda x: x - 1 if x == l else x + 1, a))
else:
a = list(map(lambda x: min(l, x + n), a))
print('Draw' if a.... |
999_C. Alphabetic Removals | You are given a string s consisting of n lowercase Latin letters. Polycarp wants to remove exactly k characters (k ≤ n) from the string s. Polycarp uses the following algorithm k times:
* if there is at least one letter 'a', remove the leftmost occurrence and stop the algorithm, otherwise go to next item;
* if th... | ```python
# import collections
import string
letters = list(string.ascii_lowercase)
n, k = map(int, input().split())
a = list(input())
for i in range(n):
a[i] = (i, a[i])
a.sort(key= lambda x: x[1])
a = a[k:]
a.sort(key= lambda x: x[0])
for i in range(len(a)):
print(a[i][1], end='')
``` |
p02665 NOMURA Programming Competition 2020 - Folia | Given is an integer sequence of length N+1: A_0, A_1, A_2, \ldots, A_N. Is there a binary tree of depth N such that, for each d = 0, 1, \ldots, N, there are exactly A_d leaves at depth d? If such a tree exists, print the maximum possible number of vertices in such a tree; otherwise, print -1.
Constraints
* 0 \leq N \... | ```python
n = int(input())
a = list(map(int,input().split()))
cumsum_a = a.copy()
for i in range(n-1, -1, -1):
cumsum_a[i] += cumsum_a[i+1]
ans = 0
node = 1
for i in range(n + 1):
if a[i] > node:
ans = -1
break
ans += node
if i < n:
node = min(2 * (node - a[i]), cum... |
p02794 AtCoder Beginner Contest 152 - Tree and Constraints | We have a tree with N vertices numbered 1 to N. The i-th edge in this tree connects Vertex a_i and Vertex b_i.
Consider painting each of these edges white or black. There are 2^{N-1} such ways to paint the edges. Among them, how many satisfy all of the following M restrictions?
* The i-th (1 \leq i \leq M) restriction... | ```python
import sys
input = sys.stdin.buffer.readline
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N - 1)]
M = int(input())
UV = [list(map(int, input().split())) for _ in range(M)]
def popcnt(n):
c = (n & 0x5555555555555555) + ((n >> 1) & 0x5555555555555555)
c = (c & 0x33333333333333... |
p02930 Japanese Student Championship 2019 Qualification - Classified | AtCoder's head office consists of N rooms numbered 1 to N. For any two rooms, there is a direct passage connecting these rooms.
For security reasons, Takahashi the president asked you to set a level for every passage, which is a positive integer and must satisfy the following condition:
* For each room i\ (1 \leq i \... | ```python
#二部グラフにできるのか
#ここからよ
#実は奇サイクルを含まない=二部グラフとなる
#それぞれのレベルで奇サイクルかどうか
#二部グラフを考えて残りでもどんどん二部グラフを考えるイメージ
#最終的には1or2の状態で残る
N=int(input())
ans=[[0]*N for j in range(N)]
#nはvecの長さ
#次の通路のレベル
def dfs(n,vec,level):
global ans
#print(vec)
#print(n)
l=vec[:n//2]
r=vec[n//2:]
for i in l:
for j i... |
p03066 Tenka1 Programmer Contest 2019 - Banned X | Find the number, modulo 998244353, of sequences of length N consisting of 0, 1 and 2 such that none of their contiguous subsequences totals to X.
Constraints
* 1 \leq N \leq 3000
* 1 \leq X \leq 2N
* N and X are integers.
Input
Input is given from Standard Input in the following format:
N X
Output
Print the nu... | ```python
"""
Writer: SPD_9X2
https://atcoder.jp/contests/tenka1-2019/tasks/tenka1_2019_f
Xが偶数か奇数かは重要な気がする
長さL(<=N)の1,2で構成された文字列の問題、に変換できる
O(L)で求められばおk
dpか?
X == 1なら、0,2のみで構成されてればおk
X == 2なら、1が2つ以上入っていたら不可能 0 & 1が1つまで
X == 3なら、2を入れる場合→1は入れられないが、2を好きなだけ入れていい
入れない場合→1を2個まで入れられる
X == 4なら、
→やはり偶奇が重要か?
とどく場合... |
p03209 AtCoder Beginner Contest 115 - Christmas | In some other world, today is Christmas.
Mr. Takaha decides to make a multi-dimensional burger in his party. A level-L burger (L is an integer greater than or equal to 0) is the following thing:
* A level-0 burger is a patty.
* A level-L burger (L \geq 1) is a bun, a level-(L-1) burger, a patty, another level-(L-1) b... | ```python
n,x = map(int,input().split())
a=[0]*n
p=[0]*n
a[0]=1
p[0]=1
for i in range(1,n):
a[i]=3+2*a[i-1]
p[i]=1+2*p[i-1]
def f(n,x):
if n ==0:
return 0 if x <= 0 else 1
elif x <= 1+a[n-1]:
return f(n-1,x-1)
else:
return p[n-1]+1+f(n-1,x-a[n-1]-2)
print(f(n,x))
``` |
p03358 AtCoder Regular Contest 097 - Monochrome Cat | There is a tree with N vertices numbered 1 through N. The i-th edge connects Vertex x_i and y_i. Each vertex is painted white or black. The initial color of Vertex i is represented by a letter c_i. c_i = `W` represents the vertex is white; c_i = `B` represents the vertex is black.
A cat will walk along this tree. More... | ```python
"""
https://atcoder.jp/contests/arc097/tasks/arc097_d
始点と終点関係ある?
→逆にしても問題はない
黒い葉は完全に無視できる(落とせる)
よって、葉はすべて白
葉以外は白黒どっちもあり得る
すべての葉をめぐる最短経路?
ある葉からスタートするのは自明っぽい?
ある白からスタートするのはそう
→自分を塗ってからdfsする
→全方位木dp?
行きのみで帰らない場所が1つ存在するはず
→始点と終点のパスとそこから生える木って感じのイメージ
足踏み(停止)の回数を極力少なくしたい
→始点でも終点でもない場合、 e本の辺がつながってたらe回訪問は確定
... |
p03679 AtCoder Beginner Contest 065 - Expired? | Takahashi has a strong stomach. He never gets a stomachache from eating something whose "best-by" date is at most X days earlier. He gets a stomachache if the "best-by" date of the food is X+1 or more days earlier, though.
Other than that, he finds the food delicious if he eats it not later than the "best-by" date. Ot... | ```python
x,a,b=map(int,input().split())
print("dangerous" if (a+x)<b else "delicious" if a>=b else "safe")
``` |
p03834 AtCoder Beginner Contest 051 - Haiku | As a New Year's gift, Dolphin received a string s of length 19.
The string s has the following format: `[five lowercase English letters],[seven lowercase English letters],[five lowercase English letters]`.
Dolphin wants to convert the comma-separated string s into a space-separated string.
Write a program to perform th... | ```python
a = input()
A = a.replace(","," ")
print(A)
``` |
p03999 AtCoder Beginner Contest 045 - Many Formulas | You are given a string S consisting of digits between `1` and `9`, inclusive. You can insert the letter `+` into some of the positions (possibly none) between two letters in this string. Here, `+` must not occur consecutively after insertion.
All strings that can be obtained in this way can be evaluated as formulas.
... | ```python
s = input()
count = 0
for i in range(len(s)):
for j in range(i + 1, len(s) + 1):
count += int(s[i:j]) * (2 ** (max(0, (i - 1)) + max(0, (len(s) - j - 1))))
print(count)
``` |
p00087 Strange Mathematical Expression | Dr .: Peter, I've finally done it.
Peter: See you again? What kind of silly invention is this time?
Dr .: I finally came up with a revolutionary way to process mathematical formulas on a computer. Look at this table.
Ordinary notation | Dr.'s "breakthrough" notation
--- | ---
1 + 2 | 1 2 +
3 * 4 + 7 | 3 4 * 7 +
10 /... | ```python
# Aizu Problem 0087: Strange Mathematical Expression
#
import sys, math, os
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
def upn(inputs):
# inverse polish notation
res = 0
stack = []
for inp in inputs:
if inp in ['+',... |
p00219 A Popular Ice-cream Shop | There is an ice cream shop named Ten Ice Cream. At this store, we always have 10 types of ice cream on the shelves. The store manager creates a daily graph showing how well ice cream is selling for reference in product development.
For such a store manager, you decided to create a program that displays the number of e... | ```python
while True:
c=[0]*10
n=int(input())
if n==0:
break
for i in range(n):
a=int(input())
c[a]+=1
for i in c:
if i==0:
print("-")
else:
print("*"*i)
``` |
p00381 Transporter | In the year 30XX, an expedition team reached a planet and found a warp machine suggesting the existence of a mysterious supercivilization. When you go through one of its entrance gates, you can instantaneously move to the exit irrespective of how far away it is. You can move even to the end of the universe at will with... | ```python
from collections import defaultdict
MOD = 1000000007
n = int(input())
s = input()
t = input()
dic = defaultdict(int)
dic[s[0]] = 1
for cs, ct in zip(s[1:n-1], t[1:n-1]):
dic[cs] += dic[ct]
dic[cs] %= MOD
print(dic[t[-1]])
``` |
p00597 Finding the Largest Carbon Compound Given Its Long | An bydrocarbon is an organic compound which contains only carbons and hydrogens. An isomer is a compound that has the same number of carbons but different structures. Heptane, for example, is a hydrocarbon with 7 carbons. It has nine isomers. The structural formula of three are shown in Figure 1. Carbons are represente... | ```python
# AOJ 1011: Finding the Largest Carbon Compound Give...
# Python3 2018.7.4 bal4u
a = [0]*32
a[1], a[2] = 1, 2
for i in range(3, 31): a[i] = 3*a[i-2] + 2
while True:
try: i = int(input())
except: break
print(a[i])
``` |
p00733 Dr. Podboq or: How We Became Asymmetric | After long studying how embryos of organisms become asymmetric during their development, Dr. Podboq, a famous biologist, has reached his new hypothesis. Dr. Podboq is now preparing a poster for the coming academic conference, which shows a tree representing the development process of an embryo through repeated cell div... | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def parse(S):
S = S + "$"
cur = 0
mp = {"01": 0}
sp = {"01": {0}}
sv = {"01": (0, 1)}
lbl = 1
fmt = "0{}{}1".format
def comp(left, right):
lcs, lb = left
rcs, rb = right
a0, b0 = sv[lb]
... |
p01136 Gather the Maps! | It is said that a legendary treasure left by Mr. Yao is sleeping somewhere in Hachioji long ago. The treasure map, which is said to show its whereabouts, has been handed down by Yao's n descendants, divided into several pieces.
Now, the descendants of Mr. Yao were trying to cooperate to obtain the treasure. However, t... | ```python
while True:
n = int(input())
if n == 0:
break
days = [[] for _ in range(31)]
for i in range(n):
hima = list(map(int, input().split()))
for d in hima[1:]:
days[d].append(i)
tos = [{i} for i in range(n)]
end = {i for i in range(n)}
for i in range(31):
gather = set()
fo... |
p01275 Dial Lock | A dial lock is a kind of lock which has some dials with printed numbers. It has a special sequence of numbers, namely an unlocking sequence, to be opened.
You are working at a manufacturer of dial locks. Your job is to verify that every manufactured lock is unlocked by its unlocking sequence. In other words, you have ... | ```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 ... |
p01445 Mobile Network | The trafic on the Internet is increasing these days due to smartphones. The wireless carriers have to enhance their network infrastructure.
The network of a wireless carrier consists of a number of base stations and lines. Each line connects two base stations bi-directionally. The bandwidth of a line increases every y... | ```python
import collections
class MyList(list):
def __init__(self, x=[]):
list.__init__(self, x)
def __iadd__(self, A):
ret = MyList()
for a, b in zip(self, A):
ret.append(a + b)
return ret
def __isub__(self, A):
ret = MyList()
for a, b in zip... |
p01751 Yamanote Line | Mr. A wants to get to the destination on the Yamanote line.
After getting on the train, Mr. A gets up for a minute and sleeps for b minutes repeatedly. It is c minutes after boarding to the destination, and you can get off if you are awake at this time, but on the contrary, if you are sleeping, you will miss it. Also,... | ```python
"山手線"
a, b, c = map(int, input().split())
flag = True
if a+b == 60 and c > a: # 必ず辿りつけない
print(-1)
else:
right = 0
left = a
i = 0
while True:
# print('left : ', left)
# print('right : ', right)
# print('c : ', c)
if left >= c and c >= right:
pr... |
p01891 Cabbage | Problem statement
AOR Ika got a cabbage with $ N $ leaves. The leaves of this cabbage are numbered $ 1, \ ldots, N $ in order from the outside, and the dirtiness of the $ i $ th leaf is $ D_i $. The larger this value is, the worse the degree of dirt is. AOR Ika-chan decided to use the cabbage leaves for cooking, so sh... | ```python
#!/usr/bin/env python3
def solve(n, m, a, b, ds):
is_waste = [False for _ in range(n)]
for i in range(n):
if ds[i] >= a:
is_waste[i] = True
else:
break
if sum(is_waste) > n - m:
for i in range(n)[::-1]:
if is_waste[i]:
i... |
p02028 Mail Order | N: Mail order
Mr. Komozawa bought building blocks toys from Makai mail order.
The building blocks are in the shape of a cube with a side length of 1, and are stacked on squares divided into $ H $ pieces vertically and $ W $ pieces horizontally.
Seen from the side, $ A_1, A_2, A_3, \ dots, A_H $ blocks were stacked i... | ```python
from bisect import bisect_left as bl
from itertools import accumulate
h, w= map(int, input().split())
aList = sorted(map(int, input().split()))
bList = list(map(int, input().split()))
acc = [0]+list(accumulate(aList))
aList.insert(0, -1)
ans = 0
for b in bList:
index = bl(aList, b)
ans += acc[index ... |
p02170 Coin and Die | Problem
There are coins with front and back sides and dice with rolls from $ 1 $ to $ N $. Gacho decided to play the following games using these.
The game starts with a score of $ 0 $ and proceeds as follows.
1. Roll the dice $ 1 $ and add the number of rolls to the score.
2. If the current score is $ K $ or more, ... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline(... |
p02311 Common Tangent | Find common tangent lines of two circles $c1$ and $c2$.
Constraints
* $-1,000 \leq c1x, c1y, c2x, c2y \leq 1,000$
* $1 \leq c1r, c2r \leq 1,000$
* $c1$ and $c2$ are different
Input
Center coordinates ($cix$, $ciy$) and radii $cir$ of two circles $c1$ are $c2$ are given in the following format.
$c1x \; c1y \; c1r$
... | ```python
from math import acos, atan2, cos, hypot, isclose, pi, sin
from typing import List, Tuple
def tangent_points(c1x: float, c1y: float, c1r: float,
c2x: float, c2y: float, c2r: float) -> List[Tuple[float, float]]:
c1c2 = hypot(c2x - c1x, c2y - c1y)
t0 = atan2(c2y - c1y, c2x - c1x)
... |
p02459 Map: Search | For a dictionary $M$ that stores elements formed by a pair of a string key and an integer value, perform a sequence of the following operations. Note that each key in $M$ must be unique.
* insert($key$, $x$): Insert an element formed by a pair of $key$ and $x$ to $M$. If there is an element with $key$, replace the cor... | ```python
from collections import defaultdict
def main():
q = int(input())
d = defaultdict(int)
for _ in range(q):
para = input().split()
if para[0] == "0":
d[para[1]] = int(para[2])
elif para[0] == "1":
print(d[para[1]])
main()
``` |
1005_F. Berland and the Shortest Paths | There are n cities in Berland. Some pairs of cities are connected by roads. All roads are bidirectional. Each road connects two different cities. There is at most one road between a pair of cities. The cities are numbered from 1 to n.
It is known that, from the capital (the city with the number 1), you can reach any o... | ```python
import sys
import io, os
input = sys.stdin.buffer.readline
n,m,k = map(int,input().split())
AB = []
g = [[] for _ in range(n)]
for i in range(m):
a,b = map(int, input().split())
a,b = a-1, b-1
g[a].append(b)
g[b].append(a)
AB.append((a,b))
from collections import deque
q = deque([])
q.app... |
1029_E. Tree with Small Distances | You are given an undirected tree consisting of n vertices. An undirected tree is a connected undirected graph with n - 1 edges.
Your task is to add the minimum number of edges in such a way that the length of the shortest path from the vertex 1 to any other vertex is at most 2. Note that you are not allowed to add loo... | ```python
from sys import stdin
n = int(stdin.readline())
g = dict()
for i in range(n-1):
u,v = map(int,stdin.readline().split())
g.setdefault(u-1,[]).append(v-1)
g.setdefault(v-1, []).append(u-1)
st = [0]
rank = [0]*n
tree = [0]*n
msk = [0]*n
rd = dict()
while len(st)>0:
top = st.pop()
msk[top] = 1... |
104_D. Russian Roulette | After all the events in Orlando we all know, Sasha and Roma decided to find out who is still the team's biggest loser. Thankfully, Masha found somewhere a revolver with a rotating cylinder of n bullet slots able to contain exactly k bullets, now the boys have a chance to resolve the problem once and for all.
Sasha se... | ```python
n, k, p = map(int, input().split())
for i in range(p):
pos = int(input())
if n % 2:
if pos == n:
print('X' if k > 0 else '.', end='')
else:
if k * 2 > n + 1:
print('X' if (pos & 1) == 0 or (n - pos) // 2 \
+ n // 2 + 1<= ... |
1114_A. Got Any Grapes? | [The Duck song](https://www.youtube.com/watch?v=MtN1YnoL46Q)
For simplicity, we'll assume that there are only three types of grapes: green grapes, purple grapes and black grapes.
Andrew, Dmitry and Michal are all grapes' lovers, however their preferences of grapes are different. To make all of them happy, the followi... | ```python
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 15:00:31 2019
@author: avina
"""
x,y,z = map(int, input().strip().split())
a,b,c = map(int,input().strip().split())
k=0
if a+b+c >= x+y+z:
if a+b >= x+y:
if a>=x:
k+=1
if k != 0:
print("YES")
else:
print("NO")
``` |
1142_B. Lynyrd Skynyrd | Recently Lynyrd and Skynyrd went to a shop where Lynyrd bought a permutation p of length n, and Skynyrd bought an array a of length m, consisting of integers from 1 to n.
Lynyrd and Skynyrd became bored, so they asked you q queries, each of which has the following form: "does the subsegment of a from the l-th to the ... | ```python
import os
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
def input_as_list():
return list(map(int, input().split()))
def array_of(f, *dim):
return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f()
def main():
n, m, q = input_as_list()
... |
1162_D. Chladni Figure | Inaka has a disc, the circumference of which is n units. The circumference is equally divided by n points numbered clockwise from 1 to n, such that points i and i + 1 (1 ≤ i < n) are adjacent, and so are points n and 1.
There are m straight segments on the disc, the endpoints of which are all among the aforementioned ... | ```python
n, m = map(int, input().split())
a = set()
for i in range(m):
c, d = map(int, input().split())
c %= n
d %= n
a.add((min(c, d), max(c, d)))
def comprobar(x):
global a, n
b = set()
for c, d in a:
c += x
d += x
c %= n
d %= n
if (min(c, d), max(c, d)) not in a:
return False
#print("COMPAR... |
1183_C. Computer Game | Vova is playing a computer game. There are in total n turns in the game and Vova really wants to play all of them. The initial charge of his laptop battery (i.e. the charge before the start of the game) is k.
During each turn Vova can choose what to do:
* If the current charge of his laptop battery is strictly gre... | ```python
n=int(input())
for i in range(0,n):
p=input().rstrip().split(' ')
k=int(p[0])
K=k;
n=int(p[1])
CC=n;
a=int(p[2])
b=int(p[3])
T=min(a,b);
if (k%T==0):
H=(k//T)-1;
else:
H=(k//T)
if n>H:
print(-1)
else:
if k%a==0:
A=(k//... |
1200_D. White Lines | Gildong has bought a famous painting software cfpaint. The working screen of cfpaint is square-shaped consisting of n rows and n columns of square cells. The rows are numbered from 1 to n, from top to bottom, and the columns are numbered from 1 to n, from left to right. The position of a cell at row r and column c is r... | ```python
from collections import deque
def final(ans,arr):
queue=deque()
count=0
for i in range(n):
count=0
queue=deque()
for j in range(n-1,-1,-1):
if(queue and queue[0]-j+1>k):
queue.popleft()
count=max(count-1,0)
if(i>=arr[... |
1218_F. Workout plan | Alan decided to get in shape for the summer, so he created a precise workout plan to follow. His plan is to go to a different gym every day during the next N days and lift X[i] grams on day i. In order to improve his workout performance at the gym, he can buy exactly one pre-workout drink at the gym he is currently in ... | ```python
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]... |
1242_C. Sum Balance | Ujan has a lot of numbers in his boxes. He likes order and balance, so he decided to reorder the numbers.
There are k boxes numbered from 1 to k. The i-th box contains n_i integer numbers. The integers can be negative. All of the integers are distinct.
Ujan is lazy, so he will do the following reordering of the numbe... | ```python
import sys
n = sys.stdin.readline()
n = int(n)
def get_graph(n):
graph = []
for _ in range(n):
entries = list(map(lambda x : int(x), sys.stdin.readline().split(" ")[1:]))
graph.append(entries)
return graph
def chain(target, buckets, reverse_bucket, sum_bucket, bucket_num, val):
... |
1283_E. New Year Parties | Oh, New Year. The time to gather all your friends and reflect on the heartwarming events of the past year...
n friends live in a city which can be represented as a number line. The i-th friend lives in a house with an integer coordinate x_i. The i-th friend can come celebrate the New Year to the house with coordinate ... | ```python
# cook your dish here
n = int(input())
f = list(map(int, input().split()))
f.sort()
f1 = []
for i in range(n):
f1.append(f[i])
if (f1[0] > 0):
f1[0] -= 1
for i in range(1, n):
if (f1[i]-f1[i-1] > 1):
f1[i] -= 1
elif (f1[i] == f1[i-1]):
if (i == n-1 or f1[i+1] > f1[i])... |
1303_A. Erasing Zeroes | You are given a string s. Each character is either 0 or 1.
You want all 1's in the string to form a contiguous subsegment. For example, if the string is 0, 1, 00111 or 01111100, then all 1's form a contiguous subsegment, and if the string is 0101, 100001 or 11111111111101, then this condition is not met.
You may eras... | ```python
n=int(input())
for i in range(n):
x=input()
if '1' in x:
a=x.index('1')
c=0
for j in range(a+1,len(x)):
if x[j]=='1':
c+=x.count('0',a,j)
a=j
print(c)
else:
print(0)
``` |
1327_B. Princesses and Princes | The King of Berland Polycarp LXXXIV has n daughters. To establish his power to the neighbouring kingdoms he wants to marry his daughters to the princes of these kingdoms. As a lucky coincidence there are n other kingdoms as well.
So Polycarp LXXXIV has enumerated his daughters from 1 to n and the kingdoms from 1 to n.... | ```python
t = int(input())
setups = []
for _ in range(t):
n = int(input())
setup = []
for _ in range(n):
count_and_list = input().split(" ")
if len(count_and_list) == 1:
husbands = tuple()
else:
husbands = tuple(int(x) for x in count_and_list[1:])
setu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.