name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
322_D. Ciel and Duel | Fox Ciel is playing a card game with her friend Jiro.
Jiro has n cards, each one has two attributes: position (Attack or Defense) and strength. Fox Ciel has m cards, each one has these two attributes too. It's known that position of all Ciel's cards is Attack.
Now is Ciel's battle phase, Ciel can do the following ope... | ```python
n, m = map(int, input().split())
(a, d) = ([], [])
for i in range(n):
t, val = input().split()
(a if t == 'ATK' else d).append(int(val))
my = sorted([int(input()) for i in range(m)])
a.sort()
d.sort()
def solve1():
ret = 0
used = [False] * m
for val in d:
for i in range(m):
... |
347_B. Fixed Points | A permutation of length n is an integer sequence such that each integer from 0 to (n - 1) appears exactly once in it. For example, sequence [0, 2, 1] is a permutation of length 3 while both [0, 2, 2] and [1, 2, 3] are not.
A fixed point of a function is a point that is mapped to itself by the function. A permutation c... | ```python
#347B
n = int(input())
inpt = list(map(int, input().split(" ")))
count = 0
b = 0
for i in range(n):
if inpt[i] == i:
count += 1
if b == 0 and inpt[i] != i and inpt[inpt[i]] == i:
count += 2
b = 1
if b == 0:
count += 1
print(min(n, count))
``` |
370_C. Mittens | A Christmas party in city S. had n children. All children came in mittens. The mittens can be of different colors, but each child had the left and the right mitten of the same color. Let's say that the colors of the mittens are numbered with integers from 1 to m, and the children are numbered from 1 to n. Then the i-th... | ```python
from collections import Counter
def main():
n, m = map(int, input().split())
c = list(map(int, input().split()))
sc = sorted(range(n), key=lambda x: c[x])
mc = Counter(c).most_common(1)[0][1]
print(n if mc <= n - mc else 2*(n - mc))
for i in range(n):
print(c[sc[i]], ... |
415_A. Mashmokh and Lights | Mashmokh works in a factory. At the end of each day he must turn off all of the lights.
The lights on the factory are indexed from 1 to n. There are n buttons in Mashmokh's room indexed from 1 to n as well. If Mashmokh pushes button with index i, then each light with index not less than i that is still turned on turn... | ```python
n = input().split()
n = int(n[0])
butt = {}
for i in range(1, n+1):
butt[i] = 0
a = input().split()
for i in a:
for k in range(int(i), n+1):
if butt[k] == 0:
butt[k] = int(i)
else: continue
for i in range(1, n+1):
print(butt[i], end=' ')
``` |
510_C. Fox And Names | Fox Ciel is going to publish a paper on FOCS (Foxes Operated Computer Systems, pronounce: "Fox"). She heard a rumor: the authors list on the paper is always sorted in the lexicographical order.
After checking some examples, she found out that sometimes it wasn't true. On some papers authors' names weren't sorted in l... | ```python
from collections import defaultdict
n = int(input())
g = defaultdict(list)
names = []
for _ in range(n):
names.append(input())
for i in range(1, n):
j = 0
while j < len(names[i]) and j < len(names[i-1]) and names[i-1][j] == names[i][j]:
j += 1
if j >= len(names[i]):
p... |
535_D. Tavas and Malekas | Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead.
<image>
Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions... | ```python
from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
import string
characters = string.ascii_uppercase
from random import choice
# digits = string.digits
# setrecursionlimit(int(1e6))
# dir = [-1,0,1,0,-1]
# moves = 'NESW'
inf = float('inf')
from functools import cmp_to_key
from collections... |
586_B. Laurenty and Shop | A little boy Laurenty has been playing his favourite game Nota for quite a while and is now very hungry. The boy wants to make sausage and cheese sandwiches, but first, he needs to buy a sausage and some cheese.
The town where Laurenty lives in is not large. The houses in it are located in two rows, n houses in each r... | ```python
n = int(input())
a1 = [int(s) for s in input().split()]
a2 = [int(s) for s in input().split()]
b = [int(s) for s in input().split()]
sum = 0
for i in range(n-1):
sum = sum + a2[i]
sum1 = min(sum + b[0], sum - a2[0] + a1[0] + b[1])
sum2 = max(sum + b[0], sum - a2[0] + a1[0] + b[1])
sum = sum - a2[0] + a... |
608_C. Chain Reaction | There are n beacons located at distinct positions on a number line. The i-th beacon has position ai and power level bi. When the i-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance bi inclusive. The beacon itself is not destroyed however. Saitama will acti... | ```python
import sys
def inp():
return sys.stdin.readline().strip()
n=int(input())
x=dict()
mm=-1
for i in range(n):
a,b=map(int,input().split())
x[a]=b
mm=max(a,mm)
if 0 in x:
otv=[1]
else:
otv=[0]
ma=-1
for i in range(1,mm+2):
if i not in x:
otv.append(otv[i-1])
ma=max... |
62_B. Tyndex.Brome | Tyndex is again well ahead of the rivals! The reaction to the release of Zoozle Chrome browser was the release of a new browser Tyndex.Brome!
The popularity of the new browser is growing daily. And the secret is not even the Tyndex.Bar installed (the Tyndex.Bar automatically fills the glass with the finest 1664 cognac... | ```python
from bisect import bisect_left
n,k=map(int,input().split())
q="abcdefghijklmnopqrstuvwxyz"
a={i:[] for i in q}
for key,value in enumerate(input()):a[value].append(key)
#print(a)
def g(t):return [(t[i]+t[i-1])//2 for i in range(1,len(t))] #类似于二分查找的思路 //便于快速确定位置
c={i:g(a[i]) for i in q}
#print(c)
for _ in ... |
656_A. Da Vinci Powers |
Input
The input contains a single integer a (0 ≤ a ≤ 35).
Output
Output a single integer.
Examples
Input
3
Output
8
Input
10
Output
1024 | ```python
a=int(input())
b=str(bin(a))
b=b[2:]
c="0"*(6-len(b))+b
d=""
d+=c[0]
d+=c[5]
d+=c[3]
d+=c[2]
d+=c[4]
d+=c[1]
ret=0;
for i in range(5,-1,-1):
ret+=int(d[i])*(2**(5-i))
print(ret)
``` |
67_A. Partial Teacher | A teacher decides to give toffees to his students. He asks n students to stand in a queue. Since the teacher is very partial, he follows the following rule to distribute toffees.
He looks at the first two students and gives more toffees to the student having higher marks than the other one. If they have the same marks... | ```python
from collections import deque
n = int(input())
s = input()
ans = [1]*n
for i in range(1,n):
if s[i-1]=='R':
ans[i]=ans[i-1]+1
elif s[i-1]=='=':
ans[i]=ans[i-1]
for i in range(n-2, -1, -1):
if s[i]=='L':
ans[i]=max(ans[i+1]+1, ans[i])
elif s[i]=='=':
ans[i]... |
702_A. Maximum Increase | You are given array consisting of n integers. Your task is to find the maximum length of an increasing subarray of the given array.
A subarray is the sequence of consecutive elements of the array. Subarray is called increasing if each element of this subarray strictly greater than previous.
Input
The first line cont... | ```python
"""
Author: Sagar Pandey
"""
# ---------------------------------------------------Import Libraries---------------------------------------------------
import sys
import os
from math import sqrt, log, log2, log10, gcd, floor, pow, sin, cos, tan, pi, inf, factorial
from copy import copy, deepcopy
from sys i... |
724_B. Batch Sort | You are given a table consisting of n rows and m columns.
Numbers in each row form a permutation of integers from 1 to m.
You are allowed to pick two elements in one row and swap them, but no more than once for each row. Also, no more than once you are allowed to pick two columns and swap them. Thus, you are allowed ... | ```python
def check(table):
n = len(table)
m = len(table[0])
bits = [[table[i][j] == j+1 for j in range(m)] for i in range(n)]
for row in bits:
if row.count(False) > 2:
return False
return True
n,m =map(int, input().split())
table = [list(map(int, input().split())) for i in rang... |
746_B. Decoding | Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, inf... | ```python
n=int(input())
s=input()
print(s[-2::-2]+s[-1::-2][::-1])
``` |
769_B. News About Credit | Polycarp studies at the university in the group which consists of n students (including himself). All they are registrated in the social net "TheContacnt!".
Not all students are equally sociable. About each student you know the value ai — the maximum number of messages which the i-th student is agree to send per day. ... | ```python
import collections as col
import itertools as its
import operator
class Solver:
def solve(self):
n = int(input())
a = list(map(int, input().split()))
for i in range(len(a)):
a[i] = [a[i], i + 1]
a[0][0] += 1000
a = sorted(a)[::-1]
a[0][0] -= 10... |
793_B. Igor and his way to work | Woken up by the alarm clock Igor the financial analyst hurried up to the work. He ate his breakfast and sat in his car. Sadly, when he opened his GPS navigator, he found that some of the roads in Bankopolis, the city where he lives, are closed due to road works. Moreover, Igor has some problems with the steering wheel,... | ```python
import sys
def solve():
def run(r, c, visited):
visited[r][c] = True
for i in range(c + 1, m + 2):
if visited[r][i] or (not ok[r][i]):
break
visited[r][i] = True
for i in range(c - 1, -1, -1):
if visited[r][i] or (not ok[r][i]):... |
839_D. Winter is here | Winter is here at the North and the White Walkers are close. John Snow has an army consisting of n soldiers. While the rest of the world is fighting for the Iron Throne, he is going to get ready for the attack of the White Walkers.
He has created a method to know how strong his army is. Let the i-th soldier’s strength... | ```python
n=int(input())
num=[0 for i in range(1000000+1)]
mx=0
for i in input().split(' '):
i=int(i)
mx=max(mx,i)
num[i]+=1
f=[0 for i in range(mx+1)]
p=[0 for i in range(mx+1)]
mod=1e9+7
p[0]=1
for i in range(1,mx+1):
p[i]=2*p[i-1]%mod
ans=0
for i in range(mx,1,-1):
m=sum(num[i::i])
if m:
f[i]=(m*p[m-1]%mod-s... |
859_G. Circle of Numbers | n evenly spaced points have been marked around the edge of a circle. There is a number written at each point. You choose a positive real number k. Then you may repeatedly select a set of 2 or more points which are evenly spaced, and either increase all numbers at points in the set by k or decrease all numbers at points... | ```python
#Circle of Numbers
import math
def centre(n, pts):
x, y = 0, 0
for j in [7,11,13,17,19,23,29,31,37,1193,1663,2711,4007,65537]:
if math.gcd(n,j) == 1:
for i in range(n):
k = int(pts[i])
x += k*math.cos(math.pi * 2*i*j/n)
y += k*math.s... |
884_F. Anti-Palindromize | A string a of length m is called antipalindromic iff m is even, and for each i (1 ≤ i ≤ m) ai ≠ am - i + 1.
Ivan has a string s consisting of n lowercase Latin letters; n is even. He wants to form some string t that will be an antipalindromic permutation of s. Also Ivan has denoted the beauty of index i as bi, and the... | ```python
#https://pymotw.com/2/collections/counter.html
#same code as mmaxio
from collections import Counter
r = lambda: map(int, input().split())
def main():
n, = r()
s = input()
cost = list(r())
ans = 0
cnt = Counter()
for i in range(n // 2):
if s[i] == s[n - 1 - i]:
ans += min(cost[i], cost[n - 1 - ... |
930_B. Game with String | Vasya and Kolya play a game with a string, using the following rules. Initially, Kolya creates a string s, consisting of small English letters, and uniformly at random chooses an integer k from a segment [0, len(s) - 1]. He tells Vasya this string s, and then shifts it k letters to the left, i. e. creates a new string ... | ```python
s=input()
d=dict()
mod=[]
mx=[]
for k in s:
d[k]=[]
for i in range(len(s)):
d[s[i]].append(i)
index=0
for k in d.keys():
mod.append(d[k])
for k in mod:
mxct=0
ct=0
x=[]
for i in range(len(s)):
ct=0
dic=dict()
for j in k:
elt = s[(j+i)%(len(s))]
if elt in dic.keys():
dic[elt]+=1
el... |
984_B. Minesweeper | One day Alex decided to remember childhood when computers were not too powerful and lots of people played only default games. Alex enjoyed playing Minesweeper that time. He imagined that he saved world from bombs planted by terrorists, but he rarely won.
Alex has grown up since then, so he easily wins the most difficu... | ```python
arr = []
def valid(i, j):
bombs = 0
if arr[i][j] == '*':
return True
if i != len(arr) - 1:
if arr[i + 1][j] == '*':
bombs += 1
if i != 0:
if arr[i - 1][j] == '*':
bombs += 1
if j != len(arr[0]) - 1:
if arr[i][j + 1] == '*':
... |
p02570 AtCoder Beginner Contest 177 - Don't be late | Takahashi is meeting up with Aoki.
They have planned to meet at a place that is D meters away from Takahashi's house in T minutes from now.
Takahashi will leave his house now and go straight to the place at a speed of S meters per minute.
Will he arrive in time?
Constraints
* 1 \leq D \leq 10000
* 1 \leq T \leq 10... | ```python
d, t, s = map(int, input().split())
print("Yes" if d/s <= t else "No")
``` |
p02701 AtCoder Beginner Contest 164 - gacha | You drew lottery N times. In the i-th draw, you got an item of the kind represented by a string S_i.
How many kinds of items did you get?
Constraints
* 1 \leq N \leq 2\times 10^5
* S_i consists of lowercase English letters and has a length between 1 and 10 (inclusive).
Input
Input is given from Standard Input in t... | ```python
N=int(input())
J=[input() for i in range(N)]
print(len(list(set(J))))
``` |
p02830 AtCoder Beginner Contest 148 - Strings with the Same Length | Given are strings s and t of length N each, both consisting of lowercase English letters.
Let us form a new string by alternating the characters of S and the characters of T, as follows: the first character of S, the first character of T, the second character of S, the second character of T, ..., the N-th character of... | ```python
N = int(input())
S,T = input().split()
for n in range(N):
print(S[n]+T[n],end='')
``` |
p03102 AtCoder Beginner Contest 121 - Can you solve this? | There are N pieces of source code. The characteristics of the i-th code is represented by M integers A_{i1}, A_{i2}, ..., A_{iM}.
Additionally, you are given integers B_1, B_2, ..., B_M and C.
The i-th code correctly solves this problem if and only if A_{i1} B_1 + A_{i2} B_2 + ... + A_{iM} B_M + C > 0.
Among the N c... | ```python
N,M,C = map(int, input().split())
B = list(map(int, input().split()))
A = [list(map(int, input().split())) for _ in range(N)]
print(sum([(sum([a*b for a,b in zip(B,i)]) + C) > 0 for i in A]))
``` |
p03250 AtCoder Beginner Contest 110 - Maximize the Formula | You have decided to give an allowance to your child depending on the outcome of the game that he will play now.
The game is played as follows:
* There are three "integer panels", each with a digit between 1 and 9 (inclusive) printed on it, and one "operator panel" with a `+` printed on it.
* The player should constru... | ```python
A,B,C = sorted(input().split())[::-1]
print(int(A+B)+int(C))
``` |
p03403 AtCoder Regular Contest 093 - Traveling Plan | There are N sightseeing spots on the x-axis, numbered 1, 2, ..., N. Spot i is at the point with coordinate A_i. It costs |a - b| yen (the currency of Japan) to travel from a point with coordinate a to another point with coordinate b along the axis.
You planned a trip along the axis. In this plan, you first depart from... | ```python
n = int(input())
a = [0]+list(map(int,input().split()))+[0]
s = 0
for i in range(n+1):
s += abs(a[i+1]-a[i])
for i in range(n):
ans = s+ abs(a[i+2]-a[i])-(abs(a[i]-a[i+1])+abs(a[i+1] - a[i+2]))
print(ans)
``` |
p03566 AtCoder Beginner Contest 076 - AtCoder Express | In the year 2168, AtCoder Inc., which is much larger than now, is starting a limited express train service called AtCoder Express.
In the plan developed by the president Takahashi, the trains will run as follows:
* A train will run for (t_1 + t_2 + t_3 + ... + t_N) seconds.
* In the first t_1 seconds, a train must ru... | ```python
n = int(input())
t = list(map(int, input().split()))
v = list(map(int, input().split()))
tmp = 0
e_t = []
for i in t:
tmp+=i
e_t.append(tmp)
def calc_end_speed(s):
end_time = e_t[s]
ma = 10**10
for i in range(s+1, n):
ma = min(e_t[i-1] - end_time + v[i], ma)
return min(e_t[-1]... |
p03721 AtCoder Beginner Contest 061 - Big Array | There is an empty array. The following N operations will be performed to insert integers into the array. In the i-th operation (1≤i≤N), b_i copies of an integer a_i are inserted into the array. Find the K-th smallest integer in the array after the N operations. For example, the 4-th smallest integer in the array \\{1,2... | ```python
N, K = map(int, input().split())
arr = [list(map(int, input().split())) for i in range(N)]
arr.sort()
n = 0
for i in range(N):
n += arr[i][1]
if n >= K:
print(arr[i][0])
break
``` |
p00123 Speed Skating Badge Test | In the speed skating badge test, grades are awarded when the time specified for two distances is exceeded. For example, to reach Class A, 500 M requires less than 40.0 seconds and 1000 M requires less than 1 minute and 23 seconds.
Create a program that takes the time recorded in the speed skating competitions (500 M a... | ```python
import bisect
while 1:
try:
n,m=map(float,input().split())
m500=[35.5,37.5,40,43,50,55,70]
m1000=[71,77,83,89,105,116,148]
r1=bisect.bisect_left(m500,n+0.001)
r2=bisect.bisect_left(m1000,m+0.001)
rank=["AAA","AA","A","B","C","D","E","NA"]
print(rank[... |
p00256 Mayan Crucial Prediction | Shinya watched a program on TV called "Maya's Great Prophecy! Will the World End in 2012?" After all, I wasn't sure if the world would end, but I was interested in Maya's "long-term calendar," which was introduced in the program. The program explained as follows.
The Maya long-term calendar is a very long calendar con... | ```python
import datetime
time_std=datetime.date(2012, 12, 21)
while 1:
n=input()
if n=="#":break
n_len=list(map(int,n.split(".")))
if len(n_len)==3:
year_keep=0
while n_len[0]>9999:
year_keep+=1
n_len[0]-=400
ans=[0]*5
cal_date=datetime.date(n_len... |
p00443 Lightest Mobile | problem
Mobiles are widely known as moving works of art. The IOI Japan Committee has decided to create mobiles to publicize JOI. JOI public relations mobiles are sticks, strings, and weights. It is constructed as follows using the three types of elements of.
* One end of the bar is painted blue and the other end is p... | ```python
# AOJ 0520: Lightest Mobile
# Python3 2018.6.30 bal4u
def lcm(a, b):
return a // gcd(a, b) * b
def gcd(a, b):
while b != 0:
r = a % b
a, b = b, r
return a
def calc(i):
wr = calc(t[i][2]) if t[i][2] > 0 else 1
wb = calc(t[i][3]) if t[i][3] > 0 else 1
w = lcm(t[i][0] * wr, t[i][1] * wb)
return w//... |
p00633 Crop Circle | A crop circle suddenly appeared on the vast agricultural land of Argentina. A total of n crop circles were confirmed, including overlapping, popping, large, and small ones.
When a mystery hunter tried to capture the whole picture of a crop circle from the air, he found it difficult to show the beautiful pattern in the... | ```python
def string_to_float(s):
return list(map(float, s.split()))
def solve():
from sys import stdin
lines = stdin.readlines()
from itertools import combinations
from math import acos, pi
from cmath import phase
from bisect import insort
while True:
n = int(lines[0])
... |
p00777 Bridge Removal | Bridge Removal
ICPC islands once had been a popular tourist destination. For nature preservation, however, the government decided to prohibit entrance to the islands, and to remove all the man-made structures there. The hardest part of the project is to remove all the bridges connecting the islands.
There are n islan... | ```python
from sys import setrecursionlimit
setrecursionlimit(10 ** 8)
while True:
n = int(input())
if n == 0:
break
P = [int(i) for i in input().split()]
D = [int(i) for i in input().split()]
E = [list() for i in range(n + 1)]
for i, (p, c) in enumerate(zip(P, D), 2):
E[i].ap... |
p00908 Sliding Block Puzzle | In sliding block puzzles, we repeatedly slide pieces (blocks) to open spaces within a frame to establish a goal placement of pieces.
A puzzle creator has designed a new puzzle by combining the ideas of sliding block puzzles and mazes. The puzzle is played in a rectangular frame segmented into unit squares. Some square... | ```python
from collections import deque
from heapq import heappush, heappop, heapify
import sys
readline = sys.stdin.readline
write = sys.stdout.write
dd = ((-1, 0), (0, -1), (1, 0), (0, 1))
Z = [-1]*(50*50)
def calc(H, W, G, x0, y0, bx, by, S):
S[:] = Z[:H*W]
k = y0*W + x0
que = deque([k])
S[k] = 0
... |
p01793 Content Delivery | Example
Input
3 2
1 2 1
2 3 2
1 10 100
Output
320 | ```python
import sys
readline = sys.stdin.readline
write = sys.stdout.write
sys.setrecursionlimit(10**5)
def solve():
N, M = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(N-1):
a, b, c = map(int, readline().split())
G[a-1].append((b-1, c))
G[b-1].append((a-1,... |
p01927 Industrial Convex Pillar City | Convex polygon pillar industrial city
The Industrial Convex Pillar City (ICPC) is a city of buildings in the shape of several convex polygonal columns. You are about to walk through this city from your current location S to your destination T. The sun is strong today, so I want to go to my destination without passing ... | ```python
from math import sin, cos, tan, radians
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def dot3(O, A, B):
ox, oy = O; ax, ay = A; bx, by = B
return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy)
def cross3(O, A, B):
ox, oy = O; ax, ay = A; bx,... |
p02065 Grid Number | F: Grid number
problem
Ebi-chan is trying to write exactly one integer from 1 to 2 \ times n in a grid with n columns horizontally and 2 rows vertically.
Only one integer can be written to each cell in the grid.
It's not fun just to write normally, so I set the following rules.
* The absolute value of the differen... | ```python
from collections import Counter
N, K, mod = map(int, input().split())
dp = [Counter() for _ in range(2*N)]
dp[0][(None, (0,))] = 1
for i in range(2*N-1):
for (left, top), v in dp[i].items():
if len(top) > K+1:
continue
if left == None:
if top and i+1 - top[0] <= K:... |
p02207 Earthquakes | Earthquakes
E869120 You are not good at earthquakes.
Specifically, if an earthquake with a seismic intensity of $ p $ occurs while you are doing a task, the performance of that task will be reduced by $ 10 \ times p $ percent.
Yesterday, there were $ N $ earthquakes. More specifically, yesterday's i-th earthquake oc... | ```python
from math import log10
from bisect import bisect_left
n=int(input())
l=[[0,0]]+[list(map(int,input().split()))for _ in range(n)]
for i in range(1,n+1):
l[i][1]=log10(1-l[i][1]/10)
for i in range(n):
l[i+1][1]+=l[i][1]
q=int(input())
for _ in range(q):
a,b=map(int,input().split())
i=bisect_left(l,[a,0]... |
p02361 Single Source Shortest Path | For a given weighted graph G(V, E) and a source r, find the source shortest path to each vertex from the source (SSSP: Single Source Shortest Path).
Constraints
* 1 ≤ |V| ≤ 100000
* 0 ≤ di ≤ 10000
* 0 ≤ |E| ≤ 500000
* There are no parallel edges
* There are no self-loops
Input
An edge-weighted graph G (V, E) and th... | ```python
from heapq import heappush, heappop
INF = 10**10
a,b,c = map(int,input().split())
d = [[] for i in range(a)]
for i in range(b):
ta,tb,tc = map(int,input().split())
d[ta].append((tb,tc))
def dijkstra(N, G, s):
dist = [INF] * N
que = [(0, s)]
dist[s] = 0
while que:
c, v = heappo... |
1009_C. Annoying Present | Alice got an array of length n as a birthday present once again! This is the third year in a row!
And what is more disappointing, it is overwhelmengly boring, filled entirely with zeros. Bob decided to apply some changes to the array to cheer up Alice.
Bob has chosen m changes of the following form. For some integer... | ```python
n,m = list(map(int, input().split()))
avg = 0
def s(p):
return p*(p+1)//2
for i in range(m):
x,d = list(map(int, input().split()))
avg += (n*x + max( d*s(n-1), d*(s(n//2)+s((n-1)//2))))
#print(avg)
print("%.15f" % (avg/n))
``` |
1076_F. Summer Practice Report | Vova has taken his summer practice this year and now he should write a report on how it went.
Vova has already drawn all the tables and wrote down all the formulas. Moreover, he has already decided that the report will consist of exactly n pages and the i-th page will include x_i tables and y_i formulas. The pages are... | ```python
def max(a, b):
if a > b:
return a
else:
return b
n, k = map(int, input().split())
x = [int(t) for t in input().split()]
y = [int(t) for t in input().split()]
f, s = 0, 0
for i in range(n):
f = max(0, x[i] + f - k * y[i])
s = max(0, y[i] + s - k * x[i])
if f > k or s > k:
print('NO')
... |
1118_F1. Tree Cutting (Easy Version) | You are given an undirected tree of n vertices.
Some vertices are colored blue, some are colored red and some are uncolored. It is guaranteed that the tree contains at least one red vertex and at least one blue vertex.
You choose an edge and remove it from the tree. Tree falls apart into two connected components. Le... | ```python
import sys
input=sys.stdin.readline
n = int(input())
a = [int(t) for t in input().split(' ')]
mx = [[] for _ in range(n)]
for i in range(n-1):
v1, v2 = map(int,input().split())
mx[v1-1].append(v2-1)
mx[v2-1].append(v1-1)
count = [[0, 0] for _ in range(n)]
total = [a.count(1), a.count(2)]
answer = ... |
1145_C. Mystery Circuit | <image>
Input
The input contains a single integer a (0 ≤ a ≤ 15).
Output
Output a single integer.
Example
Input
3
Output
13 | ```python
print((15, 14, 12, 13, 8, 9, 10, 11, 0, 1, 2, 3, 4, 5, 6, 7)[int(input())])
``` |
1166_B. All the Vowels Please | Tom loves vowels, and he likes long words with many vowels. His favorite words are vowelly words. We say a word of length k is vowelly if there are positive integers n and m such that n⋅ m = k and when the word is written by using n rows and m columns (the first row is filled first, then the second and so on, with each... | ```python
N = int(input())
def make_vowels(N):
ans = ["aeiou", "eioua", "iouae", "ouaei", "uaeio"]
vowels = "aeiou"
m = 5
while m < N:
if N % m == 0 and N // m >= 5:
break
m += 1
else:
return print(-1)
n = N // m
for i in range(n):
if i <= 4:
... |
1203_D2. Remove the Substring (hard version) | The only difference between easy and hard versions is the length of the string.
You are given a string s and a string t, both consisting only of lowercase Latin letters. It is guaranteed that t can be obtained from s by removing some (possibly, zero) number of characters (not necessary contiguous) from s without chang... | ```python
def main():
string = input()
substring = input()
size = len(substring)
string_size = len(string)
first = []
last = []
first.append(-1)
index = 0
for i in range(string_size):
c = string[i]
if c==substring[index]:
first.append(i)
... |
1220_B. Multiplication Table | Sasha grew up and went to first grade. To celebrate this event her mother bought her a multiplication table M with n rows and n columns such that M_{ij}=a_i ⋅ a_j where a_1, ..., a_n is some sequence of positive integers.
Of course, the girl decided to take it to school with her. But while she was having lunch, hoolig... | ```python
n=int(input())
arr=[]
for _ in range(n):
arr.append([int(x) for x in input().split()])
ans=[0 for i in range(n)]
ans[1]=int(((arr[0][1]*arr[1][2])//arr[0][2])**0.5)
for i in range(n):
if i==1:
continue
ans[i]=arr[1][i]//ans[1]
for i in ans:
print(i,end=' ')
``` |
1245_D. Shichikuji and Power Grid | Shichikuji is the new resident deity of the South Black Snail Temple. Her first job is as follows:
There are n new cities located in Prefecture X. Cities are numbered from 1 to n. City i is located x_i km North of the shrine and y_i km East of the shrine. It is possible that (x_i, y_i) = (x_j, y_j) even when i ≠ j.
S... | ```python
import sys
#import heapq as hq
#from collections import deque
#sys.stdin = open('in', 'r')
readline = sys.stdin.readline
rdw = lambda: readline().rstrip()
rdws = lambda: readline().split()
rdwl = lambda: list(readline().split())
rdi = lambda: int(readline())
rdis = lambda: map(int, readline().split())
rdil = ... |
1265_B. Beautiful Numbers | You are given a permutation p=[p_1, p_2, …, p_n] of integers from 1 to n. Let's call the number m (1 ≤ m ≤ n) beautiful, if there exists two indices l, r (1 ≤ l ≤ r ≤ n), such that the numbers [p_l, p_{l+1}, …, p_r] is a permutation of numbers 1, 2, …, m.
For example, let p = [4, 5, 1, 3, 2, 6]. In this case, the numb... | ```python
for _ in range (int(input())):
n=int(input())
a = [int(i) for i in input().split()]
ind = [0]*(n+1)
for i in range (n):
ind[a[i]]=i
m = 1
ma = ind[1]
mi = ind[1]
ans = "1"
for i in range (n-1):
m+=1
ma = max(ind[m],ma)
mi = min(ind[m],mi)
... |
1305_F. Kuroni and the Punishment | Kuroni is very angry at the other setters for using him as a theme! As a punishment, he forced them to solve the following problem:
You have an array a consisting of n positive integers. An operation consists of choosing an element and either adding 1 to it or subtracting 1 from it, such that the element remains posit... | ```python
import sys
input = sys.stdin.readline
from math import sqrt
n=int(input())
A=list(map(int,input().split()))
SA=sorted(set(A))
MOD={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, ... |
132_C. Logo Turtle | A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward").
You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the lis... | ```python
s = input()
n = int(input())
t = [j for j, q in enumerate(s) if q == 'T']
l, r = [0] * 101, [0] * 101
for i, (a, b) in enumerate(zip([-1] + t, t + [len(s)])):
v = b - a
u = v - 1
if i:
l[i] = l[i - 1] + v
else:
u, v = -u, -v
r[i + 1] = l[i] - 1
for k in range(i - 1... |
134_A. Average Numbers | You are given a sequence of positive integers a1, a2, ..., an. Find all such indices i, that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).
Input
The first line contains the integer n (2 ≤ n ≤ 2·105). The second line contains elements of the sequence a1, ... | ```python
m = int(input())
num = [int(n) for n in input().split()]
sum = 0
for i in range(0,m):
sum += num[i]
if sum % m:
print('0')
else:
ave = sum // m
cnt = 0
for i in range(0,m):
if num[i] == ave:
cnt += 1
print(cnt)
for i in range(0,m):
if num[i] == ave:
... |
1370_A. Maximum GCD | Let's consider all integers in the range from 1 to n (inclusive).
Among all pairs of distinct integers in this range, find the maximum possible greatest common divisor of integers in pair. Formally, find the maximum value of gcd(a, b), where 1 ≤ a < b ≤ n.
The greatest common divisor, gcd(a, b), of two positive integ... | ```python
n = int(input())
for i in range(n):
print(int(input())//2)
``` |
1392_F. Omkar and Landslide | Omkar is standing at the foot of Celeste mountain. The summit is n meters away from him, and he can see all of the mountains up to the summit, so for all 1 ≤ j ≤ n he knows that the height of the mountain at the point j meters away from himself is h_j meters. It turns out that for all j satisfying 1 ≤ j ≤ n - 1, h_j < ... | ```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.bu... |
1417_B. Two Arrays | RedDreamer has an array a consisting of n non-negative integers, and an unlucky integer T.
Let's denote the misfortune of array b having length m as f(b) — the number of pairs of integers (i, j) such that 1 ≤ i < j ≤ m and b_i + b_j = T. RedDreamer has to paint each element of a into one of two colors, white and black... | ```python
for I in range(int(input())):
n,t = map(int,input().split())
a = list(map(int,input().split()))
d = []
if t % 2 != 0:
for i in range(n):
if a[i] <= t // 2:
d.append(1)
else:
d.append(0)
else:
p = 0
for i in ran... |
1433_G. Reducing Delivery Cost | You are a mayor of Berlyatov. There are n districts and m two-way roads between them. The i-th road connects districts x_i and y_i. The cost of travelling along this road is w_i. There is some path between each pair of districts, so the city is connected.
There are k delivery routes in Berlyatov. The i-th route is goi... | ```python
import sys
input = sys.stdin.readline
import heapq
def dijkstra(n, s, edges):
hq = [(0, s)]
cost = [float('inf')] * n
cost[s] = 0
while hq:
c, v = heapq.heappop(hq)
if c > cost[v]:
continue
for d, u in edges[v]:
tmp = d + cost[v]
if... |
1509_A. Average Height | Sayaka Saeki is a member of the student council, which has n other members (excluding Sayaka). The i-th member has a height of a_i millimeters.
It's the end of the school year and Sayaka wants to take a picture of all other members of the student council. Being the hard-working and perfectionist girl as she is, she wa... | ```python
t=int(input())
for i in range(t):
n=int(input())
arr=list(map(int,input().split()))
arr2=[]
for j in arr:
if(j%2!=0):
print(j, end=" ")
if(j%2==0):
arr2.append(j)
print(*arr2)
``` |
1535_A. Fair Playoff | Four players participate in the playoff tournament. The tournament is held according to the following scheme: the first player will play with the second, and the third player with the fourth, then the winners of the pairs will play in the finals of the tournament.
It is known that in a match between two players, the o... | ```python
'''
Online Python Compiler.
Code, Compile, Run and Debug python program online.
Write your code in this editor and press "Run" button to execute it.
'''
t=int(input())
for i in range(t):
l=list(map(int,input().split()))
m=l[:]
l.sort(reverse=True)
... |
205_C. Little Elephant and Interval | The Little Elephant very much loves sums on intervals.
This time he has a pair of integers l and r (l ≤ r). The Little Elephant has to find the number of such integers x (l ≤ x ≤ r), that the first digit of integer x equals the last one (in decimal notation). For example, such numbers as 101, 477474 or 9 will be inclu... | ```python
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
#from __future__ import print_function, division #while using python2
# from itertools import accumulate
# from collections import de... |
22_B. Bargaining Table | Bob wants to put a new bargaining table in his office. To do so he measured the office room thoroughly and drew its plan: Bob's office room is a rectangular room n × m meters. Each square meter of the room is either occupied by some furniture, or free. A bargaining table is rectangular, and should be placed so, that it... | ```python
n,m=map(int,input().split())
a=[]
for i in range(n):
a.append([])
for x in input():
if x=="0":
a[i].append(0)
else:
a[i].append(1)
ans=0
for x1 in range(0,m):
for x2 in range(x1,m):
for y1 in range(0,n):
for y2 in range(y1,n):
... |
255_A. Greg's Workout | Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was n integers a1, a2, ..., an. These numbers mean that Greg needs to do exactly n exercises today. Besides, Greg should repeat the i-th in order exercise ai times.
Greg now only does three types of exercises: "chest" exercises,... | ```python
n=int(input())
l=list(map(int,input().split()))
chest=back=biceps=0
for i in range(0,n,3):
chest+=l[i]
for i in range(1,n,3):
biceps+=l[i]
for i in range(2,n,3):
back+=l[i]
if chest>biceps and chest>back:
print("chest")
elif biceps>chest and biceps>back:
print("biceps")
else:
print("back")
``` |
279_A. Point on Spiral | Valera the horse lives on a plane. The Cartesian coordinate system is defined on this plane. Also an infinite spiral is painted on the plane. The spiral consists of segments: [(0, 0), (1, 0)], [(1, 0), (1, 1)], [(1, 1), ( - 1, 1)], [( - 1, 1), ( - 1, - 1)], [( - 1, - 1), (2, - 1)], [(2, - 1), (2, 2)] and so on. Thus, t... | ```python
# one ride costs a rubes
inputs = list(map(int, input().split()))
x = inputs[0]
y = inputs[1]
if y==0 and 0<=x<=1: print(0)
else:
a = max(abs(x), abs(y))
m = 1 + 4*(a-1)
if x==a and y==-(a-1):print(m-1)
if x==a and -(a-1)<y<=a: print(m)
elif y==a and -a<=x<a:print(m+1)
elif x==-a and ... |
327_C. Magic Five | There is a long plate s containing n digits. Iahub wants to delete some digits (possibly none, but he is not allowed to delete all the digits) to form his "magic number" on the plate, a number that is divisible by 5. Note that, the resulting number may contain leading zeros.
Now Iahub wants to count the number of ways... | ```python
mod = 1000000007
#gcd(a, m) = 1
def inv_mod(a, m):
a %= m
return pow(a, m-2, m)
a = input()
k = int(input())
t = len(a)
d = 0
for i, c in enumerate(a):
if not int(c) % 5:
d += pow(2, i, mod)
d %= mod
print(d*(pow(2, (k*t)%(mod-1), mod)-1)*inv_mod(pow(2, t, mod)-1, mod)%mod)
``` |
394_B. Very Beautiful Number | Teacher thinks that we make a lot of progress. Now we are even allowed to use decimal notation instead of counting sticks. After the test the teacher promised to show us a "very beautiful number". But the problem is, he's left his paper with the number in the teachers' office.
The teacher remembers that the "very beau... | ```python
p,k = input().split()
p = int (p)
k = int (k)
y = 10*k -1
x = ((10 ** (p-1)) - k) % y
b = True
for i in range(k,10):
if( (x*i % y) == 0):
#z = (x*i) // y
#print(z*10 + i)
z = i*10
while( (z-i)%y ):
z *= 10
part = str ((z-i)//y)
print(part * (p//len(part)))
b= False
break
i... |
417_C. Football | One day, at the "Russian Code Cup" event it was decided to play football as an out of competition event. All participants was divided into n teams and played several matches, two teams could not play against each other more than once.
The appointed Judge was the most experienced member — Pavel. But since he was the wi... | ```python
import sys,math
n,k=map(int,sys.stdin.readline().split())
if n<=2*k:
print(-1)
else:
ans=[]
for i in range(n):
for j in range(i+1,k+i+1):
if j+1==n:
ans.append([i+1,j+1])
else:
ans.append([i+1,((j+1)%n)])
print(len(ans))
... |
444_A. DZY Loves Physics | DZY loves Physics, and he enjoys calculating density.
Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows:
<image> where v is the sum of the values of the nodes, e is the sum of the values of the edges.
Once DZY got a ... | ```python
import sys
def input(): return sys.stdin.readline().strip()
n,m=map(int, input().split())
w=list(map(int, input().split()))
ans=0.0
for i in range(m):
u,v,c=map(int, input().split())
ans=max(ans, round( (w[u-1]+w[v-1])/c,9))
print(ans)
``` |
466_B. Wonder Room | The start of the new academic year brought about the problem of accommodation students into dormitories. One of such dormitories has a a × b square meter wonder room. The caretaker wants to accommodate exactly n students there. But the law says that there must be at least 6 square meters per student in a room (that is,... | ```python
n,a,b = map(int, input().split(' '))
A = 6*n
if a*b >= 6*n :
print(a*b)
print(a,b)
else :
R = []
temp = float("INF")
for i in range(1, int(A**0.5)+2) :
j = A//i
if i*j < A : j+=1
x = max([a,b,i,j])
y = max(min(a,b) , min(i,j))
if temp > x*y :
... |
489_F. Special Matrices | An n × n square matrix is special, if:
* it is binary, that is, each cell contains either a 0, or a 1;
* the number of ones in each row and column equals 2.
You are given n and the first m rows of the matrix. Print the number of special n × n matrices, such that the first m rows coincide with the given ones.
... | ```python
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
dp = [[-1 for i in range(505)] for j in range(505)]
def memo(row,z,o):
if(row == n):
if(z == 0 and o == 0):
return 1
else:
return 0
if(dp[z][o] != -1): return dp[z][o]
if(z > 1):
dp[z][o] += (z*(z-1)//2)*(mem... |
538_F. A Heap of Heaps | Andrew skipped lessons on the subject 'Algorithms and Data Structures' for the entire term. When he came to the final test, the teacher decided to give him a difficult task as a punishment.
The teacher gave Andrew an array of n numbers a1, ..., an. After that he asked Andrew for each k from 1 to n - 1 to build a k-ary... | ```python
import sys
def myargsort(a):
b = list(zip(a, range(0, len(a))))
b.sort()
r = [pr[1] for pr in b]
return r
fin = sys.stdin
n = int(fin.readline())
a = [int(number) for number in fin.readline().split()]
p = myargsort(a)
p.reverse()
j = 0
aib = [0] * (n + 1)
def ultb(x):
return -(x ^ (-x))... |
588_B. Duff in Love | Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x.
<image>
Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g... | ```python
import math
#n,k = map(int, input().strip().split(' '))
n=int(input())
#lst = list(map(int, input().strip().split(' ')))
if n==1 or n==2 or n==3:
print(n)
else:
p=math.sqrt(n)
l=[1,n]
c=1
for j in range(2,int(p)+1):
if n%j==0:
l.insert(c,j)
if n//j!=j:
... |
630_I. Parking Lot | To quickly hire highly skilled specialists one of the new IT City companies made an unprecedented move. Every employee was granted a car, and an employee can choose one of four different car makes.
The parking lot before the office consists of one line of (2n - 2) parking spaces. Unfortunately the total number of cars... | ```python
n = int(input())
print(int(4 * (n - 3) * 3 * 3 * 4 ** (n - 4) + 4 * 2 * 3 * 4 ** (n - 3)))
``` |
659_A. Round House | Vasya lives in a round building, whose entrances are numbered sequentially by integers from 1 to n. Entrance n and entrance 1 are adjacent.
Today Vasya got bored and decided to take a walk in the yard. Vasya lives in entrance a and he decided that during his walk he will move around the house b entrances in the direct... | ```python
n, a, b = list(map(int, input().split()))
if b == 0:
print(a)
exit()
dx = b // abs(b)
for i in range(abs(b)):
a += dx
if a == 0:
a = n
elif a == n + 1:
a = 1
print(a)
``` |
681_C. Heap Operations | Petya has recently learned data structure named "Binary heap".
The heap he is now operating with allows the following operations:
* put the given number into the heap;
* get the value of the minimum element in the heap;
* extract the minimum element from the heap;
Thus, at any moment of time the heap con... | ```python
from sys import stdin, stdout
def siftup(ind):
while ind != 1 and heap[ind] < heap[ind // 2]:
heap[ind], heap[ind // 2] = heap[ind // 2], heap[ind]
ind //= 2
def siftdown(ind):
while len(heap) > ind * 2 + 1 and (heap[ind] > heap[ind * 2] or heap[ind] > heap[ind ... |
748_A. Santa Claus and a Place in a Class | Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numb... | ```python
n, m, k = map(int,input().split())
print((k-1)//(2*m)+1,(k-1)%(2*m)//2+1,'L' if k%2 else 'R')
``` |
770_D. Draw Brackets! | A sequence of square brackets is regular if by inserting symbols "+" and "1" into it, you can get a regular mathematical expression from it. For example, sequences "[[]][]", "[]" and "[[][[]]]" — are regular, at the same time "][", "[[]" and "[[]]][" — are irregular.
Draw the given sequence using a minimalistic pseud... | ```python
import sys
def vert(f, d, c, h):
f[d][c] = '+'
f[h-1-d][c] = '+'
for i in range(d+1,h-1-d):
f[i][c] = '|'
return f
n = int(input())
s = sys.stdin.readline().rstrip()
d = 0
maxd=1
for c in s:
if c == '[':
d+=1
if d>maxd:
maxd=d
else:
d-=1
... |
816_A. Karen and Morning | Karen is getting ready for a new school day!
<image>
It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome.
What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i... | ```python
h, m = map(int, input().split(':'))
for i in range(999):
if h == 10 * (m % 10) + m // 10:
print(i)
break
h, m = (h, m + 1) if m < 59 else ((h + 1) % 24, 0)
``` |
841_A. Generous Kefa | One day Kefa found n baloons. For convenience, we denote color of i-th baloon as si — lowercase letter of the Latin alphabet. Also Kefa has k friends. Friend will be upset, If he get two baloons of the same color. Kefa want to give out all baloons to his friends. Help Kefa to find out, can he give out all his baloons, ... | ```python
from collections import Counter
n , k = map(int , input().split())
s = input()
s = list(s)
cnt = Counter(s)
r = 0
for i in cnt:
if cnt[i] > k:
r = 1
break
print('YES' if r == 0 else 'NO')
``` |
862_B. Mahmoud and Ehab and the bipartiteness | Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (u, v) that belongs to the graph, u and ... | ```python
from collections import defaultdict
n = int(input())
degree = [0 for i in range(n+1)]
def BFS(d,x,visited):
visited[x] = 1
queue = [(x,1)]
l1 = set()
l2 = set()
while len(queue):
temp,j = queue.pop()
visited[temp] = 1
if j%2 == 1:
l1.add(temp)
else:
l2.add(temp)
for i in d[temp]:
... |
910_A. The Way to Home | A frog lives on the axis Ox and needs to reach home which is in the point n. She starts from the point 1. The frog can jump to the right at a distance not more than d. So, after she jumped from the point x she can reach the point x + a, where a is an integer from 1 to d.
For each point from 1 to n is known if there is... | ```python
n , d =map(int, input().split())
s= str(input())
ans = -1
i=1
count = 0
while i<len(s):
temp = s[i:i+d]
if '1' in temp:
x = temp.rfind('1')
i = i+ x +1
count = count +1
else:
print(ans)
count=0
break
if count!=0:
print(count)
``` |
932_C. Permutation Cycle | For a permutation P[1... N] of integers from 1 to N, function f is defined as follows:
<image>
Let g(i) be the minimum positive integer j such that f(i, j) = i. We can show such j always exists.
For given N, A, B, find a permutation P of integers from 1 to N such that for 1 ≤ i ≤ N, g(i) equals either A or B.
Input... | ```python
#This code sucks, you know it and I know it.
#Move on and call me an idiot later.
def solve(a, b, n):
i = 0
while i * a <= n:
if (n - (i * a)) % b == 0:
x = i
y = (n - (i * a)) // b
return (x, y)
i = i + 1
return (-1, -1)
n,... |
959_D. Mahmoud and Ehab and another array construction task | Mahmoud has an array a consisting of n integers. He asked Ehab to find another array b of the same length such that:
* b is lexicographically greater than or equal to a.
* bi ≥ 2.
* b is pairwise coprime: for every 1 ≤ i < j ≤ n, bi and bj are coprime, i. e. GCD(bi, bj) = 1, where GCD(w, z) is the greatest com... | ```python
MAX_NUM = 2000000
prime_str = ('2 3 5 7 11 13 17 19 23 29 '
+ '31 37 41 43 47 53 59 61 67 71 '
+ '73 79 83 89 97 101 103 107 109 113 '
+ '127 131 137 139 149 1... |
986_B. Petr and Permutations | Petr likes to come up with problems about randomly generated data. This time problem is about random permutation. He decided to generate a random permutation this way: he takes identity permutation of numbers from 1 to n and then 3n times takes a random pair of different elements and swaps them. Alex envies Petr and tr... | ```python
import random
astr=input()
N=int(astr)
s=input()
sk=s.split(' ')
ml=[int(i) for i in sk]
kl=[0 for i in ml]
#for i in range(0, 7*N+2):
# A=random.randint(0,N-1)
# B=A
# while(A==B):
# B=random.randint(0,N-1)
# swap=ml[A]
# ml[A]=ml[B]
# ml[B]=swap
#print(ml)
k=0
for i in range(0,N):
... |
p02582 AtCoder Beginner Contest 175 - Rainy Season | We have weather records at AtCoder Town for some consecutive three days. A string of length 3, S, represents the records - if the i-th character is `S`, it means it was sunny on the i-th day; if that character is `R`, it means it was rainy on that day.
Find the maximum number of consecutive rainy days in this period.
... | ```python
s=input()
c=0
r=0
for i in s:
if i!='R':
c=0
else:
c+=1
r=max(r,c)
print(r)
``` |
p02713 AtCoder Beginner Contest 162 - Sum of gcd of Tuples (Easy) | Find \displaystyle{\sum_{a=1}^{K}\sum_{b=1}^{K}\sum_{c=1}^{K} \gcd(a,b,c)}.
Here \gcd(a,b,c) denotes the greatest common divisor of a, b, and c.
Constraints
* 1 \leq K \leq 200
* K is an integer.
Input
Input is given from Standard Input in the following format:
K
Output
Print the value of \displaystyle{\sum_{... | ```python
import math
K=int(input())
ans=0
for i in range(1,K+1):
for j in range(1,K+1):
for k in range(1,K+1):
ans+=math.gcd(math.gcd(i,j),k)
print(ans)
``` |
p02842 Sumitomo Mitsui Trust Bank Programming Contest 2019 - Tax Rate | Takahashi bought a piece of apple pie at ABC Confiserie. According to his memory, he paid N yen (the currency of Japan) for it.
The consumption tax rate for foods in this shop is 8 percent. That is, to buy an apple pie priced at X yen before tax, you have to pay X \times 1.08 yen (rounded down to the nearest integer).... | ```python
n = int(input())
m = 1
while int(m*1.08) < n:
m += 1
print(m) if int(m*1.08) == n else print(":(")
``` |
p02979 AtCoder Grand Contest 035 - Develop | There is a blackboard on which all integers from -10^{18} through 10^{18} are written, each of them appearing once. Takahashi will repeat the following sequence of operations any number of times he likes, possibly zero:
* Choose an integer between 1 and N (inclusive) that is written on the blackboard. Let x be the cho... | ```python
N, K, M = map(int, input().split())
# limitの最大値(limitなし)
L = (N+1)//2+1
def even(n, k) :
# dp[iまでみた][前のj個が連続]
dp = [[0] * (k+1) for _ in range(n+1)]
dp[0][0] = 1
for i in range(n) :
for j in range(k + 1) :
dp[i+1][0] = (dp[i+1][0] + dp[i][j]) % M
# 直前にK個連続していると... |
p03262 AtCoder Beginner Contest 109 - Skip | There are N cities on a number line. The i-th city is located at coordinate x_i.
Your objective is to visit all these cities at least once.
In order to do so, you will first set a positive integer D.
Then, you will depart from coordinate X and perform Move 1 and Move 2 below, as many times as you like:
* Move 1: tr... | ```python
import math
n,x=map(int,input().split());l=[abs(x-i) for i in list(map(int,input().split()))];r=0
for i in range(len(l)): r=math.gcd(r,l[i])
print(r)
``` |
p03420 AtCoder Regular Contest 091 - Remainder Reminder | Takahashi had a pair of two positive integers not exceeding N, (a,b), which he has forgotten. He remembers that the remainder of a divided by b was greater than or equal to K. Find the number of possible pairs that he may have had.
Constraints
* 1 \leq N \leq 10^5
* 0 \leq K \leq N-1
* All input values are integers.
... | ```python
n, k = map(int, input().split())
ans = 0
for i in range(1,n+1):
ans += (n//i)*max(0,i-k)+max(0,n%i-k+1)
if k==0:
ans -= n
print(ans)
``` |
p03578 CODE FESTIVAL 2017 qual B - Problem Set | Rng is preparing a problem set for a qualification round of CODEFESTIVAL.
He has N candidates of problems. The difficulty of the i-th candidate is D_i.
There must be M problems in the problem set, and the difficulty of the i-th problem must be T_i. Here, one candidate of a problem cannot be used as multiple problems.... | ```python
from collections import Counter
N = int(input())
D = [int(i) for i in input().split()]
M = int(input())
T = [int(i) for i in input().split()]
d = Counter(D)
t = Counter(T)
for k, v in t.items():
if d[k] < v:
print('NO')
break
else:
print('YES')
``` |
p03735 AtCoder Regular Contest 073 - Ball Coloring | There are N bags, each containing two white balls. The i-th box contains two balls with integers x_i and y_i written on them, respectively.
For each of these bags, you will paint one of the balls red, and paint the other blue.
Afterwards, the 2N balls will be classified according to color.
Then, we will define the f... | ```python
import sys
from operator import itemgetter
inf = 1 << 30
def solve():
n = int(sys.stdin.readline())
# r_max = MAX, b_min = MIN にしたとき
r_max = b_max = 0
r_min = b_min = inf
p = []
for i in range(n):
xi, yi = map(int, sys.stdin.readline().split())
if xi > yi:... |
p03897 CODE FESTIVAL 2016 Relay (Parallel) - Connected Checkerboard | We have an N×N checkerboard.
From the square at the upper left corner, a square that is i squares to the right and j squares below is denoted as (i, j). Particularly, the square at the upper left corner is denoted as (0, 0).
Each square (i, j) such that i+j is even, is colored black, and the other squares are colored... | ```python
n=int(input())
ans=[]
for i in range(n-1):
if i%2:
ans+=[(i,0)]
for i in range(n-1):
if i%6==1:
for j in range(2,n):
if j%2==0:
ans+=[(i,j)]
if i%6==4:
for j in range(n):
if j%2:
ans+=[(i,j)]
for j in range(n):
if(n-1+j)%2:
ans+=[(n-1,j)]
print(len(ans))
for... |
p00003 Is it a Right Triangle? | Write a program which judges wheather given length of three side form a right triangle. Print "YES" if the given sides (integers) form a right triangle, "NO" if not so.
Constraints
* 1 ≤ length of the side ≤ 1,000
* N ≤ 1,000
Input
Input consists of several data sets. In the first line, the number of data set, N is... | ```python
N = int(input())
for i in range(N):
num = sorted(map(int, input().split()))
if num[0] ** 2 + num[1] ** 2 == num[2] ** 2:
print("YES")
else:
print("NO")
``` |
p00135 Clock Short Hand and Long Hand | A mischievous notice has arrived from the primitive slow-life organization "Akaruda". Akaruda is famous for mischief such as throwing a pie at the face of a VIP, but recently it has become more radical, such as using gunpowder to sprinkle rat fireworks at the reception venue. The notice is the following text.
--- Per... | ```python
for _ in [0]*int(input()):
h,m=map(int,input().split(":"))
s=l=.0
l=m*6
s=30*(h+(m/60))
if l<s:l,s=s,l
if l-s>180:d=360-l+s
else:d=l-s
if d<30: print('alert')
elif d<90: print('warning')
else: print('safe')
``` |
p00268 Cats Going Straight II | There was a big old mansion in one place, and one cat settled in. As shown in the figure, the mansion has a convex polygonal shape when viewed from above, and is made up of several rooms surrounded by straight walls. One wall is supported by pillars at both ends. The mansion is so old that every wall has one hole that ... | ```python
from math import atan2
from collections import defaultdict, deque
def cross(a, b, c):
return (b[0]-a[0])*(c[1]-a[1]) - (b[1]-a[1])*(c[0]-a[0])
def convex_hull(ps):
qs = []
n = len(ps)
for p in ps:
while len(qs)>1 and cross(qs[-1], qs[-2], p) > 0:
qs.pop()
qs.append(... |
p00455 Time Card | problem
JOI Shoji manages the time spent at work by employees with a time card. When an employee arrives at the office, he / she uses a dedicated device to stamp the arrival time on the time card. When leaving the office after work, the time of leaving the office is stamped on the time card. The time is handled in a 2... | ```python
for i in range(3):
L =list(map(int,input().split()))
L0 = L[0] * 60 * 60 + L[1] * 60 + L[2]
L1 = L[3] * 60 * 60 + L[4] * 60 + L[5]
h = (L1 - L0) // (60 * 60)
m = ((L1 - L0) % (60 * 60)) // 60
s = ((L1 - L0) % (60 * 60)) % 60
print(h,m,s)
``` |
p00646 No Story | Since I got tired to write long problem statements, I decided to make this problem statement short. For given positive integer L, how many pairs of positive integers a, b (a ≤ b) such that LCM(a, b) = L are there? Here, LCM(a, b) stands for the least common multiple of a and b.
Constraints
* 1 ≤ L ≤ 1012
Input
For ... | ```python
# AOJ 1060: No Story
# Python3 2018.6.8 bal4u
MAX = 1000004
ptbl = [ 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223,... |
p00790 Die Game | Life is not easy. Sometimes it is beyond your control. Now, as contestants of ACM ICPC, you might be just tasting the bitter of life. But don't worry! Do not look only on the dark side of life, but look also on the bright side. Life may be an enjoyable game of chance, like throwing dice. Do or die! Then, at last, you m... | ```python
# AOJ 1210: Die Game
# Python3 2018.7.22 bal4u
dic = {'s':1, 'w':2, 'e':3, 'n':4}
rot = [[0,1,2,3,4,5,6],[0,2,6,3,4,1,5],[0,4,2,1,6,5,3],[0,3,2,6,1,5,4],[0,5,1,3,4,6,2]]
while True:
n = int(input())
if n == 0: break
dice = [i for i in range(7)]
for j in range(n):
a = input()[0]
... |
p01055 Bomb Removal | Problem
N ignited fuses and one bomb for each are placed on a vertical H x horizontal W grid. Each fuse and bomb is placed on a pathi consisting of Li cells, and the jth cell of pathi is (pxij, pyij). Each bomb is in the last square of pathi (pxiLi, pyiLi). The fire of the lead wire is in the square (pxi1, pyi1) in th... | ```python
from collections import deque
def main():
w, h, n = map(int, input().split())
sx, sy = map(int, input().split())
sx -= 1
sy -= 1
limits = []
paths = []
bombs = set()
for _ in range(n):
line = list(map(int, input().split()))
limit = line[0]
line = line[... |
p01324 Consistent Unit System | Kyo, 垓, {Reiyo}, 穣, Mizo, 澗, Tadashi, Ryo, Goku, Tsunekawasa, Amongi, Decillion, etc.
Minutes, 厘, hair, thread, 忽, fine, fine, fine, sha, dust, dust, 渺, vagueness, vagueness, patrolling, su 臾, sigh, bullet finger, moment, Rokutoku, emptiness, cleanliness, Ariya, Ama Luo, tranquility
Do you know what these are? These ... | ```python
while True:
n = int(input())
if n == 0:break
dic = {}
for _ in range(n):
_, name1, _, val, name2 = input().split()
val = int(val.split("^")[1])
if name1 not in dic:
dic[name1] = {}
if name2 not in dic:
dic[name2] = {}
dic[name1][name2] = val
dic[name2][name1] = -val... |
p01805 Alternate Escape | Alternate Escape
Alice House
Alice and Bob are playing board games. This board game is played using a board with squares in rows H and columns and one frame. In this game, the upper left square of the board is set as the 1st row and 1st column, and the rows are counted downward and the columns are counted to the righ... | ```python
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
H, W, R, C = map(int, readline().split()); R -= 1; C -= 1
if H == W == 0:
return False
G0 = [[] for i in range(H*W+1)]
G1 = [[] for i in range(H*W+1)]
g = H*W
for i in r... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.