name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
1261_B1. Optimal Subsequences (Easy Version) | This is the easier version of the problem. In this version 1 ≤ n, m ≤ 100. You can hack this problem only if you solve and lock both problems.
You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily... | ```python
import copy
b=[]
a=[]
rezult=''
n=int(input())
a=list(map(int,input().split()))
m=int(input())
for i in range(1,m+1):
k,pos=map(int,input().split())
b=copy.deepcopy(a)
b.reverse()
for j in range(1,n-k+1):
b.remove(min(b))
b.reverse()
rezult=rezult+'\n'+str(b[pos-1])
print(rezul... |
1283_C. Friends and Gifts | There are n friends who want to give gifts for the New Year to each other. Each friend should give exactly one gift and receive exactly one gift. The friend cannot give the gift to himself.
For each friend the value f_i is known: it is either f_i = 0 if the i-th friend doesn't know whom he wants to give the gift to or... | ```python
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 19 09:55:17 2020
@author: Mridul Garg
"""
#def swap()
n = int(input())
arr = list(map(int, input().split(' ')))
check = [i for i in range(1, n+1)]
last0 = 0
for i in range(n):
if arr[i] != 0:
check[arr[i]-1] = 0
else:
last0 = i+1... |
1367_F2. Flying Sort (Hard Version) | This is a hard version of the problem. In this version, the given array can contain equal elements and the constraints on n are greater than in the easy version of the problem.
You are given an array a of n integers (the given array can contain equal elements). You can perform the following operations on array element... | ```python
from sys import stdin
input = stdin.readline
for _ in range(int(input())):
n = int(input())
l = list(map(int,input().split()))
id = list(zip(l,list(range(n))))
id.sort()
val, pos = zip(*id)
blok = []
cur = [pos[0]]
for i in range(1,n):
if val[i] == val[i-1]:
... |
1389_B. Array Walk | You are given an array a_1, a_2, ..., a_n, consisting of n positive integers.
Initially you are standing at index 1 and have a score equal to a_1. You can perform two kinds of moves:
1. move right — go from your current index x to x+1 and add a_{x+1} to your score. This move can only be performed if x<n.
2. mo... | ```python
# Some people dream of success, while others wake up and work hard at it. Napoleon Hill
# by : Blue Edge - Create some chaos
# import sys
# sys.stdin = open('input.txt', 'r')
for _ in range(int(input())):
n,k,z=map(int,input().split())
a=list(map(int,input().split()))
# print(k,z)
# print(*a... |
1409_E. Two Platforms | There are n points on a plane. The i-th point has coordinates (x_i, y_i). You have two horizontal platforms, both of length k. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same y-coordinate) and have integer borders. If the left border of the platform is (x, y) then the r... | ```python
from bisect import bisect,bisect_left
for _ in range(int(input())):
n,k=map(int,input().split())
x=list(map(int,input().split()))
y=input()
x.sort()
a=[]
b=[]
i=0
while i<n:
b.append(bisect(x,x[i]+k)-i)
a.append(i-bisect_left(x,x[i]-k)+1)
i+=1
b.rev... |
1430_C. Numbers on Whiteboard | Numbers 1, 2, 3, ... n (each integer from 1 to n once) are written on a board. In one operation you can erase any two numbers a and b from the board and write one integer (a + b)/(2) rounded up instead.
You should perform the given operation n - 1 times and make the resulting number that will be left on the board as s... | ```python
for _ in range (int(input())):
n=int(input())
hold=n
res=[]
for i in range (n-1,0,-1):
res.append((hold,i))
hold=(hold+i+1)//2
print(hold)
for i in res:
print(*i)
``` |
1453_E. Dog Snacks | Gildong is playing with his dog, Badugi. They're at a park that has n intersections and n-1 bidirectional roads, each 1 meter in length and connecting two intersections with each other. The intersections are numbered from 1 to n, and for every a and b (1 ≤ a, b ≤ n), it is possible to get to the b-th intersection from ... | ```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.... |
1477_C. Nezzar and Nice Beatmap | Nezzar loves the game osu!.
osu! is played on beatmaps, which can be seen as an array consisting of distinct points on a plane. A beatmap is called nice if for any three consecutive points A,B,C listed in order, the angle between these three points, centered at B, is strictly less than 90 degrees.
<image> Points A,B,... | ```python
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
def getDist(self, a):
dx = a.x - self.x
dy = a.y - self.y
return dx * dx + dy * dy
n = int(input())
a = []
for i in range(n):
x, y = map(int, input().split())
a.append(Node(x, y))
ans = [0]
v... |
1504_A. Déjà Vu | A palindrome is a string that reads the same backward as forward. For example, the strings "z", "aaa", "aba", and "abccba" are palindromes, but "codeforces" and "ab" are not. You hate palindromes because they give you déjà vu.
There is a string s. You must insert exactly one character 'a' somewhere in s. If it is poss... | ```python
def par(s):
n = len(s)
for i in range(n // 2):
if s[i] != s[n - 1 - i]:
return False
return True
def solve(s):
if not par('a' + s):
return 'YES\n' + 'a' + s
if not par(s + 'a'):
return 'YES\n' + s + 'a'
return 'NO'
t = int(input())
while t > 0:
s = input()
print(solve(s))
... |
159_D. Palindrome pairs | You are given a non-empty string s consisting of lowercase letters. Find the number of pairs of non-overlapping palindromic substrings of this string.
In a more formal way, you have to find the quantity of tuples (a, b, x, y) such that 1 ≤ a ≤ b < x ≤ y ≤ |s| and substrings s[a... b], s[x... y] are palindromes.
A pal... | ```python
import sys
input=sys.stdin.readline
s=list(input().rstrip())
n=len(s)
l=[0]*n # [0,i]
r=[0]*n # [i,n-1]
for i in range(n):
j=0
while 0<=i-j and i+j<n and s[i-j]==s[i+j]:
l[i+j]+=1
r[i-j]+=1
j+=1
j=1
while 0<=i-j+1 and i+j<n and s[i-j+1]==s[i+j]:
l[i+j]+=1
r[i-j+1]+=1
j+=1
ans=0... |
201_B. Guess That Car! | A widely known among some people Belarusian sport programmer Yura possesses lots of information about cars. That is why he has been invited to participate in a game show called "Guess That Car!".
The game show takes place on a giant parking lot, which is 4n meters long from north to south and 4m meters wide from west ... | ```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('outpu... |
226_A. Flying Saucer Segments | An expedition group flew from planet ACM-1 to Earth in order to study the bipedal species (its representatives don't even have antennas on their heads!).
The flying saucer, on which the brave pioneers set off, consists of three sections. These sections are connected by a chain: the 1-st section is adjacent only to the... | ```python
n, m = map(int, input().split())
def fast_power(base, exp):
res = 1
while exp > 0:
if exp % 2 == 1:
res = (res * base) % m
base = (base * base) % m
exp //= 2
return res
print((fast_power(3, n) - 1 + m) % m)
``` |
24_D. Broken robot | You received as a gift a very clever robot walking on a rectangular board. Unfortunately, you understood that it is broken and behaves rather strangely (randomly). The board consists of N rows and M columns of cells. The robot is initially at some cell on the i-th row and the j-th column. Then at every step the robot c... | ```python
n,m = (int(s) for s in input().split())
i,j = (int(s) for s in input().split())
def find(n,m,i,j):
if i==n:
return 0
if m==1:
return 2*(n-i)
e,a,b = [0.]*m,[0]*m,[0]*m
for l in range(n-1,0,-1):
a[0],b[0]=.5,.5*(3+e[0])
for k in range(1,m-1):
a[k] = 1... |
298_B. Sail | The polar bears are going fishing. They plan to sail from (sx, sy) to (ex, ey). However, the boat can only sail by wind. At each second, the wind blows in one of these directions: east, south, west or north. Assume the boat is currently at (x, y).
* If the wind blows to the east, the boat will move to (x + 1, y).
... | ```python
i = 0
t, sx, sy, ex, ey = list(map(int, input().split()))
second_string = input()
while i < t:
if second_string[i] == 'E':
if sx < ex: sx += 1
elif second_string[i] == 'W':
if sx > ex: sx -= 1
elif second_string[i] == 'N':
if sy < ey: sy += 1
else:
if sy > ey: s... |
369_B. Valera and Contest | Valera loves to participate in competitions. Especially in programming contests. Today he has participated in the contest with his team, consisting of n students (including Valera). This contest was an individual competition, so each student in the team solved problems individually.
After the contest was over, Valera ... | ```python
import math
scann=input()
numbers=scann.split()
s=int(numbers[0])
s2=int(numbers[1])
min1=int(numbers[2])
max1=int(numbers[3])
total=int(numbers[4])
s2mp=int(numbers[5])
div=int(s2mp/s2)
mod=s2mp%s2
students=[]
for i in range(mod):
students.append(div +1) #intentarlo solo con piso
iter1=s2-mod
for j in r... |
391_C1. The Tournament | This problem consists of three subproblems: for solving subproblem C1 you will receive 4 points, for solving subproblem C2 you will receive 4 points, and for solving subproblem C3 you will receive 8 points.
Manao decided to pursue a fighter's career. He decided to begin with an ongoing tournament. Before Manao joined,... | ```python
m = 301000
ns = [0] * m
es = [0] * m
c = [0] * m
b = [0] * m
t = [0] * m
P = 0
def add(b, k):
k = t[k]
while k:
e = es[k]
if b[-1] > e: b[-1] = e
b[e] += 1
k = ns[k]
def delete(b):
for i in range(b[m - 1], m + 1):
if b[i]:
b[i] -= 1
b[-... |
413_B. Spyke Chatting | The R2 company has n employees working for it. The work involves constant exchange of ideas, sharing the stories of success and upcoming challenging. For that, R2 uses a famous instant messaging program Spyke.
R2 has m Spyke chats just to discuss all sorts of issues. In each chat, some group of employees exchanges mes... | ```python
n,m,k=map(int,input().split())
p=[]
for i in range(n):
o=[int(w) for w in input().split()]
p.append(o)
t=[0]*n
r=[0]*m
for i in range(k):
a,b=map(int,input().split())
t[a-1]+=1
r[b-1]+=1
for i in range(n):
ans=0
for j in range(m):
if p[i][j]==1:
ans+=r[j]
... |
43_D. Journey | The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited ever... | ```python
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m = map(int, input().split())
ans = ['1 1']
warp = [-1] * 4
if n == 1 and m == 2:
ans.append('1 2')
elif n == 2 and m == 1:
ans.append('2 1')
elif n == 1:
warp = [1, m, 1, 1... |
462_A. Appleman and Easy Task | Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th... | ```python
n=int(input())
mat = []
mat.append('x'*(n+2))
for i in range(n):
mat.append('x'+input()+'x')
mat.append('x'*(n+2))
output = "YES"
for i in range(1,n+1):
if output == "NO":
break
for j in range(1,n+1):
s=0
if mat[i][j+1] == 'o':
s+=1
if mat[i][j-1] == 'o'... |
509_E. Pretty Song | When Sasha was studying in the seventh grade, he started listening to music a lot. In order to evaluate which songs he likes more, he introduced the notion of the song's prettiness. The title of the song is a word consisting of uppercase Latin letters. The prettiness of the song is the prettiness of its title.
Let's d... | ```python
song = input()
le = len(song)
su = 0
for x in range(1,le+1):
su += 1/x
l = [0]*le
l[0] = su
diff = su
for x in range(1,int((le+1)/2)):
diff -= (1/x + 1/(le+1-x))
l[x] = l[x-1] + diff
for x in range(int((le+1)/2),le):
l[x] = l[le-1-x]
ans = 0
for x in range(le):
let = song[x]
if let i... |
534_A. Exam | An exam for n students will take place in a long and narrow room, so the students will sit in a line in some order. The teacher suspects that students with adjacent numbers (i and i + 1) always studied side by side and became friends and if they take an exam sitting next to each other, they will help each other for sur... | ```python
n = int(input())
if n ==1:
print(1)
print(1)
else:
odd = [int(k) for k in range(n+1) if k % 2 != 0]
odd.reverse()
even = [int(k) for k in range(1,n+1) if k % 2 == 0]
even.reverse()
odd_len = len(odd)
#even.reverse()
if abs(odd[odd_len-1]-even[0]) == 1:
even = even[... |
559_A. Gerald's Hexagon | Gerald got a very curious hexagon for his birthday. The boy found out that all the angles of the hexagon are equal to <image>. Then he measured the length of its sides, and found that each of them is equal to an integer number of centimeters. There the properties of the hexagon ended and Gerald decided to draw on it.
... | ```python
import math
a = [int(x) for x in input().split()]
nb_triangles = 0
nb_triangles += a[0]*a[1]*2
nb_triangles += a[2]*a[3]*2
nb_triangles += a[4]*a[5]*2
nb_triangles += abs(a[0]-a[3])**2
print(nb_triangles)
``` |
584_D. Dima and Lisa | Dima loves representing an odd number as the sum of multiple primes, and Lisa loves it when there are at most three primes. Help them to represent the given number as the sum of at most than three primes.
More formally, you are given an odd numer n. Find a set of numbers pi (1 ≤ i ≤ k), such that
1. 1 ≤ k ≤ 3
2. ... | ```python
def isPrime(n):
if n==2:
return True
if n%2==0:
return False
for i in range(3,n,2):
if i*i>n:
break
if n%i==0:
return False
return True
n=int(input())
if isPrime(n):
print(1)
print(n)
elif isPrime(n-2):
print(2)
print('2 '... |
606_D. Lazy Student | Student Vladislav came to his programming exam completely unprepared as usual. He got a question about some strange algorithm on a graph — something that will definitely never be useful in real life. He asked a girl sitting next to him to lend him some cheat papers for this questions and found there the following defin... | ```python
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from heapq import *
def main():
n,m=map(int,input().split())
a=[list(map(int,input().split())) for _ in range(m)]
edges,j,b=[[]]*m,1,sorted(range(m),key=lambda x:a[x][0]*10000000000-a... |
628_D. Magic Numbers | Consider the decimal presentation of an integer. Let's call a number d-magic if digit d appears in decimal presentation of the number on even positions and nowhere else.
For example, the numbers 1727374, 17, 1 are 7-magic but 77, 7, 123, 34, 71 are not 7-magic. On the other hand the number 7 is 0-magic, 123 is 2-magic... | ```python
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
from array import array
def solve(x,m,d,mod,par):
dp = [[array('i',[0])*m for _ in range(2)] for _ in range(len(x))]
# remainder of number formed till now ; smaller/equal ; place value
zz = i... |
678_C. Joty and Chocolate | Little Joty has got a task to do. She has a line of n tiles indexed from 1 to n. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by a and an unpainted tile should be painted Blue if it's index is divisible by b. So the tile with the number divisible by a a... | ```python
import math
n, red, blue, red_cost, blue_cost = map(int, input().split())
reds = n//red - n//((red*blue)//math.gcd(red,blue))
blues = n//blue - n//((red*blue)//math.gcd(red,blue))
ans = reds*red_cost + blues*blue_cost + max(blue_cost, red_cost)*(n//((red*blue)//math.gcd(red,blue)))
print(int(ans))
``` |
791_D. Bear and Tree Jumps | A tree is an undirected connected graph without cycles. The distance between two vertices is the number of edges in a simple path between them.
Limak is a little polar bear. He lives in a tree that consists of n vertices, numbered 1 through n.
Limak recently learned how to jump. He can jump from a vertex to any verte... | ```python
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlin... |
812_A. Sagheer and Crossroads | Sagheer is walking in the street when he comes to an intersection of two roads. Each road can be represented as two parts where each part has 3 lanes getting into the intersection (one for each direction) and 3 lanes getting out of the intersection, so we have 4 parts in total. Each part has 4 lights, one for each lane... | ```python
arr = [list() for i in range(4)]
arrp = []
for i in range(4):
l, s, r, p = [int(i) for i in input().split()]
arr[i].extend([l, s, r])
arr[[3, i - 1][i > 0]].append(l)
arr[[0, i + 1][i < 3]].append(r)
arr[(i + 2) % 4].append(s)
arrp.append(p)
for i in range(4):
if arrp[i]:
i... |
838_A. Binary Blocks | You are given an image, that can be represented with a 2-d n by m grid of pixels. Each pixel of the image is either on or off, denoted by the characters "0" or "1", respectively. You would like to compress this image. You want to choose an integer k > 1 and split the image into k by k blocks. If n and m are not divisib... | ```python
from sys import stdin as fin
def check(x, y):
if x < 0 or y < 0:
return 0
else:
return table2[x][y]
n, m = [int(x) for x in fin.readline().split()]
table = fin.readlines()
fin.close()
table2 = [[None]*m for _ in range(n)]
table2[0][0] = int(table[0][0])
for __ in range(1, m):
t... |
858_D. Polycarp's phone book | There are n phone numbers in Polycarp's contacts on his phone. Each number is a 9-digit integer, starting with a digit different from 0. All the numbers are distinct.
There is the latest version of Berdroid OS installed on Polycarp's phone. If some number is entered, is shows up all the numbers in the contacts for whi... | ```python
n = int(input())
a = []
d = {}
for b in range(n):
s = input()
g = set()
for i in range(len(s)):
for k in range(i, len(s)):
w = s[i:k + 1]
if w in g:
continue
else:
g.add(w)
if w in d:
d[w] += 1
... |
928_B. Chat | There are times you recall a good old friend and everything you've come through together. Luckily there are social networks — they store all your message history making it easy to know what you argued over 10 years ago.
More formal, your message history is a sequence of messages ordered by time sent numbered from 1 to... | ```python
def count_unic_mess(crt, display, array, n, result_arr):
low_bound = 0 if crt - display < 0 else crt - display
high_bound = n if crt + display + 1 > n else crt + display + 1
result = high_bound - low_bound
if array[crt] == 0:
result_arr.append(result)
return result
ref ... |
957_D. Riverside Curio | Arkady decides to observe a river for n consecutive days. The river's water level on each day is equal to some real value.
Arkady goes to the riverside each day and makes a mark on the side of the channel at the height of the water level, but if it coincides with a mark made before, no new mark is created. The water d... | ```python
import sys
n = int(input())
a = [int(x) for x in input().split(' ')]
maxm = 0
idx=0
ans=0
b=[0]*n
for i in range(n):
if a[i]>=maxm:
maxm=a[i]
idx=i
for i in range(idx,n):
b[i]=maxm+1
i=idx-1
while i>=0:
b[i]=max(a[i]+1,b[i+1]-1)
i-=1
for i in range(1,n):
if b[i]<b[i-1]:
... |
982_D. Shark | For long time scientists study the behavior of sharks. Sharks, as many other species, alternate short movements in a certain location and long movements between locations.
Max is a young biologist. For n days he watched a specific shark, and now he knows the distance the shark traveled in each of the days. All the dis... | ```python
BigNum = 10 ** 10
n = int(input())
aa = [BigNum] + list(map(int, input().split(' '))) + [BigNum]
appear = sorted([(v, i) for i, v in enumerate(aa)])
ans = -1
maxLocations = 0
intervals = [(i, i) for i in range(len(aa))]
lengths = {}
def incCount(val):
global lengths
lengths[val] = lengths.get(val,... |
p02561 AtCoder Library Practice Contest - Maxflow | You are given a grid of N rows and M columns. The square at the i-th row and j-th column will be denoted as (i,j). Some of the squares contain an object. All the remaining squares are empty. The state of the grid is represented by strings S_1,S_2,\cdots,S_N. The square (i,j) contains an object if S_{i,j}= `#` and is em... | ```python
N,M = map(int,input().split())
S = [input() for i in range(N)]
P = N*M+2
src, dst = N*M, N*M+1
es = [[] for i in range(P)] # [[to1,cap1,rev1], ...]
pos = []
def add_edge(fr,to,cap):
pos.append((fr, len(es[fr])))
es[fr].append([to,cap,len(es[to])])
es[to].append([fr,0,len(es[fr])-1])
for i,row i... |
p02692 AtCoder Beginner Contest 166 - Three Variables Game | There is a game that involves three variables, denoted A, B, and C.
As the game progresses, there will be N events where you are asked to make a choice. Each of these choices is represented by a string s_i. If s_i is `AB`, you must add 1 to A or B then subtract 1 from the other; if s_i is `AC`, you must add 1 to A or ... | ```python
#from collections import deque,defaultdict
printn = lambda x: print(x,end='')
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
ins = lambda : input().strip()
DBG = True # and False
BIG = 10**18
R = 10**9 + 7
def ddprint(x):
if DBG:
... |
p02821 AtCoder Beginner Contest 149 - Handshake | Takahashi has come to a party as a special guest. There are N ordinary guests at the party. The i-th ordinary guest has a power of A_i.
Takahashi has decided to perform M handshakes to increase the happiness of the party (let the current happiness be 0). A handshake will be performed as follows:
* Takahashi chooses o... | ```python
from bisect import bisect_left, bisect_right
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
# print(a)
a_cs = [0] * (n + 1)
for i in range(n):
a_cs[i + 1] = a_cs[i] + a[n - 1 - i]
def check(x):
# M回の握手の幸福度の最小値をx以上にできるか
# つまり、M回の任意の握手の幸福度をx以上にできるか
cnt = 0
f... |
p02957 AtCoder Beginner Contest 135 - Harmony | We have two distinct integers A and B.
Print the integer K such that |A - K| = |B - K|.
If such an integer does not exist, print `IMPOSSIBLE` instead.
Constraints
* All values in input are integers.
* 0 \leq A,\ B \leq 10^9
* A and B are distinct.
Input
Input is given from Standard Input in the following format:
... | ```python
a,b = map(int,input().split())
ans = [(a+b)//2,"IMPOSSIBLE"]
print(ans[(a+b)%2])
``` |
p03093 AtCoder Grand Contest 032 - Modulo Pairing | Let M be a positive integer.
You are given 2 N integers a_1, a_2, \ldots, a_{2 N}, where 0 \leq a_i < M for each i.
Consider dividing the 2 N integers into N pairs. Here, each integer must belong to exactly one pair.
We define the ugliness of a pair (x, y) as (x + y) \mod M. Let Z be the largest ugliness of the N pa... | ```python
def modulo_pairing(N: int, M: int, A: list)->int:
A.sort()
def check(n: int)->bool:
'''2*n の位置を区切りとして、右側が全て赤のペアになることを確認する。
'''
for i in range(2*n, N+n):
if A[i] + A[2*N+2*n-i-1] < M:
return False
return True
l, r = -1, N+1
while r -... |
p03239 AtCoder Beginner Contest 112 - Time Limit Exceeded | When Mr. X is away from home, he has decided to use his smartwatch to search the best route to go back home, to participate in ABC.
You, the smartwatch, has found N routes to his home.
If Mr. X uses the i-th of these routes, he will get home in time t_i at cost c_i.
Find the smallest cost of a route that takes not l... | ```python
N,T=map(int,input().split())
ans=10**10
for i in range(N):
c,t=map(int,input().split())
if t<=T:
ans=min(ans,c)
if ans==10**10:
print('TLE')
else:
print(ans)
``` |
p03392 AtCoder Regular Contest 094 - Normalization | You are given a string S consisting of `a`,`b` and `c`. Find the number of strings that can be possibly obtained by repeatedly performing the following operation zero or more times, modulo 998244353:
* Choose an integer i such that 1\leq i\leq |S|-1 and the i-th and (i+1)-th characters in S are different. Replace each... | ```python
from collections import Counter
import sys
sys.setrecursionlimit(10**6)
MOD = 998244353
ABC = "abc".index
*S, = map(ABC, input())
N = len(S)
def bruteforce(S):
used = set()
def dfs(s):
key = tuple(s)
if key in used:
return
used.add(key)
for i in range(len... |
p03555 AtCoder Beginner Contest 077 - Rotation | You are given a grid with 2 rows and 3 columns of squares. The color of the square at the i-th row and j-th column is represented by the character C_{ij}.
Write a program that prints `YES` if this grid remains the same when rotated 180 degrees, and prints `NO` otherwise.
Constraints
* C_{i,j}(1 \leq i \leq 2, 1 \leq... | ```python
e=input()
f=input()
if e[::-1]==f:
print('YES')
else:
print('NO')
``` |
p03710 AtCoder Grand Contest 015 - Kenus the Ancient Greek | Kenus, the organizer of International Euclidean Olympiad, is seeking a pair of two integers that requires many steps to find its greatest common divisor using the Euclidean algorithm.
You are given Q queries. The i-th query is represented as a pair of two integers X_i and Y_i, and asks you the following: among all pai... | ```python
from math import gcd
import random,time
def gcdcount(n,m):
x,y=min(n,m),max(n,m)
if x==0:
return 0
else:
return 1+gcdcount(x,y%x)
fibo=[0,1,2]
for i in range(100):
fibo.append(fibo[-1]+fibo[-2])
gcdfibo=[[],[(1,2),(1,3)]]
for i in range(2,101):
temp=[]
for a,b in gc... |
p03866 AtCoder Regular Contest 064 - Cosmic Rays | On the xy-plane, Snuke is going to travel from the point (x_s, y_s) to the point (x_t, y_t). He can move in arbitrary directions with speed 1. Here, we will consider him as a point without size.
There are N circular barriers deployed on the plane. The center and the radius of the i-th barrier are (x_i, y_i) and r_i, r... | ```python
Xs,Ys,Xt,Yt = map(int,input().split())
n = int(input())
p = [(Xs,Ys,0),(Xt,Yt,0)]
for i in range(2,n+2):
p.append(tuple(map(int,input().split())))
cost = [[0]*(n+2)for i in range(n+2)]
for i in range(n+2):
for j in range(i,n+2):
cost[i][j] = cost[j][i] = max(((p[i][0]-p[j][0])**2+(p[i][1]-p[... |
p04030 AtCoder Beginner Contest 043 - Unhappy Hacking (ABC Edit) | Sig has built his own keyboard. Designed for ultimate simplicity, this keyboard only has 3 keys on it: the `0` key, the `1` key and the backspace key.
To begin with, he is using a plain text editor with this keyboard. This editor always displays one string (possibly empty). Just after the editor is launched, this stri... | ```python
s = input()
ans = ""
for ss in s:
if ss == "B":
ans = ans[:-1]
else:
ans += ss
print(ans)
``` |
p00114 Electro-Fly | A calculator scholar has discovered a strange life form called an electronic fly that lives in electronic space. While observing the behavior of the electronic flies, the electronic flies at the (x, y, z) point in this space then move to (x', y', z') indicated by the following rules. I found out.
<image>
However, a1... | ```python
def gcd(m, n):
while n:
m, n = n, m % n
return m
def lcm(m, n):
return m // gcd(m, n) * n
def f(a, m):
x = a
cnt = 1
while x != 1:
x = x * a % m
cnt += 1
return cnt
while 1:
a1, m1, a2, m2, a3, m3 = map(int, input().split())
if a1 == 0:
bre... |
p00247 Ice Maze | There is a rectangular maze with square squares lined up vertically and horizontally. In this maze, while moving to the adjacent squares in the north, south, east and west, the starting square S departs and the goal square G is aimed at. There are three types of trout: plain, mountain, and ice. S and G are located in t... | ```python
from collections import deque
while True:
x, y = map(int, input().split())
if x == 0:break
mp = [list("#" * (x + 2))] + [list("#" + input() + "#") for _ in range(y)] + [list("#" * (x + 2))]
ice_cnt = 0
ice_dic = []
vec = ((1, 0), (0, -1), (-1, 0), (0, 1))
def ice_search(... |
p00428 Questionnaire | I have a plan to go on a school trip at a school. I conducted a questionnaire survey for that purpose. Students have student numbers from 1 to n, and the locations of travel candidates are represented by numbers from 1 to m, and where they want to go ○ , Mark the places you don't want to go with a cross and submit.
At... | ```python
def f():
N, M = map(int, input().split())
if N == 0:
return -1
A = [0] * M
for i in range(N):
T = [int(i) for i in map(int, input().split())]
for j in range(M):
if T[j] == 1:
A[j] += 1
B = sorted([(v, i + 1) for i, v in enumerate(A)], ke... |
p00768 ICPC Ranking | ICPC Ranking
Your mission in this problem is to write a program which, given the submission log of an ICPC (International Collegiate Programming Contest), determines team rankings.
The log is a sequence of records of program submission in the order of submission. A record has four fields: elapsed time, team number, p... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1187&lang=jp
"""
import sys
from sys import stdin
input = stdin.readline
class Team(object):
def __init__(self, id):
self.id = id
self.correct = 0 # ??£?§£??°
self.time = 0 # ... |
p00899 City Merger | Recent improvements in information and communication technology have made it possible to provide municipal service to a wider area more quickly and with less costs. Stimulated by this, and probably for saving their not sufficient funds, mayors of many cities started to discuss on mergers of their cities.
There are, of... | ```python
#!usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
import sys
import math
import bisect
import random
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def I(): return int(sys.stdin.readline())
def LS():return [list(x) for x in sys.stdin.readline(... |
p01471 Fractional Knapsack | Problem statement
Real variables $ x_1, x_2, ..., x_N $ satisfy the following conditions.
1. $ 0 \ leq x_i \ leq 1 $ ($ 1 \ leq i \ leq N $)
2. $ w_1x_1 + w_2x_2 + ... + w_Nx_N \ leq W $
At this time, find the maximum value that $ v_1x_1 + v_2x_2 + ... + v_Nx_N $ can take. It is known that such a maximum actually ... | ```python
import heapq
N, W = [int(n) for n in input().split()]
tmpw = 0
tmpv = 0
minheap = []
for i in range(N):
w, v = [int(n) for n in input().split()]
if(w < 0):
tmpw += w
tmpv += v
w *= -1
v *= -1
if(v > 0):
if w == 0:
tmpv += v
else:
... |
p01631 English | Problem Statement
Mr. Takatsuki, who is planning to participate in the Aizu training camp, is enthusiastic about studying and has been studying English recently. She tries to learn as many English words as possible by playing the following games on her mobile phone. The mobile phone she has is a touch panel type that ... | ```python
def main():
n = int(input())
words = []
scores = []
for _ in range(n):
word, score = input().split()
words.append(word)
scores.append(int(score))
mp = ["#" * 6] + ["#" + input() + "#" for _ in range(4)] + ["#" * 6]
t = int(input())
def search(word):
used = [[False] * 6 for _ i... |
p01783 LR | Example
Input
R?????,2?)
Output
29 | ```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 ... |
p02056 Jam | E: Jam
problem
There are N cities in a country, numbered 1, \ 2, \ ..., \ N. These cities are connected in both directions by M roads, and the i-th road allows you to travel between the cities u_i and v_i in time t_i. Also, any two cities can be reached by using several roads.
Bread is sold in each town, and the del... | ```python
import sys
from heapq import heappop as hpp, heappush as hp
def dijkstra(N, s, Edge):
inf = 10**18
dist = [inf] * N
Q = [(0, s)]
decided = set()
for _ in range(N):
while True:
dn, vn = hpp(Q)
if vn not in decided:
decided.add(vn)
... |
p02198 Oranges on Cans | Oranges on Cans
square1001 You put a $ N $ can of aluminum on the table.
E869120 You put $ M $ of oranges on each aluminum can on the table.
How many oranges are on the aluminum can?
input
Input is given from standard input in the following format.
$ N $ $ M $
output
Output the number of oranges on the alumin... | ```python
n, m = [int(i) for i in input().split()]
print(n*m)
``` |
p02352 RMQ and RAQ | Write a program which manipulates a sequence $A$ = {$a_0, a_1, ..., a_{n-1}$} with the following operations:
* $add(s, t, x)$ : add $x$ to $a_s, a_{s+1}, ..., a_t$.
* $find(s, t)$ : report the minimum value in $a_s, a_{s+1}, ..., a_t$.
Note that the initial values of $a_i ( i = 0, 1, ..., n-1 )$ are 0.
Constraints... | ```python
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians, log2
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase,... |
1033_A. King Escape | Alice and Bob are playing chess on a huge chessboard with dimensions n × n. Alice has a single piece left — a queen, located at (a_x, a_y), while Bob has only the king standing at (b_x, b_y). Alice thinks that as her queen is dominating the chessboard, victory is hers.
But Bob has made a devious plan to seize the vic... | ```python
n = int(input())
bx, by = map(int, input().split())
ax, ay = map(int, input().split())
cx, cy = map(int, input().split())
ans = "NO"
if(ax<bx and cx<bx):
if(ay<by and cy<by):
ans = "YES"
elif(ay>by and cy>by):
ans = "YES"
elif(ax>bx and cx>bx):
if(ay<by and cy<by):
ans = "Y... |
1077_F2. Pictures with Kittens (hard version) | The only difference between easy and hard versions is the constraints.
Vova likes pictures with kittens. The news feed in the social network he uses can be represented as an array of n consecutive pictures (with kittens, of course). Vova likes all these pictures, but some are more beautiful than the others: the i-th p... | ```python
n, k, x = map(int, input().split())
a = [None] + list(map(int, input().split()))
lo, hi = 0, 10 ** 9 * 5000
q = [None] * (n + 1)
def get(mid):
f, r = 0, 0
q[0] = 0, 0, 0
for i in range(1, n + 1):
if q[r][2] == i - k - 1: r += 1
cur = q[r][0] + a[i] - mid, q[r][1] + 1, i
w... |
1146_D. Frog Jumping | A frog is initially at position 0 on the number line. The frog has two positive integers a and b. From a position k, it can either jump to position k+a or k-b.
Let f(x) be the number of distinct integers the frog can reach if it never jumps on an integer outside the interval [0, x]. The frog doesn't need to visit all ... | ```python
from math import gcd
m,a,b = map(int,input().split())
g = gcd(a,b)
vis = [0]*(a+b+1)
vis[0] = 1
nvis = 1
count = 0
last = 0
t = 0
while True:
#print(t, vis)
if t >= b:
#print('back')
t -= b
if vis[t]:
break
vis[t] = 1
nvis += 1
else:
... |
1167_D. Bicolored RBS | A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular (shortly, RBS) if it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are RBS and ")(" and ... | ```python
# import math
# import sys
n = int(input().strip())
s = input().strip()
a = 0
for i in range(n):
if s[i]=='(':
if a&1:
print(0,end="")
else:
print(1,end="")
a+=1
else:
a-=1
if a&1:
print(0,end="")
else:
print(1,end="")
``` |
1185_G1. Playlist for Polycarp (easy version) | The only difference between easy and hard versions is constraints.
Polycarp loves to listen to music, so he never leaves the player, even on the way home from the university. Polycarp overcomes the distance from the university to the house in exactly T minutes.
In the player, Polycarp stores n songs, each of which is... | ```python
import sys
input = sys.stdin.readline
n,T=map(int,input().split())
S=[list(map(int,input().split())) for i in range(n)]
DP=[[0]*(4) for i in range(T+1)]
mod=10**9+7
from functools import lru_cache
@lru_cache(maxsize=None)
def calc(used,recent,time):
ANS=0
for i in range(n):
#print(i,used)
... |
1204_D2. Kirk and a Binary String (hard version) | The only difference between easy and hard versions is the length of the string. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
Kirk has a binary string s (a string which consists of zeroes and ones) of length n and he is asking you to find a binary str... | ```python
pp = input()
if len(pp) == 1:
print('0')
exit(0)
z = 1 if pp[0]=='0' else 0
zc = [z]
l = 1
lndl = [l]
for p in pp[1:]:
l = max(z + 1, l + (1 if p == '1' else 0))
z += 1 if p == '0' else 0
lndl.append(l)
zc.append(z)
lnda = lndl[-1]
o = 1 if pp[-1]=='1' else 0
oc = [o]
l = 1
lndr = [l]
... |
1221_C. Perfect Team | You may have already known that a standard ICPC team consists of exactly three members. The perfect team however has more restrictions. A student can have some specialization: coder or mathematician. She/he can have no specialization, but can't have both at the same time.
So the team is considered perfect if it includ... | ```python
q = int(input())
for i in range(q):
k = 0
c, m, x = [int(s) for s in input().split()]
if min(c, m, x) != x:
print(min(c, m))
else:
k += x
z = (c + m - 2 * x) // 3
print(k + min(z, c - x, m - x))
``` |
1266_D. Decreasing Debts | There are n people in this world, conveniently numbered 1 through n. They are using burles to buy goods and services. Occasionally, a person might not have enough currency to buy what he wants or needs, so he borrows money from someone else, with the idea that he will repay the loan later with interest. Let d(a,b) deno... | ```python
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
#threading.stack_size... |
1331_B. Limericks | There was once young lass called Mary,
Whose jokes were occasionally scary.
On this April's Fool
Fixed limerick rules
Allowed her to trip the unwary.
Can she fill all the lines
To work at all times?
On juggling the words
Right around two-thirds
Sh... | ```python
n = int(input())
res = ''
while n != 1:
for i in range(2,n+1):
if n % i == 0:
res += str(i)
n //= i
break
print(res)
``` |
1371_B. Magical Calendar | A competitive eater, Alice is scheduling some practices for an eating contest on a magical calendar. The calendar is unusual because a week contains not necessarily 7 days!
In detail, she can choose any integer k which satisfies 1 ≤ k ≤ r, and set k days as the number of days in a week.
Alice is going to paint some n... | ```python
import sys;
import math;
def get_ints(): return map(int, sys.stdin.readline().strip().split())
def get_array(): return list(map(int, sys.stdin.readline().strip().split()))
def get_string(): return sys.stdin.readline().strip()
t = int(input());
for test in range(t):
n,k = get_ints();
ans=0;
if(n<=... |
1418_D. Trash Problem | Vova decided to clean his room. The room can be represented as the coordinate axis OX. There are n piles of trash in the room, coordinate of the i-th pile is the integer p_i. All piles have different coordinates.
Let's define a total cleanup as the following process. The goal of this process is to collect all the pile... | ```python
def get(t, l, r):
l += len(t)//2
r += len(t)//2
res = -1
while l <= r:
if l % 2 == 1:
res = max(res, t[l])
if r % 2 == 0:
res = max(res, t[r])
l = (l + 1) // 2
r = (r - 1) // 2
return res
def change(t, x, v):
x += len(t)//2
t[x] = v
while x > 1:
x //= 2
t[x] = max(t[x*2],t[x*2+1])
... |
1436_C. Binary Search | Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode o... | ```python
f, t = -1, 0
INT = 10 ** 9 + 7
def mult(a, b):
ans = 1
for i in range(b):
ans *= a - i
ans %= INT
return ans
def fact(a):
ans = 1
for i in range(a):
ans *= i + 1
ans %= INT
return ans
L = []
def BinarySearch(num, pos):
global f, t
a = [i for i in range(num)]
left = 0
right = num
while left... |
1461_A. String Generation | One fall day Joe got bored because he couldn't find himself something interesting to do. Marty suggested Joe to generate a string of length n to entertain him somehow. It didn't seem particularly difficult, but Joe's generated string had to follow these rules:
* the string may only contain characters 'a', 'b', or 'c... | ```python
for u in range(int(input())):
n, k = map(int, input().split())
t = n-k
s = ""
for i in range(t):
if(i%3==0):
s += "a"
if(i%3 == 1):
s += "b"
if(i%3 == 2):
s += "c"
if(t%3 == 0):
s += "a"*... |
1486_B. Eastern Exhibition | You and your friends live in n houses. Each house is located on a 2D plane, in a point with integer coordinates. There might be different houses located in the same point. The mayor of the city is asking you for places for the building of the Eastern exhibition. You have to find the number of places (points with intege... | ```python
import os
DEBUG = 'DEBUG' in os.environ
def debug(*args):
if DEBUG:
print(">", *args)
def solution(houses):
if len(houses) == 1:
return 1
housesX = []
housesY = []
for house in houses:
housesX.append(house[0])
housesY.append(house[1])
housesX.sort()
housesY.sort()
leftX =... |
1536_D. Omkar and Medians | Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. O... | ```python
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readl... |
27_D. Ring Road 2 | It is well known that Berland has n cities, which form the Silver ring — cities i and i + 1 (1 ≤ i < n) are connected by a road, as well as the cities n and 1. The goverment have decided to build m new roads. The list of the roads to build was prepared. Each road will connect two cities. Each road should be a curve whi... | ```python
n, m = map(int, input().split())
road = [[] for i in range(m)]
for i in range(m):
road[i] = [i] + list(map(int, input().split())) + ['NONE']
for i in road:
if i[2] < i[1]:
i[1], i[2] = i[2], i[1]
i[1], i[2] = i[1] - 1, i[2] - 1
participation = [[] for i in range(m)]
for i in range(len(roa... |
302_C. Yaroslav and Sequence | Yaroslav has an array, consisting of (2·n - 1) integers. In a single operation Yaroslav can change the sign of exactly n elements in the array. In other words, in one operation Yaroslav can select exactly n array elements, and multiply each of them by -1.
Yaroslav is now wondering: what maximum sum of array elements c... | ```python
n = int(input())
a = list(map(int, input().split()))
c = list(map(abs, a))
if len(list(filter(lambda x: x < 0, a))) & 1 and n + 1 & 1:
print(sum(c) - 2 * min(c))
else:
print(sum(c))
# Made By Mostafa_Khaled
``` |
329_D. The Evil Temple and the Moving Rocks | Important: All possible tests are in the pretest, so you shouldn't hack on this problem. So, if you passed pretests, you will also pass the system test.
You are an adventurer currently journeying inside an evil temple. After defeating a couple of weak monsters, you arrived at a square room consisting of tiles forming ... | ```python
r, c = map(int, input().split())
if r == 3:
print('>vv')
print('^<.')
print('^.<')
print('1 3')
elif r == 5:
print('>...v')
print('v.<..')
print('..^..')
print('>....')
print('..^.<')
print('1 1')
elif r == 100:
for i in range(25):
print('>'*50+'.>'*24+'.v')... |
350_B. Resort | Valera's finally decided to go on holiday! He packed up and headed for a ski resort.
Valera's fancied a ski trip but he soon realized that he could get lost in this new place. Somebody gave him a useful hint: the resort has n objects (we will consider the objects indexed in some way by integers from 1 to n), each obje... | ```python
import sys
def Z(s):
return int(s)-1
n=int(sys.stdin.readline())
Hotels=[False]*(n)
Rep=[0]*(n+1)
Chains=[]
Type=list(map(int,sys.stdin.readline().split()))
for i in range(n):
if(Type[i]==1):
Hotels[i]=True
A=list(map(Z,sys.stdin.readline().split()))
for item in A:
Rep[item]+=1
for i ... |
374_C. Inna and Dima | Inna and Dima bought a table of size n × m in the shop. Each cell of the table contains a single letter: "D", "I", "M", "A".
Inna loves Dima, so she wants to go through his name as many times as possible as she moves through the table. For that, Inna acts as follows:
1. initially, Inna chooses some cell of the tabl... | ```python
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
# from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as ... |
41_A. Translation | The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc.... | ```python
#41A
print("YES" if input()==input()[::-1] else "NO")
``` |
513_G3. Inversions problem | You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
In... | ```python
f = lambda: map(int, input().split())
n, k = f()
p = list(f())
r = range
u = [l * l + l >> 1 for l in r(n + 1)]
v = [(i, j) for i in r(n) for j in r(i + 1, n)]
t = [[p[i] > p[j] for j in r(n)] for i in r(n)]
a = [[0] * n for i in r(n)]
b = [[0] * n for i in r(n)]
c = [[0] * n for i in r(n)]
for l in r(min(... |
540_A. Combination Lock | Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | ```python
n=int(input())
s=input()
s=list(s)
s1=input()
s1=list(s1)
c=0
for i in range(n):
if abs(int(s[i])-int(s1[i]))>5:
c+=10-abs(int(s[i])-int(s1[i]))
else:
c+=abs(int(s[i])-int(s1[i]))
print(c)
``` |
568_B. Symmetric and Transitive | Little Johnny has recently learned about set theory. Now he is studying binary relations. You've probably heard the term "equivalence relation". These relations are very important in many areas of mathematics. For example, the equality of the two numbers is an equivalence relation.
A set ρ of pairs (a, b) of elements ... | ```python
from math import factorial
cat = [1, 1]
p = 10**9 + 7
n = int(input())
ans = 0
fac = [1]
mat = [[0 for i in range(n + 1)] for j in range(n + 1)]
mat[0][0] = 1
for i in range(1, n + 1):
mat[i][0] = mat[i - 1][i - 1]
for j in range(i):
mat[i][j + 1] = (mat[i][j] + mat[i - 1][j]) % p
print(mat... |
611_B. New Year and Old Property | The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak... | ```python
a,b=map(int,input().split())
lis=list()
s=''
for i in range(1,69):
s=s+'1'
for j in range(1,len(s)):
temp=s[:j]+'0'+s[j+1:]
lis.append(int(temp,2))
c=0
for x in lis:
if x>=a and x<=b:
c+=1
print(c)
``` |
630_Q. Pyramids | IT City administration has no rest because of the fame of the Pyramids in Egypt. There is a project of construction of pyramid complex near the city in the place called Emerald Walley. The distinction of the complex is that its pyramids will be not only quadrangular as in Egypt but also triangular and pentagonal. Of co... | ```python
a,a1,a2 = map(int,input().split())
print(a**3 / 6 / 2**.5 + a1**3 * 2**.5 / 6 + a2**3 * (5 + 5 ** .5) / 24)
``` |
65_B. Harry Potter and the History of Magic | The History of Magic is perhaps the most boring subject in the Hogwarts school of Witchcraft and Wizardry. Harry Potter is usually asleep during history lessons, and his magical quill writes the lectures for him. Professor Binns, the history of magic teacher, lectures in such a boring and monotonous voice, that he has ... | ```python
n,a,ans,last=int(input()),[],[],1000
for i in range(n):a.append(input())
for d in a:
minoverd=10000000
for i in range(10):
for j in range(i==0,5):
t=int(d[:j]+str(i)+d[j+1:])
if minoverd>t>=last:minoverd=t
ans.append(str(minoverd))
if minoverd>2011:break
... |
729_B. Spotlights | Theater stage is a rectangular field of size n × m. The director gave you the stage's plan which actors will follow. For each cell it is stated in the plan if there would be an actor in this cell or not.
You are to place a spotlight on the stage in some good position. The spotlight will project light in one of the fou... | ```python
from sys import stdin,stdout
input = stdin.readline
n,m = map(int, input().split())
arr = []
for i in range(n):
arr.append(list(map(int, input().split())))
dp = [[0 for i in range(m)] for j in range(n)]
for i in range(n):
t = 0
for j in range(m):
if arr[i][j] == 0: dp[i][j] += t
e... |
749_C. Voting | There are n employees in Alternative Cake Manufacturing (ACM). They are now voting on some very important question and the leading world media are trying to predict the outcome of the vote.
Each of the employees belongs to one of two fractions: depublicans or remocrats, and these two fractions have opposite opinions o... | ```python
n=int(input())
s=input()
t=[]
d=r=0
for i in s:
t.append(i)
while len(t)!=1:
for i in range(len(t)):
if t[i]=="R" and d==0:
r+=1
elif t[i]=="D" and r==0:
d+=1
elif t[i]=="R" and d!=0:
d-=1
t[i]=0
else:
r-=1
... |
772_B. Volatile Kite | You are given a convex polygon P with n distinct vertices p1, p2, ..., pn. Vertex pi has coordinates (xi, yi) in the 2D plane. These vertices are listed in clockwise order.
You can choose a real number D and move each vertex of the polygon a distance of at most D from their original positions.
Find the maximum value ... | ```python
#!/usr/bin/env python3
from decimal import Decimal
def dist(a, b):
x1, y1 = a
x2, y2 = b
return Decimal((x1-x2)**2+(y1-y2)**2).sqrt()
def minh(a, b, c):
m = dist(a, b)
n = dist(b, c)
k = dist(a, c)
p = Decimal(m + n + k)/2
sqp = (p*(p-m)*(p-n)*(p-k)).sqrt()
hm = (Decim... |
797_B. Odd sum | You are given sequence a1, a2, ..., an of integer numbers of length n. Your task is to find such subsequence that its sum is odd and maximum among all such subsequences. It's guaranteed that given sequence contains subsequence with odd sum.
Subsequence is a sequence that can be derived from another sequence by deletin... | ```python
n=int(input())
o1=[]
o2=[]
e1=[]
e2=[]
l=list(map(int,input().split()))
for i in range(n):
if l[i]%2==0:
if l[i]<0:
e1.append(l[i])
elif l[i]>0:
e2.append(l[i])
else:
if l[i]>0:
o2.append(l[i])
elif l[i]<0:
o1.append(l[i])... |
817_D. Imbalanced Array | You are given an array a consisting of n elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of arra... | ```python
#####################################
import atexit, io, sys, collections, math, heapq, fractions,copy, os
from io import BytesIO, IOBase
##################################### python 3 START
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.f... |
842_D. Vitya and Strange Lesson | Today at the lesson Vitya learned a very interesting function — mex. Mex of a sequence of numbers is the minimum non-negative number that is not present in the sequence as element. For example, mex([4, 33, 0, 1, 1, 5]) = 2 and mex([1, 2, 3]) = 0.
Vitya quickly understood all tasks of the teacher, but can you do the sa... | ```python
# ------------------- fast io --------------------
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... |
863_D. Yet Another Array Queries Problem | You are given an array a of size n, and q queries to it. There are queries of two types:
* 1 li ri — perform a cyclic shift of the segment [li, ri] to the right. That is, for every x such that li ≤ x < ri new value of ax + 1 becomes equal to old value of ax, and new value of ali becomes equal to old value of ari;
... | ```python
import sys
import math
from collections import defaultdict,deque
def get(ind ,arr):
n = len(arr)
for i in range(n):
t,l,r = arr[i]
if t == 1:
if l <= ind <= r:
if ind == l:
ind = r
else:
ind -= 1
continue
if t == 2:
if l <=ind <= r:
ind = (r - ind + l)
continue
retur... |
889_A. Petya and Catacombs | A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages ... | ```python
n = int(input())
notes = [int(x) for x in input().split()]
greatest_cave = 1
visits = {0: 1}
for time, curr in enumerate(notes, start=1):
if curr in visits and visits[curr] != -1:
visits[time] = visits[curr]
visits[curr] = -1
else:
greatest_cave += 1
visits[time] = grea... |
911_F. Tree Destruction | You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps:
1. choose two leaves;
2. add the length of the simple path between them to the answer;
3. remove one of the chosen leaves from the tree.
Initial an... | ```python
import sys
def main():
n = int(input())
edges = list(map(int, sys.stdin.read().split()))
tree_edges = dict()
for i in range(n):
tree_edges[i + 1] = set()
for i in range(0, len(edges) - 1, 2):
tree_edges[edges[i]].add(edges[i + 1])
tree_edges[edges[i + 1]].add(ed... |
960_A. Check the string | A has a string consisting of some number of lowercase English letters 'a'. He gives it to his friend B who appends some number of letters 'b' to the end of this string. Since both A and B like the characters 'a' and 'b', they have made sure that at this point, at least one 'a' and one 'b' exist in the string.
B now gi... | ```python
s = input()+"d"
d = []
r,l = 0,0
e = set()
while r!=len(s):
if s[r]!=s[l]:
d.append(s[l:r])
l=r
r+=1
if d[-1][0]!="c" or d[0][0]!="a" or d[1][0]!="b" or len(d)!=3:
print("NO")
elif len(d[-1])!=len(d[0]) and len(d[-1])!=len(d[1]):
print("NO")
else:
print("YES")
``` |
p02721 AtCoder Beginner Contest 161 - Yutori | Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.
You are given an integer C and a string S. Takahashi will choose his workdays as follows:
* After working for a day, he will refrain from working on the subsequent C days.
* If the i-th character of S is `x`, he will not wor... | ```python
n,k,c=map(int, input().split())
s = input()
leftmost = []
cursor = 0
for _ in range(k):
while s[cursor] == 'x':
cursor += 1
leftmost.append(cursor)
cursor += c+1
rightmost = []
cursor = n-1
for _ in range(k):
while s[cursor] == 'x':
cursor -= 1
rightmost.append(cursor)
... |
p02851 AtCoder Beginner Contest 146 - Rem of Sum is Num | Given are a sequence of N positive integers A_1, A_2, \ldots, A_N, and a positive integer K.
Find the number of non-empty contiguous subsequences in A such that the remainder when dividing the sum of its elements by K is equal to the number of its elements. We consider two subsequences different if they are taken from... | ```python
from collections import defaultdict
def gets():
return list(map(int, input().split()))
N, K = gets()
A = gets()
S = [0] * (N + 1)
for i in range(N):
S[i + 1] = (S[i] + A[i] - 1) % K
cnt = defaultdict(int)
ans = 0
cnt[0] += 1
for i in range(1, N+1):
if i - K >= 0:
cnt[S[i - K]] -= 1
ans += cnt[... |
p02988 AtCoder Beginner Contest 132 - Ordinary Number | We have a permutation p = {p_1,\ p_2,\ ...,\ p_n} of {1,\ 2,\ ...,\ n}.
Print the number of elements p_i (1 < i < n) that satisfy the following condition:
* p_i is the second smallest number among the three numbers p_{i - 1}, p_i, and p_{i + 1}.
Constraints
* All values in input are integers.
* 3 \leq n \leq 20
* p... | ```python
N = int(input())
p = list(map(int,input().split()))
s = 0
for i in range(1,N-1):
s += p[i-1] < p[i] < p[i+1] or p[i-1] > p[i] > p[i+1]
print(s)
``` |
p03129 Yahoo Programming Contest 2019 - Anti-Adjacency | Determine if we can choose K different integers between 1 and N (inclusive) so that no two of them differ by 1.
Constraints
* 1\leq N,K\leq 100
* N and K are integers.
Input
Input is given from Standard Input in the following format:
N K
Output
If we can choose K integers as above, print `YES`; otherwise, prin... | ```python
N, K = list(map(int, input().split(" ")))
print("YES") if 2*K-1 <= N else print("NO")
``` |
p03272 AtCoder Beginner Contest 107 - Train | There is an N-car train.
You are given an integer i. Find the value of j such that the following statement is true: "the i-th car from the front of the train is the j-th car from the back."
Constraints
* 1 \leq N \leq 100
* 1 \leq i \leq N
Input
Input is given from Standard Input in the following format:
N i
O... | ```python
n,i = map(int,input().split())
ans = n+1-i
print(ans)
``` |
p03429 AtCoder Grand Contest 021 - Tiling | Takahashi has an N \times M grid, with N horizontal rows and M vertical columns. Determine if we can place A 1 \times 2 tiles (1 vertical, 2 horizontal) and B 2 \times 1 tiles (2 vertical, 1 horizontal) satisfying the following conditions, and construct one arrangement of the tiles if it is possible:
* All the tiles m... | ```python
N,M,A,B=map(int,input().split())
def solve(n,m,a,b):
#そもそも絶対的にスペースが足りない場合
if a*2+b*2>n*m:
return False
else:
ans=[['.' for x in range(m)] for y in range(n)]
#各タイルの残りをカウント
remainA=a
remainB=b
#原点を起点として2枚を正方形にして敷き詰めていく
nx=0
ny=0
#縦横の限界値をカウント
gx=n
gy=m
#縦が奇数ならばnxを+1して、最初の行にAを... |
p03587 Tenka1 Programmer Beginner Contest - Accepted...? | Snuke prepared 6 problems for a upcoming programming contest. For each of those problems, Rng judged whether it can be used in the contest or not.
You are given a string S of length 6. If the i-th character of s is `1`, it means that the i-th problem prepared by Snuke is accepted to be used; `0` means that the problem... | ```python
def solution():
return sum([int(x) for x in list(input())])
print(solution())
``` |
p03745 AtCoder Grand Contest 013 - Sorted Arrays | You are given an array A of length N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into?
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq 10^9
* Each A_i ... | ```python
N = int(input())
A = list(map(int, input().split()))
sgn = 0
answer = 1
for i in range(N-1):
cur = A[i+1] - A[i]
if cur * sgn < 0:
answer += 1
sgn = 0
continue
if cur != 0:
sgn = cur
print(answer)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.