name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p02667 NOMURA Programming Competition 2020 - Binary Programming | Takahashi has an empty string S and a variable x whose initial value is 0.
Also, we have a string T consisting of `0` and `1`.
Now, Takahashi will do the operation with the following two steps |T| times.
* Insert a `0` or a `1` at any position of S of his choice.
* Then, increment x by the sum of the digits in the o... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
T = read().rstrip().decode()
T
def f(n, r, l, z):
# 長さnの1が座標 r から l へと移動する。
# z回立ち止まることが許されている。
# 獲得スコアの最大値は?
if n % 2 == 0:
move = r - l + z
return (move + 1... |
p02796 Keyence Programming Contest 2020 - Robot Arms | In a factory, there are N robots placed on a number line. Robot i is placed at coordinate X_i and can extend its arms of length L_i in both directions, positive and negative.
We want to remove zero or more robots so that the movable ranges of arms of no two remaining robots intersect. Here, for each i (1 \leq i \leq N... | ```python
N=int(input())
xl=[]
for i in range(N):
x,l=map(int,input().split())
xl.append([x-l,x+l])
XL=sorted(xl,key=lambda x:x[1])
w=1
robot=XL[0]
for i in XL:
if robot[1] <= i[0]:
w+=1
robot=i
print(w)
``` |
p02932 Japanese Student Championship 2019 Qualification - Candy Retribution | Find the number of sequences of N non-negative integers A_1, A_2, ..., A_N that satisfy the following conditions:
* L \leq A_1 + A_2 + ... + A_N \leq R
* When the N elements are sorted in non-increasing order, the M-th and (M+1)-th elements are equal.
Since the answer can be enormous, print it modulo 10^9+7.
Const... | ```python
MOD = 10**9+7
kaijo_memo = []
def kaijo(n):
if(len(kaijo_memo) > n): return kaijo_memo[n]
if(len(kaijo_memo) == 0): kaijo_memo.append(1)
while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if(len(gyak... |
p03068 Tenka1 Programmer Beginner Contest 2019 - *e**** ********e* *e****e* ****e** | You are given a string S of length N consisting of lowercase English letters, and an integer K. Print the string obtained by replacing every character in S that differs from the K-th character of S, with `*`.
Constraints
* 1 \leq K \leq N\leq 10
* S is a string of length N consisting of lowercase English letters.
* N... | ```python
N=int(input())
S=input()
K=int(input())
print("".join(s if s==S[K-1] else "*" for s in S))
``` |
p03211 AtCoder Beginner Contest 114 - 754 | There is a string S consisting of digits `1`, `2`, ..., `9`. Lunlun, the Dachshund, will take out three consecutive digits from S, treat them as a single integer X and bring it to her master. (She cannot rearrange the digits.)
The master's favorite number is 753. The closer to this number, the better. What is the mini... | ```python
s=input()
t=753
for i in range(len(s)-2):
t=min(t,abs(753-int(s[i:i+3])))
print(t)
``` |
p03360 AtCoder Beginner Contest 096 - Maximum Sum | There are three positive integers A, B and C written on a blackboard. E869120 performs the following operation K times:
* Choose one integer written on the blackboard and let the chosen integer be n. Replace the chosen integer with 2n.
What is the largest possible sum of the integers written on the blackboard after... | ```python
l = list(map(int, input().split()))
k = int(input())
print(max(l)*2**k + sum(l)-max(l))
``` |
p03683 AtCoder Regular Contest 076 - Reconciled? | Snuke has N dogs and M monkeys. He wants them to line up in a row.
As a Japanese saying goes, these dogs and monkeys are on bad terms. ("ken'en no naka", literally "the relationship of dogs and monkeys", means a relationship of mutual hatred.) Snuke is trying to reconsile them, by arranging the animals so that there a... | ```python
import sys
def main():
line = sys.stdin.readline()
lst = line.split(' ')
a = int(lst[0])
b = int(lst[1])
n = min(a,b)
m = max(a,b)
if (m == n+1):
#n! * m!
ans = 1
for i in range(1,n+1):
ans = (ans * i) % 1000000007
for i in range(1,m+1):
... |
p03836 AtCoder Beginner Contest 051 - Back and Forth | Dolphin resides in two-dimensional Cartesian plane, with the positive x-axis pointing right and the positive y-axis pointing up.
Currently, he is located at the point (sx,sy). In each second, he can move up, down, left or right by a distance of 1.
Here, both the x- and y-coordinates before and after each movement must ... | ```python
A, B, X, Y = map(int, input().split())
P = X-A
Q = Y-B
print("R"*P+"U"*Q+"L"*P+"D"*Q+"L"+"U"*(Q+1)+"R"*(P+1)+"D"+\
"R"+"D"*(Q+1)+"L"*(P+1)+"U")
``` |
p04003 AtCoder Regular Contest 061 - Snuke's Subway Trip | Snuke's town has a subway system, consisting of N stations and M railway lines. The stations are numbered 1 through N. Each line is operated by a company. Each company has an identification number.
The i-th ( 1 \leq i \leq M ) line connects station p_i and q_i bidirectionally. There is no intermediate station. This li... | ```python
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict, deque
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, produ... |
p00089 The Shortest Path on A Rhombic Path | <image>
Arrange integers (0 or more and 99 or less) in a rhombus as illustrated in Fig. 1. Create a program that reads the data representing the rhombus and outputs the maximum value of the sum of the integers that pass when starting from the top and proceeding to the bottom according to the following rules.
* At ea... | ```python
import sys
s=[list(map(int,e.split(',')))for e in sys.stdin]
for i in range(1,len(s)):
for j in range(len(s[i])):
t=j-(len(s[i])>len(s[i-1]))
s[i][j]+=max(s[i-1][t*(j>0):t+2])
print(*s[-1])
``` |
p00221 FizzBuzz | There is a game that uses numbers called "Fizz Buzz". In this game, multiple players count the numbers one by one, starting with 1, and each player says only one number after the previous player. At that time, you must say "Fizz" if it is divisible by 3, "Buzz" if it is divisible by 5, and "FizzBuzz" if it is divisible... | ```python
def fizzbuzz(i):
if i % 15 == 0:
return 'FizzBuzz'
elif i % 5 == 0:
return 'Buzz'
elif i % 3 == 0:
return 'Fizz'
else:
return str(i)
import sys
f = sys.stdin
while True:
m, n = map(int, f.readline().split())
if m == n == 0:
break
member = ... |
p00735 Monday-Saturday Prime Factors | Chief Judge's log, stardate 48642.5. We have decided to make a problem from elementary number theory. The problem looks like finding all prime factors of a positive integer, but it is not.
A positive integer whose remainder divided by 7 is either 1 or 6 is called a 7N+{1,6} number. But as it is hard to pronounce, we s... | ```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def monsat(num):
L = [False for i in range(num+1)]
for i in range(0,num,7):
if i == 1 or i == 0:
continue
for d in [-1,1]:
if L[i+d] == False:
L[i+d] = True
for j in range((i+d)*2,num... |
p00875 Repeated Substitution with Sed | Do you know "sed," a tool provided with Unix? Its most popular use is to substitute every occurrence of a string contained in the input string (actually each input line) with another string β. More precisely, it proceeds as follows.
1. Within the input string, every non-overlapping (but possibly adjacent) occurrences... | ```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 = [(0,-1),(1,0),(0,1),(-1,0)]
ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)]
def LI(): return [int(x) for x in ... |
p01138 Osaki | Osaki
Osaki
English text is not available in this practice contest.
The Yamanote Line is a circular railway line laid in the 23 wards of Tokyo. The total route distance is 34.5km, and one lap takes about one hour. There are 29 stations in total. The line color is Uguisu color. The peak congestion rate exceeds 200%, ... | ```python
while True:
n = int(input())
if n == 0: break
trains = []
for _ in range(n):
dept, ariv = input().split()
trains.append((dept, ariv))
trains.sort(key=lambda x:x[0])
dcheck = 0
usecar = 0
returntime = []
for tridx in range(len(trains)):
new = Tru... |
p01277 Symmetry | Open Binary and Object Group organizes a programming contest every year. Mr. Hex belongs to this group and joins the judge team of the contest. This year, he created a geometric problem with its solution for the contest. The problem required a set of points forming a line-symmetric polygon for the input. Preparing the ... | ```python
from collections import defaultdict
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def gcd(m, n):
while n:
m, n = n, m % n
return m
def solve():
N = int(readline())
P = [list(map(int, readline().split())) for i in range(N)]
ok = 0
x0, y0 = P[0]; x1, y1 = P[1]... |
p01447 Earth Invasion Diary of Miyabi-sensei | The Quarkgo Empire Expeditionary Force is an evil organization that plans to invade the Earth. In keeping with the tradition of the invaders, they continued to send monsters at a pace of one every week, targeting the area around Tokyo in Japan. However, each time, five warriors calling themselves the Human Squadron Ear... | ```python
N = int(input())
n = 1
ans = 1
while True:
n *= 3
if n>=N:
print(ans)
break
ans+=1
``` |
p01753 Magic Bullet | In 20XX AD, a school competition was held. The tournament has finally left only the final competition. You are one of the athletes in the competition.
The competition you participate in is to compete for the time it takes to destroy all the blue objects placed in the space. Athletes are allowed to bring in competition... | ```python
N, Q = map(int, input().split())
x = [None] * N
y = [None] * N
z = [None] * N
r = [None] * N
l = [None] * N
for i in range(N):
x[i], y[i], z[i], r[i], l[i] = map(int, input().split())
for _ in range(Q):
ans = 0
sx, sy, sz, dx, dy, dz = map(int, input().split())
vx = dx - sx
vy = dy - sy
... |
p01893 Lost Graph | Problem statement
You and AOR Ika are preparing for a graph problem in competitive programming. Generating input cases is AOR Ika-chan's job. The input case for that problem is a directed graph of the $ N $ vertices. The vertices are numbered from $ 1 $ to $ N $. Edges may contain self-loops, but not multiple edges.
... | ```python
from operator import itemgetter
N = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
cnt_a = 0
cnt_b = 0
for i, (a, b) in enumerate(zip(A, B)):
cnt_a += i*a
cnt_b += i*b
if cnt_a!=cnt_b or not sum(A)==sum(B)==N:
print("NO")
exit()
B_ = []
cumi = 0
for i, b... |
p02030 Information Search | A: Information Search
problem
The posting list is a list in which there is a correspondence between the search term and the appearing document ID. For example
* Hokkaido: 1, 2, 4, 9
* Sightseeing: 1, 3, 4, 7
And so on.
From the above posting list, if you search for and, the document with ID 1, 4 will be hit, and... | ```python
n,m = map(int,input().split())
a = set(map(int,input().split()))
b = set(map(int,input().split()))
i = sorted(a&b)
u = sorted(a|b)
print(len(i),len(u))
for x in i:
print(x)
for x in u:
print(x)
``` |
p02461 Map: Range 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$.
* get($key$): Print the value with the specified $... | ```python
import sys
import bisect
n = int(input())
arr = []
lines = sys.stdin.readlines()
ans = [None] * n
d = {}
for i in range(n):
q, *arg = lines[i].split()
key = arg[0]
idx = bisect.bisect_left(arr, arg[0])
if q == '0': # insert
if idx == len(arr) or arr[idx] != key:
arr.ins... |
1010_B. Rocket | This is an interactive problem.
Natasha is going to fly to Mars. Finally, Natasha sat in the rocket. She flies, flies... but gets bored. She wishes to arrive to Mars already! So she decides to find something to occupy herself. She couldn't think of anything better to do than to calculate the distance to the red planet... | ```python
from sys import stdin
from math import *
from sys import stdout
line = stdin.readline().rstrip().split()
m = int(line[0])
n = int(line[1])
bits = []
for i in range(n):
print(m)
stdout.flush()
line = stdin.readline().rstrip().split()
res = int(line[0])
if res == 0:
exit(0)
if ... |
1034_B. Little C Loves 3 II | Little C loves number «3» very much. He loves all things about it.
Now he is playing a game on a chessboard of size n × m. The cell in the x-th row and in the y-th column is called (x,y). Initially, The chessboard is empty. Each time, he places two chessmen on two different empty cells, the Manhattan distance between ... | ```python
known = [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 2, 4],
[0, 0, 0, 4, 8, 10],
[0, 0, 4, 8, 12, 14],
[0, 2, 8, 12, 16, 20],
[0, 4, 10, 14, 20, 24]
]
n,m = map(int,input().split(" "))
if n>m:
n,m = m,n
if n<=5 and m<=5:
print(known[m][n])
elif n==1:
print(6*(m//6)+ [0,0,0,0,2,4][m%6... |
109_B. Lucky Probability | Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya and his friend Vasya play an interesting game. Petya randomly chooses an integer p from the in... | ```python
import itertools as it
all_lucky = []
for length in range(1, 10):
for comb in it.product(['7', '4'], repeat=length):
all_lucky += [int(''.join(comb))]
all_lucky.sort()
# print(len(all_lucky))
pl, pr, vl, vr, k = map(int, input().split())
result = 0
def inters_len(a, b, c, d):
a, b = s... |
1120_B. Once in a casino | One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow.
A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this o... | ```python
def main():
n = int(input())
a = list(map(int, (x for x in input())))
b = list(map(int, (x for x in input())))
x = [0] * (n - 1)
x[0] = b[0] - a[0]
for i in range(1, n - 1):
x[i] = b[i] - a[i] - x[i - 1]
if a[n - 1] + x[n - 2] != b[n - 1]:
print(-1)
return
... |
1187_B. Letters Shop | The letters shop showcase is a string s, consisting of n lowercase Latin letters. As the name tells, letters are sold in the shop.
Letters are sold one by one from the leftmost to the rightmost. Any customer can only buy some prefix of letters from the string s.
There are m friends, the i-th of them is named t_i. Eac... | ```python
from collections import defaultdict
n = int(input())
s = input()
r = defaultdict(list)
for i, c in enumerate(s):
r[c].append(i)
m = int(input())
for i in range(m):
t = input()
ans = 0
pos = defaultdict(int)
for c in t:
pos[c] += 1
ans = max(ans, r[c][pos[c]-1])
print(a... |
1206_A. Choose Two Numbers | You are given an array A, consisting of n positive integers a_1, a_2, ..., a_n, and an array B, consisting of m positive integers b_1, b_2, ..., b_m.
Choose some element a of A and some element b of B such that a+b doesn't belong to A and doesn't belong to B.
For example, if A = [2, 1, 7] and B = [1, 3, 4], we can ... | ```python
n=int(input())
a=list(map(int,input().split()))
m=int(input())
b=list(map(int,input().split()))
t=[];o=[]
for i in a:
for j in b:
t.append(i+j)
o.append((i,j))
for i in range(len(t)):
if (t[i] not in a) and (t[i] not in b):
print(o[t.index(t[i])][0])
print(o[t.index(t[... |
1223_D. Sequence Sorting | You are given a sequence a_1, a_2, ..., a_n, consisting of integers.
You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.
For example,... | ```python
import sys
input=sys.stdin.buffer.readline
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
stored=[-1 for i in range(n+2)]
counted=[[0,0] for i in range(n+2)]
count=0
for i in range(n):
stored[a[i]]=a[i]
if(counted[a[i]][0]==0):
... |
1249_A. Yet Another Dividing into Teams | You are a coach of a group consisting of n students. The i-th student has programming skill a_i. All students have distinct programming skills. You want to divide them into teams in such a way that:
* No two students i and j such that |a_i - a_j| = 1 belong to the same team (i.e. skills of each pair of students in t... | ```python
from itertools import *
q = int(input())
for _ in range(q):
n = int(input())
a = list(map(int, input().split()))
a.sort()
cnt = 1
while len(a) > 1:
a = list(a)
b = []
for i in range(1, len(a)):
if a[i] - a[i - 1] <= 1:
b.append(a[i])
... |
128_A. Statues | In this task Anna and Maria play a game with a very unpleasant rival. Anna and Maria are in the opposite squares of a chessboard (8 × 8): Anna is in the upper right corner, and Maria is in the lower left one. Apart from them, the board has several statues. Each statue occupies exactly one square. A square that contains... | ```python
f = []
for i in range(8):
f.append(input())
d = [[[0 for i in range(8)] for j in range(8)] for k in range(100)]
d[0][7][0] = 1
dx = [1, 1, 1, 0, 0, -1, -1, -1, 0]
dy = [1, 0, -1, 1, -1, 1, 0, -1, 0]
ans = 'LOSE'
for i in range(99):
for x in range(8):
for y in range(8):
if not d[... |
1332_B. Composite Coloring | A positive integer is called composite if it can be represented as a product of two positive integers, both greater than 1. For example, the following numbers are composite: 6, 4, 120, 27. The following numbers aren't: 1, 2, 3, 17, 97.
Alice is given a sequence of n composite numbers a_1,a_2,…,a_n.
She wants to choos... | ```python
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
dct={}
m=1
arr1=[]
for n1 in arr:
check=-1
n2=int(n1**(0.5))
for j in range(2,n2+1,1):
if(n1%j==0):
check=0
if(j in dct.keys()):
... |
1352_E. Special Elements | Pay attention to the non-standard memory limit in this problem.
In order to cut off efficient solutions from inefficient ones in this problem, the time limit is rather strict. Prefer to use compiled statically typed languages (e.g. C++). If you use Python, then submit solutions on PyPy. Try to write an efficient solut... | ```python
import sys
from math import ceil
read=sys.stdin.buffer.readline
mi=lambda:map(int,read().split())
li=lambda:list(mi())
cin=lambda:int(read())
for _ in range(cin()):
n=cin()
a=li()
freq=[0]*(n+1)
for el in a:
freq[el]+=1
ans=0
for i in range(n-1):
sm=a[i]
for j ... |
1372_C. Omkar and Baseball | Patrick likes to play baseball, but sometimes he will spend so many hours hitting home runs that his mind starts to get foggy! Patrick is sure that his scores across n sessions follow the identity permutation (ie. in the first game he scores 1 point, in the second game he scores 2 points and so on). However, when he ch... | ```python
import sys
import math
import heapq
import collections
def inputnum():
return(int(input()))
def inputnums():
return(map(int,input().split()))
def inputlist():
return(list(map(int,input().split())))
def inputstring():
return([x for x in input()])
def inputmatrixchar(rows):
arr2d = [[j for j... |
1395_B. Boboniu Plays Chess | Boboniu likes playing chess with his employees. As we know, no employee can beat the boss in the chess game, so Boboniu has never lost in any round.
You are a new applicant for his company. Boboniu will test you with the following chess question:
Consider a n× m grid (rows are numbered from 1 to n, and columns are nu... | ```python
def print_column(x1,y1):
global last
print(x1,y1)
a=y1-1
k=0
while (a>0):
print(x1,a)
a-=1
k=a+1
a=y1+1
while (a<=m):
print(x1,a)
a+=1
k=a-1
last=k
#print(f"last spoted at ({x1},{last})")
return last
def print_m... |
1419_D2. Sage's Birthday (hard version) | This is the hard version of the problem. The difference between the versions is that in the easy version all prices a_i are different. You can make hacks if and only if you solved both versions of the problem.
Today is Sage's birthday, and she will go shopping to buy ice spheres. All n ice spheres are placed in a row ... | ```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.w... |
1437_E. Make It Increasing | You are given an array of n integers a_1, a_2, ..., a_n, and a set b of k distinct integers from 1 to n.
In one operation, you may choose two integers i and x (1 ≤ i ≤ n, x can be any integer) and assign a_i := x. This operation can be done only if i does not belong to the set b.
Calculate the minimum number of opera... | ```python
import bisect
def stablesort(s,l6):
l3 = []
l4 = [0]
for i in range(len(s)):
if l6[0] == -1:
if s[i]<=l[l6[1]]:
k = bisect.bisect(l3,s[i])
if len(l3) == 0 or l3[-1]<=s[i]:
l3.append(s[i])
l4.append(l4[-1] +... |
1462_C. Unique Number | You are given a positive number x. Find the smallest positive integer number that has the sum of digits equal to x and all digits are distinct (unique).
Input
The first line contains a single positive integer t (1 ≤ t ≤ 50) — the number of test cases in the test. Then t test cases follow.
Each test case consists of ... | ```python
test=int(input())
for testcase in range(test):
n=int(input())
if(n<=45):
if(n<10):
print(n)
else:
i=9
s=0
ans=0
while(i>0):
#print(i)
if(s+i<=n):
s+=i
ans... |
1487_D. Pythagorean Triples | A Pythagorean triple is a triple of integer numbers (a, b, c) such that it is possible to form a right triangle with the lengths of the first cathetus, the second cathetus and the hypotenuse equal to a, b and c, respectively. An example of the Pythagorean triple is (3, 4, 5).
Vasya studies the properties of right tria... | ```python
import math
t = int(input())
for _ in range(t):
n = int(input())
n = math.floor(math.sqrt(n+n-1))
if n%2==0:
print((n//2)-1)
else:
print(((n+1)//2)-1)
``` |
1511_A. Review Site | You are an upcoming movie director, and you have just released your first movie. You have also launched a simple review site with two buttons to press — upvote and downvote.
However, the site is not so simple on the inside. There are two servers, each with its separate counts for the upvotes and the downvotes.
n revi... | ```python
t = int(input())
for _ in range(t):
n = int(input())
ans = 0
a = [int(i) for i in input().split()]
for i in a:
if i == 1 or i == 3:
ans += 1
print(ans)
``` |
1538_F. Interesting Function | You are given two integers l and r, where l < r. We will add 1 to l until the result is equal to r. Thus, there will be exactly r-l additions performed. For each such addition, let's look at the number of digits that will be changed after it.
For example:
* if l=909, then adding one will result in 910 and 2 digits... | ```python
def count(s):
ans = 0
for i in range(len(s), 0 ,-1):
ans += int(s[:i])
return ans
for t in range(int(input())):
l, r = input().split()
print(count(r) - count(l))
``` |
165_A. Supercentral Point | One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (x1, y1), (x2, y2), ..., (xn, yn). Let's define neighbors for some fixed point from the given set (x, y):
* point (x', y') is (x, y)'s right neighbor, if x' > x and y' = y
* point (x', y') is (x, y)'s left neighb... | ```python
n=int(input())
a=[]
for i in range(0,n):
a.append([int(i) for i in input().split()])
ans=0
for i in range(0,n):
c1=0
c2=0
c3=0
c4=0
for j in range(0,n):
if a[i][0]>a[j][0] and a[i][1]==a[j][1]:
c1+=1
elif a[i][0]<a[j][0] and a[i][1]==a[j][1]:
c2+... |
186_B. Growing Mushrooms | Each year in the castle of Dwarven King there is a competition in growing mushrooms among the dwarves. The competition is one of the most prestigious ones, and the winner gets a wooden salad bowl. This year's event brought together the best mushroom growers from around the world, so we had to slightly change the rules ... | ```python
n, t1, t2, k = map(int, input().split())
a = n * [0]
list_indexes = []
for i in range(n):
x = list(map(int, input().split()))
x.sort()
a[i] = x
for j in range(n):
a[j] = max((a[j][0] * t1 * ((100 - k) / 100) + a[j][1] * t2),
(a[j][1] * t1 * ((100 - k) / 100) + a[j][0] * t2))
... |
207_D4. The Beaver's Problem - 3 | The Smart Beaver from ABBYY came up with another splendid problem for the ABBYY Cup participants! This time the Beaver invites the contest participants to check out a problem on sorting documents by their subjects. Let's describe the problem:
You've got some training set of documents. For each document you know its su... | ```python
print('1')
``` |
281_B. Nearest Fraction | You are given three positive integers x, y, n. Your task is to find the nearest fraction to fraction <image> whose denominator is no more than n.
Formally, you should find such pair of integers a, b (1 ≤ b ≤ n; 0 ≤ a) that the value <image> is as minimal as possible.
If there are multiple "nearest" fractions, choose... | ```python
import sys
from fractions import Fraction
def input(): return sys.stdin.readline().strip()
def iinput(): return int(input())
def rinput(): return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7
x, y, n = rin... |
304_A. Pythagorean Theorem II | In mathematics, the Pythagorean theorem — is a relation in Euclidean geometry among the three sides of a right-angled triangle. In terms of areas, it states:
In any right-angled triangle, the area of the square whose side is the hypotenuse (the side opposite the right angle) is equal to the sum of the areas of the sq... | ```python
def gcd(a, b):
c = a % b
return gcd(b, c) if c else b
from math import sqrt
n = int(input())
print(sum(n // (x * x + y * y) for x in range(1, int(sqrt(n // 2)) + 1) for y in range(x + 1, int(sqrt(n - x * x)) + 1, 2) if gcd(x, y) == 1))
``` |
330_B. Road Construction | A country has n cities. Initially, there is no road in the country. One day, the king decides to construct some roads connecting pairs of cities. Roads can be traversed either way. He wants those roads to be constructed in such a way that it is possible to go from each city to any other city by traversing at most two r... | ```python
__author__ = 'Rajan'
n,m = map(int,input().split())
# n nodes and m edges
hash = [False for i in range(n+1)]
for i in range(m):
a,b = map(int,input().split())
hash[a] = hash[b] = True
b = 0
for i in range(1,n+1):
if not hash[i]:
b = i
break
print(n-1)
for i in range(1,n+1):
i... |
351_E. Jeff and Permutation | Jeff's friends know full well that the boy likes to get sequences and arrays for his birthday. Thus, Jeff got sequence p1, p2, ..., pn for his birthday.
Jeff hates inversions in sequences. An inversion in sequence a1, a2, ..., an is a pair of indexes i, j (1 ≤ i < j ≤ n), such that an inequality ai > aj holds.
Jeff c... | ```python
n = int(input())
inp = input()
seq = inp.split(' ')
seq = [ abs(int(x)) for x in seq ]
Max = max(seq)
nxt = [0] * n
cnt = [0] * n
pos = [n] * (Max+1)
for i in range(n-1, -1, -1):
nxt[i] = pos[seq[i]]
pos[seq[i]] = i
for i in range(0, Max+1):
j = pos[i]
while(j<n):
front = sum(cnt[0:j])... |
376_A. Lever | You have a description of a lever as string s. We'll represent the string length as record |s|, then the lever looks as a horizontal bar with weights of length |s| - 1 with exactly one pivot. We will assume that the bar is a segment on the Ox axis between points 0 and |s| - 1.
The decoding of the lever description is ... | ```python
a=input()
x=a.index('^')
c=0
for i in range(len(a)):
if a[i]in['^','=']:continue
c+=int(a[i])*(i-x)
print("right"if c>0else("left"if c<0else"balance"))
``` |
420_D. Cup Trick | The employees of the F company have lots of ways to entertain themselves. Today they invited a famous magician who shows a trick with plastic cups and a marble.
The point is to trick the spectator's attention. Initially, the spectator stands in front of a line of n plastic cups. Then the magician places a small marble... | ```python
import io
import os
# List with O(n^1/3) (for n=10**6) get/set/insert/delete based on: https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SortedList.py
class UnsortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
value... |
447_B. DZY Loves Strings | DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter c DZY knows its value wc. For each special string s = s1s2... s|s| (|s| is the length of the string) he represents its value with a function f(s), where
<image>
Now DZY has a string s. He wants to insert k lowercase ... | ```python
s = input()
k = int(input())
w = list(map(int, input().split()))
value = 0
for i in range(len(s)):
value += (i + 1) * w[ord(s[i]) - ord('a')]
for i in range(len(s) + 1, len(s) + k + 1):
value += max(w) * i
print(value)
``` |
469_C. 24 Game | Little X used to play a card game called "24 Game", but recently he has found it too easy. So he invented a new game.
Initially you have a sequence of n integers: 1, 2, ..., n. In a single step, you can pick two of them, let's denote them a and b, erase them from the sequence, and append to the sequence either a + b, ... | ```python
n = int(input())
if n < 4:
print('NO')
elif n == 4:
print('YES')
print('1 * 2 = 2')
print('2 * 3 = 6')
print('6 * 4 = 24')
elif n == 5:
print('YES')
print('4 * 5 = 20')
print('3 - 1 = 2')
print('20 + 2 = 22')
print('22 + 2 = 24')
else:
print('YES')
print('2 * 3 ... |
491_B. New York Hotel | Think of New York as a rectangular grid consisting of N vertical avenues numerated from 1 to N and M horizontal streets numerated 1 to M. C friends are staying at C hotels located at some street-avenue crossings. They are going to celebrate birthday of one of them in the one of H restaurants also located at some street... | ```python
N, M = input().split()
a, b, c, d = [int(1e10) for _ in range(4)]
for i in range(int(input())):
x, y = list(map(int, input().split()))
a, b, c, d = min(a, x + y), min(b, x - y), min(c, - x + y), min(d, - x - y)
res, pos = int(1e10), 0
for i in range(int(input())):
x, y = list(map(int, input().spli... |
515_C. Drazil and Factorial | Drazil is playing a math game with Varda.
Let's define <image> for positive integer x as a product of factorials of its digits. For example, <image>.
First, they choose a decimal number a consisting of n digits that contains at least one digit larger than 1. This number may possibly start with leading zeroes. Then th... | ```python
#in the name of god
#Mr_Rubik
#CodeForces,Problemset
sepData=[[],[],[2],[3],[2,2,3],[5],[5,3],[7],[7,2,2,2],[7,2,3,3]]
digit=input()
number=input()
ans=[]
for i in number:
if i!='1' and i!='\r':
for j in sepData[int(i)]:
ans.append(j)
ans.sort(reverse=True)
for i in ans:
print(i,en... |
590_C. Three States | The famous global economic crisis is approaching rapidly, so the states of Berman, Berance and Bertaly formed an alliance and allowed the residents of all member states to freely pass through the territory of any of them. In addition, it was decided that a road between the states should be built to guarantee so that on... | ```python
# lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje
from collections import deque
n, m = input().split()
n = int(n)
m = int(m)
def idx(i, j):
return i*m + j
max = n*m*2
graph = ""
virtDist = [[], [], []]
virtVertex = [deque(), deque(), deque()]
vir... |
612_B. HDD is Outdated Technology | HDD hard drives group data by sectors. All files are split to fragments and each of them are written in some sector of hard drive. Note the fragments can be written in sectors in arbitrary order.
One of the problems of HDD hard drives is the following: the magnetic head should move from one sector to another to read s... | ```python
n = int(input())
fi = list(map(int, input().split()))
fi2 = list(range(n))
i = 0
while i < n:
fi2[fi[i] - 1] = i
i += 1
pos = fi2[0]
i = 1
d = 0
while i < n:
d += abs(fi2[i] - pos)
pos = fi2[i]
i += 1
print(d)
``` |
632_B. Alice, Bob, Two Teams | Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are n pieces, and the i-th piece has a strength pi.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups A and B. This can be seen as writing the... | ```python
read = lambda: map(int, input().split())
n = int(input())
p = list(read())
a = [{'B': 1, 'A': 0}[i] for i in input()]
cur = sum(p[i] for i in range(n) if a[i])
ans = cur
b = a[:]
for i in range(n):
b[i] = int(not a[i])
if b[i]: cur += p[i]
else: cur -= p[i]
ans = max(ans, cur)
cur = sum(p[i] f... |
660_E. Different Subsets For All Tuples | For a sequence a of n integers between 1 and m, inclusive, denote f(a) as the number of distinct subsequences of a (including the empty subsequence).
You are given two positive integers n and m. Let S be the set of all sequences of length n consisting of numbers from 1 to m. Compute the sum f(a) over all a in S modulo... | ```python
import sys
from array import array
n, m = map(int, input().split())
dp = [array('i', [0])*(n+1) for _ in range(2)]
dp[0][0] = dp[1][0] = 1
mod = 10**9 + 7
for i in range(1, n+1):
dp[0][i] = (dp[0][i-1] * m + dp[0][i-1] * (m-1)) % mod
dp[1][i] = (dp[0][i-1] * m + dp[1][i-1] * m) % mod
print(dp[1][-1... |
707_C. Pythagorean Triples | Katya studies in a fifth grade. Recently her class studied right triangles and the Pythagorean theorem. It appeared, that there are triples of positive integers such that you can construct a right triangle with segments of lengths corresponding to triple. Such triples are called Pythagorean triples.
For example, tripl... | ```python
if __name__ == '__main__':
n = int(input())
if n < 3:
print(-1)
elif n % 2 == 0:
print(str(n*n//4-1) + " " + str(n*n//4+1))
else:
print(str((n*n-1)//2) + " " + str((n*n+1)//2))
``` |
750_A. New Year and Hurry | Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th... | ```python
def main():
n,m = [int(v) for v in input().split()]
e = 4*60-m
d = 0
i = 1
while d<=e:
d+=5*(i)
if d>e:
break
i+=1
print(min(n,i-1))
if __name__ == "__main__":
main()
``` |
798_D. Mike and distribution | Mike has always been thinking about the harshness of social inequality. He's so obsessed with it that sometimes it even affects him while solving problems. At the moment, Mike has two sequences of positive integers A = [a1, a2, ..., an] and B = [b1, b2, ..., bn] of length n each which he uses to ask people some quite p... | ```python
n = int(input())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
idAB = zip(range(n), A, B)
idAB = sorted(idAB, key=lambda x: x[1], reverse=True)
ans = [idAB[0][0] + 1]
i = 1
while i < n:
choice = max(idAB[i:i + 2], key=lambda x: x[2])
ans.append(choice[0] + 1)
... |
818_F. Level Generation | Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly ni vertices in the graph representing level i, and the edges have to be bidirectional. When c... | ```python
#! /usr/bin/env python
# http://codeforces.com/problemset/problem/818/F
# Problem name ::: F. Level Generation
# submission number
#212055293
#508427854
def newest_approach(n):
from math import floor, ceil, sqrt
quad_solv = sqrt(2*n+1/4)-1/2
x = floor(quad_solv)
y = ceil(quad_solv)
x... |
844_B. Rectangles | You are given n × m table. Each cell of the table is colored white or black. Find the number of non-empty sets of cells such that:
1. All cells in a set have the same color.
2. Every two cells in a set share row or column.
Input
The first line of input contains integers n and m (1 ≤ n, m ≤ 50) — the number of ... | ```python
from math import factorial
def count(n, k):
return factorial(n) // (factorial(k) * factorial(n - k))
n, m = map(int, input().split())
table = []
for i in range(n):
table.append(list(map(int, input().split())))
ans = 0
for i in range(n):
c0 = table[i].count(0)
c1 = table[i].count(1)
for j... |
864_E. Fire | Polycarp is in really serious trouble — his house is on fire! It's time to save the most valuable items. Polycarp estimated that it would take ti seconds to save i-th item. In addition, for each item, he estimated the value of di — the moment after which the item i will be completely burned and will no longer be valuab... | ```python
from sys import stdin, stdout
n = int(stdin.readline())
items = []
for i in range(n):
t,d,p = map(int,stdin.readline().split())
items.append((d,p,t,i+1))
items.sort()
N = 2000+1
dp = [0 for i in range(N)]
cur = [[] for i in range(N)]
for d,p,t,it in items:
for i in range(d-1,t-1,-1):
if dp[i-t] + ... |
88_D. Vasya and Types | Programmer Vasya is studying a new programming language &K*. The &K* language resembles the languages of the C family in its syntax. However, it is more powerful, which is why the rules of the actual C-like languages are unapplicable to it. To fully understand the statement, please read the language's description below... | ```python
types = {'void':'void', 'errtype':'errtype'}
def getRealType(type_expr):
expr_type = type_expr.strip('&*')
full_type_name = type_expr.replace(expr_type, types.get(expr_type, "errtype"))
base_type = full_type_name.strip('&*')
if base_type == "void":
addr_count = full_type_name.count('*')
deref... |
913_B. Christmas Spruce | Consider a rooted tree. A rooted tree has one special vertex called the root. All edges are directed from the root. Vertex u is called a child of vertex v and vertex v is called a parent of vertex u if there exists a directed edge from v to u. A vertex is called a leaf if it doesn't have children and has a parent.
Let... | ```python
if __name__ == '__main__':
n = int(input())
nonleaf = [0 for i in range(1010)]
child = [[] for i in range(1010)]
leaf = [0 for i in range(1010)]
def dfs(s):
cnt = 0
for chd in child[s]:
cnt += dfs(chd)
leaf[s] = cnt
return 1 - nonleaf[s]
fo... |
935_B. Fafa and the Gates | Two neighboring kingdoms decided to build a wall between them with some gates to enable the citizens to go from one kingdom to another. Each time a citizen passes through a gate, he has to pay one silver coin.
The world can be represented by the first quadrant of a plane and the wall is built along the identity line (... | ```python
n=int(input())
s=input()
x=0
y=0
c=0
side=2
lastside=2
for i in s:
prevx=x
prevy=y
if i=='U':
y+=1
if i=='R':
x+=1
lastside=side
if x>y:
side=0
elif x<y:
side=1
if lastside!=side and lastside!=2:
c+=1
print(c)
``` |
961_A. Tetris | You are given a following process.
There is a platform with n columns. 1 × 1 squares are appearing one after another in some columns on this platform. If there are no squares in the column, a square will occupy the bottom row. Otherwise a square will appear at the top of the highest square of this column.
When all ... | ```python
n, m = map(int, input().split())
mas = list(map(int, input().split()))
mn = 1001
for i in range(1, n + 1):
if mas.count(i) < mn:
mn = mas.count(i)
print(mn)
``` |
988_F. Rain and Umbrellas | Polycarp lives on a coordinate line at the point x = 0. He goes to his friend that lives at the point x = a. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on n non-intersecting segments, the i... | ```python
import sys
a,m,n=list(map(int,input().split()))
aux=[0]*(a+1)
inf=10**15
dp=[aux.copy() for i in range(n+1)]
m1=10**12
m2=10**12
for i in range(m):
l,r=list(map(int,input().split()))
if l<m1:
m1=l
for j in range(l,r):
dp[0][j+1]=inf
s=[]
for i in range(1,n+1):
x,w=list(map(int,... |
p02598 AtCoder Beginner Contest 174 - Logs | We have N logs of lengths A_1,A_2,\cdots A_N.
We can cut these logs at most K times in total. When a log of length L is cut at a point whose distance from an end of the log is t (0<t<L), it becomes two logs of lengths t and L-t.
Find the shortest possible length of the longest log after at most K cuts, and print it a... | ```python
n,k = map(int,input().split())
l = list(map(int,input().split()))
l.sort()
x,y=0,10**9
while y>x+1:
m = (x+y)//2
c=0
for i in l:
c+=(i-1)//m
if c<=k:
y=m
else:
x=m
print(y)
``` |
p02729 AtCoder Beginner Contest 159 - The Number of Even Pairs | We have N+M balls, each of which has an integer written on it.
It is known that:
* The numbers written on N of the balls are even.
* The numbers written on M of the balls are odd.
Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.
It c... | ```python
N,M=map(int,input().split())
print(int(N*(N-1)/2.0 + M*(M-1)/2.0) )
``` |
p02862 AtCoder Beginner Contest 145 - Knight | There is a knight - the chess piece - at the origin (0, 0) of a two-dimensional grid.
When the knight is at the square (i, j), it can be moved to either (i+1,j+2) or (i+2, j+1).
In how many ways can the knight reach the square (X, Y)?
Find the number of ways modulo 10^9 + 7.
Constraints
* 1 \leq X \leq 10^6
* 1 \l... | ```python
X,Y = map(int, input().split())
m = (-X+2*Y)//3
n = (2*X-Y)//3
def combination(n, r, mod=10**9+7):
n1, r = n+1, min(r, n-r)
numer = denom = 1
for i in range(1, r+1):
numer = (numer*(n1-i)) % mod
denom = (denom*i) % mod
return numer * pow(denom, mod-2, mod) % mod
if (X+Y)%3 !=... |
p02996 AtCoder Beginner Contest 131 - Megalomania | Kizahashi, who was appointed as the administrator of ABC at National Problem Workshop in the Kingdom of AtCoder, got too excited and took on too many jobs.
Let the current time be time 0. Kizahashi has N jobs numbered 1 to N.
It takes A_i units of time for Kizahashi to complete Job i. The deadline for Job i is time B... | ```python
N = int(input())
L = [list(map(int, input().split())) for _ in range(N)]
L = sorted(L, key=lambda x: x[1])
t = 0
for l in L:
t += l[0]
if t > l[1]:
print('No')
exit(0)
print('Yes')
``` |
p03137 AtCoder Beginner Contest 117 - Streamline | We will play a one-player game using a number line and N pieces.
First, we place each of these pieces at some integer coordinate.
Here, multiple pieces can be placed at the same coordinate.
Our objective is to visit all of the M coordinates X_1, X_2, ..., X_M with these pieces, by repeating the following move:
Move... | ```python
n, m = map(int, input().split())
x = list(map(int, input().split()))
x.sort()
l = [x[i+1]-x[i] for i in range(m-1)]
l.sort(reverse=True)
print(sum(l[n-1:]))
``` |
p03282 AtCoder Beginner Contest 106 - To Infinity | Mr. Infinity has a string S consisting of digits from `1` to `9`. Each time the date changes, this string changes as follows:
* Each occurrence of `2` in S is replaced with `22`. Similarly, each `3` becomes `333`, `4` becomes `4444`, `5` becomes `55555`, `6` becomes `666666`, `7` becomes `7777777`, `8` becomes `888888... | ```python
s = str(input())
k = int(input())
for i in range(k):
if s[i] != "1":
print(s[i])
exit()
print("1")
``` |
p03437 AtCoder Petrozavodsk Contest 001 - Two Integers | You are given positive integers X and Y. If there exists a positive integer not greater than 10^{18} that is a multiple of X but not a multiple of Y, choose one such integer and print it. If it does not exist, print -1.
Constraints
* 1 ≤ X,Y ≤ 10^9
* X and Y are integers.
Input
Input is given from Standard Input in... | ```python
x, y = map(int, input().split())
if x % y == 0:
print('-1')
else:
print(x)
``` |
p00020 Capitalize | Write a program which replace all the lower-case letters of a given text with the corresponding captital letters.
Input
A text including lower-case letters, periods, and space is given in a line. The number of characters in the text is less than or equal to 200.
Output
Print the converted text.
Example
Input
t... | ```python
a=input().upper()
print(a)
``` |
p00151 Grid | There is a n × n grid D where each cell contains either 1 or 0.
Your task is to create a program that takes the gird data as input and computes the greatest number of consecutive 1s in either vertical, horizontal, or diagonal direction.
For example, the consecutive 1s with greatest number in the figure below is circl... | ```python
# Aizu Problem 00151: Grid
#
import sys, math, os, bisect
# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
sys.stdin = open("sample-input.txt", "rt")
def grid_length(n, grid):
L = 0
for row in grid:
L = max(L, max([len(_) for _ in row.split('0')]))
for c in range(n):
... |
p00472 A Traveler | problem
You are a traveler traveling on the JOI Highway. The JOI Highway is a road that extends straight from east to west, and there are n post towns on the JOI Highway. Numbered. The westernmost post town on the JOI highway is post town 1, and the easternmost post town is post town n.
You have decided to depart fro... | ```python
n, m = map(int, input().split())
accums = [0]
for i in range(n - 1):
accums.append(accums[-1] + int(input()))
result = 0
k = 0
for i in range(m):
a = int(input())
result = (result + abs(accums[k + a] - accums[k])) % 100000
k += a
print(result)
``` |
p00664 Cosmic Market | Cosmic market, commonly known as Kozumike, is the largest coterie spot sale in the universe. Doujin lovers of all genres gather at Kozumike. In recent years, the number of visitors to Kozumike has been increasing. If everyone can enter from the beginning, it will be very crowded and dangerous, so admission is restricte... | ```python
while True:
r, c, q = map(int, input().split())
if r == 0: break
querys = [list(map(int, input().split())) for _ in range(q)]
querys.reverse()
r_used = [False] * r
c_used = [False] * c
r_cnt = c
c_cnt = r
ans = 0
for a, b, o in querys:
if a == 0:
if not r_used[b]:
r_used[... |
p00938 Wall Clocks | Example
Input
2 10 6
4 4 E
6 4 W
Output
2 | ```python
N, W, D = map(int, input().split())
def calc(x0, y0, dx, dy):
s = min(W - x0 if dx >= 0 else x0, D - y0 if dy >= 0 else y0)
x = x0 + dx*s; y = y0 + dy*s
assert x in [0, W] or y in [0, D], (x, y)
if y == 0:
return x
if x == W:
return W+y
if y == D:
return 2*W+D-x... |
p01341 Save your cats | Nicholas Y. Alford was a cat lover. He had a garden in a village and kept many cats in his garden. The cats were so cute that people in the village also loved them.
One day, an evil witch visited the village. She envied the cats for being loved by everyone. She drove magical piles in his garden and enclosed the cats w... | ```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 ... |
p01679 SIRO Challenge | Problem Statement
You are now participating in the Summer Training Camp for Programming Contests with your friend Jiro, who is an enthusiast of the ramen chain SIRO. Since every SIRO restaurant has its own tasteful ramen, he wants to try them at as many different restaurants as possible in the night. He doesn't have p... | ```python
from heapq import heappush, heappop
import sys
def main():
readline = sys.stdin.readline
write = sys.stdout.write
L2 = 1 << 16
bc = [0]*L2
for i in range(1, L2):
bc[i] = bc[i ^ (i & -i)] + 1
INF = 10**18
def solve():
N, M, L, s, T = map(int, readline().split())
... |
p02245 8 Puzzle | The goal of the 8 puzzle problem is to complete pieces on $3 \times 3$ cells where one of the cells is empty space.
In this problem, the space is represented by 0 and pieces are represented by integers from 1 to 8 as shown below.
1 3 0
4 2 5
7 8 6
You can move a piece toward the empty space at one step. Your goal ... | ```python
import sys, collections
input = lambda: sys.stdin.readline().rstrip()
sys.setrecursionlimit(10**7)
INF = 10**10
def I(): return int(input())
def F(): return float(input())
def SS(): return input()
def LI(): return [int(x) for x in input().split()]
def LI_(): return [int(x)-1 for x in input().split()]
def LF(... |
p02391 Small | Write a program which prints small/large/equal relation of given two integers a and b.
Constraints
* -1000 ≤ a, b ≤ 1000
Input
Two integers a and b separated by a single space are given in a line.
Output
For given two integers a and b, print
a < b
if a is less than b,
a > b
if a is greater than b, and
a... | ```python
a, b = map(int, input().split())
if a == b:
print('a == b')
elif a < b:
print("a < b")
else:
print("a > b")
``` |
1047_B. Cover Points | There are n points on the plane, (x_1,y_1), (x_2,y_2), …, (x_n,y_n).
You need to place an isosceles triangle with two sides on the coordinate axis to cover all points (a point is covered if it lies inside the triangle or on the side of the triangle). Calculate the minimum length of the shorter side of the triangle.
I... | ```python
n = int(input())
m = [[int(i) for i in input().split()] for i in range(n)]
#l = [ sum(m[i]) for i in range(n) ]
#l = l.index(max(l))
print(max([ sum(m[i]) for i in range(n) ]))
``` |
1070_K. Video Posts | Polycarp took n videos, the duration of the i-th video is a_i seconds. The videos are listed in the chronological order, i.e. the 1-st video is the earliest, the 2-nd video is the next, ..., the n-th video is the last.
Now Polycarp wants to publish exactly k (1 ≤ k ≤ n) posts in Instabram. Each video should be a part ... | ```python
n, k = map(int, input().split())
sp = list(map(int, input().split()))
s = sum(sp) // k
s1 = []
ans, sm = 0, 0
for el in sp:
sm += el
ans += 1
if sm == s:
s1.append(ans)
ans, sm = 0, 0
elif sm > s:
print("No")
break
else:
if sum(s1) == n:
print("Yes")... |
1092_F. Tree with Maximum Cost | You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
... | ```python
import sys
from collections import deque
from types import GeneratorType
sys.setrecursionlimit(200000)
input = sys.stdin.readline
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
... |
1141_C. Polycarp Restores Permutation | An array of integers p_1, p_2, ..., p_n is called a permutation if it contains each number from 1 to n exactly once. For example, the following arrays are permutations: [3, 1, 2], [1], [1, 2, 3, 4, 5] and [4, 3, 1, 2]. The following arrays are not permutations: [2], [1, 1], [2, 3, 4].
Polycarp invented a really cool p... | ```python
if __name__ == '__main__':
n = input()
a = list(map(int, input().split()))
b = [0]
for ai in a:
b.append(b[-1] + ai)
b.sort()
for i in range(1, len(b)):
if b[i - 1] + 1 != b[i]:
print(-1)
break
else:
zero_idx = b.index(0)
... |
115_B. Lawnmower | You have a garden consisting entirely of grass and weeds. Your garden is described by an n × m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either gras... | ```python
n, m = [int(i) for i in input().split()]
if n == 1 and m == 1: # nothing to mow
print(0)
elif n == 1: # 1 row --> move right until last weed
lawn = input()
print(lawn.rfind('W'))
elif m == 1: # 1 column --> move down until last weed
weeds = 0
for i in range(n):
lawn = input()
... |
1182_B. Plus from Picture | You have a given picture with size w × h. Determine if the given picture has a single "+" shape or not. A "+" shape is described below:
* A "+" shape has one center nonempty cell.
* There should be some (at least one) consecutive non-empty cells in each direction (left, right, up, down) from the center. In other ... | ```python
def check(pic,row,col,h,w):
for i in range(row+1,h):
for j in range(w):
if j != col:
if pic[i][j] == '*':
return False
for i in range(row-1,-1,-1):
for j in range(w):
if j != col:
if pic[i][j] == '*':
... |
11_B. Jumping Jack | Jack is working on his jumping skills recently. Currently he's located at point zero of the number line. He would like to get to the point x. In order to train, he has decided that he'll first jump by only one unit, and each subsequent jump will be exactly one longer than the previous one. He can go either left or righ... | ```python
from math import sqrt
x = abs(int(input()))
n = int((sqrt(1 + 8 * x) - 1) / 2)
k = (n * (n + 1)) // 2
if k == x: print(n)
else:
n += 1
k += n
if (k - x) % 2:
n += 1
k += n
print(n + (k - x) % 2)
else: print(n)
``` |
1240_B. Sequence Sorting | You are given a sequence a_1, a_2, ..., a_n, consisting of integers.
You can apply the following operation to this sequence: choose some integer x and move all elements equal to x either to the beginning, or to the end of a. Note that you have to move all these elements in one direction in one operation.
For example,... | ```python
import sys as _sys
def main():
q = int(input())
for i_q in range(q):
n, = _read_ints()
a = tuple(_read_ints())
result = find_min_sorting_cost(sequence=a)
print(result)
def _read_line():
result = _sys.stdin.readline()
assert result[-1] == "\n"
return resu... |
1260_C. Infinite Fence | You are a rebel leader and you are planning to start a revolution in your country. But the evil Government found out about your plans and set your punishment in the form of correctional labor.
You must paint a fence which consists of 10^{100} planks in two colors in the following way (suppose planks are numbered from ... | ```python
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.... |
1282_C. Petya and Exam | Petya has come to the math exam and wants to solve as many problems as possible. He prepared and carefully studied the rules by which the exam passes.
The exam consists of n problems that can be solved in T minutes. Thus, the exam begins at time 0 and ends at time T. Petya can leave the exam at any integer time from 0... | ```python
res = []
for nt in range(int(input())):
n,t,a,b = map(int,input().split())
diff = list(map(int,input().split()))
time = list(map(int,input().split()))
count = diff.count(0)
new = [(time[i],diff[i]) for i in range(n)]
new.sort()
ans = 0
curr = 0
k = 0
c = 0
# print (new)
while k<len(new) and curr<... |
1326_D1. Prefix-Suffix Palindrome (Easy version) | This is the easy version of the problem. The difference is the constraint on the sum of lengths of strings and the number of test cases. You can make hacks only if you solve all versions of this task.
You are given a string s, consisting of lowercase English letters. Find the longest string, t, which satisfies the fol... | ```python
def is_polindrom(s):
return s == reverse(s)
def reverse(s):
return s[::-1]
result = []
test_am = int(input())
stroks = []
for alolo in range(test_am):
stroks.append(input())
for test in range(test_am):
string = stroks[test]
if is_polindrom(string):
print(string)
contin... |
1345_C. Hilbert's Hotel | Hilbert's Hotel is a very unusual hotel since the number of rooms is infinite! In fact, there is exactly one room for every integer, including zero and negative integers. Even stranger, the hotel is currently at full capacity, meaning there is exactly one guest in every room. The hotel's manager, David Hilbert himself,... | ```python
test = int(input())
for i in range(test):
n = int(input())
arr = list(map(int,input().split()))
rakh = [0] * n
temp = False
for i in range(0,n):
value = (arr[i] + i + 1000000000) % n
if rakh[value] != 0:
temp = True
break
else:
ra... |
1367_B. Even Array | You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero.
An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≤ i ≤ n - 1) the equality i mod 2 = a[i] m... | ```python
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 25 19:21:12 2020
@author: user
"""
def solve(n,l):
c1=0
c2=0
for i in range(n):
if(i%2==0 and l[i]%2!=0):
c1+=1
elif(i%2!=0 and l[i]%2==0):
c2+=1
if(c1==c2):
print(c1)
else:
print(-1)
... |
1388_B. Captain Flint and a Long Voyage | Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | ```python
#code
t=int(input())
while t>0:
n=int(input())
k=n/4
l=int(k)
if k==l:
for i in range(n-l):
print("9",end="")
for i in range(l):
print("8",end="")
print("")
else:
l+=1
for i in range(n-l):
print("9",end="")
... |
142_C. Help Caretaker | Autumn came late to the kingdom of Far Far Away. The harvest was exuberant and it is now time to get ready for the winter. As most people celebrate the Harvest festival, Simon the Caretaker tries to solve a very non-trivial task of how to find place for the agricultural equipment in the warehouse.
He's got problems wi... | ```python
n, m = map(int, input().split())
swapped = False
if n < m:
n, m = m, n
swapped = True
ans = ''
if n == 1 and m == 1:
ans = '''0
.'''
if n == 2 and m == 1:
ans = '''0
.
.'''
if n == 2 and m == 2:
ans = '''0
..
..'''
if n == 3 and m == 1:
ans = '''0
.
.
.'''
if n == 3 and m == 2:
ans = '''0
..
..
... |
1476_E. Pattern Matching | You are given n patterns p_1, p_2, ..., p_n and m strings s_1, s_2, ..., s_m. Each pattern p_i consists of k characters that are either lowercase Latin letters or wildcard characters (denoted by underscores). All patterns are pairwise distinct. Each string s_j consists of k lowercase Latin letters.
A string a matches ... | ```python
import sys;input = sys.stdin.readline
def topological_sorted(digraph):
n = len(digraph)
indegree = [0] * n
for v in range(n):
for nxt_v in digraph[v]:
indegree[nxt_v] += 1
tp_order = [i for i in range(n) if indegree[i] == 0]
stack = tp_order[:]
while stack:
... |
1503_B. 3-Coloring | This is an interactive problem.
Alice and Bob are playing a game. There is n× n grid, initially empty. We refer to the cell in row i and column j by (i, j) for 1≤ i, j≤ n. There is an infinite supply of tokens that come in 3 colors labelled 1, 2, and 3.
The game proceeds with turns as follows. Each turn begins with A... | ```python
from sys import stdin, stdout
n = int(stdin.readline())
ones = n**2 // 2
twos = n**2 - ones
i1, j1 = 0, 1
i2, j2 = 0, 0
while ones and twos:
a = stdin.readline()
if a == '1\n' or a == '3\n':
stdout.write(f"2 {i2+1} {j2+1}\n")
stdout.flush()
j2 += 2
if j2 >= n:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.