name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
581_C. Developing Skills | Petya loves computer games. Finally a game that he's been waiting for so long came out!
The main character of this game has n different skills, each of which is characterized by an integer ai from 0 to 100. The higher the number ai is, the higher is the i-th skill of the character. The total rating of the character is... | ```python
n,k=map(int,input().split())
l=list(map(int,input().split()))
rem=[]
ans=0
for i in l:
rem.append(i%10)
ans=ans+i//10
#print(ans)
rem.sort() # 0 1 2 3.. 9 9 9..
i=n-1
while(i>=0 and k>0):
if(rem[i]!=0): #starting from back 9 -> 8 .... -> 2 -> 1->0
sm=10-(rem[i])
... |
603_B. Moodular Arithmetic | As behooves any intelligent schoolboy, Kevin Sun is studying psycowlogy, cowculus, and cryptcowgraphy at the Bovinia State University (BGU) under Farmer Ivan. During his Mathematics of Olympiads (MoO) class, Kevin was confronted with a weird functional equation and needs your help. For two fixed integers k and p, where... | ```python
__author__ = 'MoonBall'
import sys
# sys.stdin = open('data/D.in', 'r')
T = 1
M = 1000000007
def pow(x, y, m):
if y == 0:
return 1
if (y & 1):
return pow(x, y - 1, m) * x % m
else:
t = pow(x, y >> 1, m)
return t * t % m
def process():
P, K = list(map(int, inp... |
675_A. Infinite Sequence | Vasya likes everything infinite. Now he is studying the properties of a sequence s, such that its first element is equal to a (s1 = a), and the difference between any two neighbouring elements is equal to c (si - si - 1 = c). In particular, Vasya wonders if his favourite integer b appears in this sequence, that is, the... | ```python
a, b, c = map(int, input().split())
if b == a:
print('YES')
elif not c:
print('NO')
elif (a < b) and c < 0:
print('NO')
elif (a > b) and c > 0:
print('NO')
else:
print('NO' if ((b-a) % c) else 'YES')
``` |
699_B. One Bomb | You are given a description of a depot. It is a rectangular checkered field of n × m size. Each cell in a field can be empty (".") or it can be occupied by a wall ("*").
You have one bomb. If you lay the bomb at the cell (x, y), then after triggering it will wipe out all walls in the row x and all walls in the column... | ```python
def bombs(array, rows, cols, walls, wallsInRows, wallsInCols):
if walls == 0:
print("YES")
print(1, 1)
return
for i in range(0, rows):
for j in range(0, cols):
s = wallsInRows[i] + wallsInCols[j]
if (array[i][j] == '*' and s - 1 == walls) or (arr... |
71_D. Solitaire | Vasya has a pack of 54 cards (52 standard cards and 2 distinct jokers). That is all he has at the moment. Not to die from boredom, Vasya plays Solitaire with them.
Vasya lays out nm cards as a rectangle n × m. If there are jokers among them, then Vasya should change them with some of the rest of 54 - nm cards (which a... | ```python
ranks = '23456789TJQKA'
suits = 'CDHS'
n, m = [int(i) for i in input().split()]
b = [input().split() for _ in range(n)]
p = [r + s for r in ranks for s in suits]
j1, j2 = False, False
for r in b:
for c in r:
if c == 'J1':
j1 = True
elif c == 'J2':
j2 = True
... |
741_A. Arpa's loud Owf and Mehrdad's evil plan | As you have noticed, there are lovely girls in Arpa’s land.
People in Arpa's land are numbered from 1 to n. Everyone has exactly one crush, i-th person's crush is person with the number crushi.
<image>
Someday Arpa shouted Owf loudly from the top of the palace and a funny game started in Arpa's land. The rules are a... | ```python
def gcd(a,b):
if b==0:
return a
return gcd(b, a%b)
def lcm(a,b):
return a*b/gcd(a,b)
def dfs(sad, num, posjeceno):
"""if sad==a[sad]-1 and posjeceno!=[0]*n:
return (-10, [])"""
posjeceno[sad]=1
if posjeceno[a[sad]-1]==1:
return (num+1, posjeceno)
return dfs(... |
764_E. Timofey and remoduling | Little Timofey likes integers a lot. Unfortunately, he is very young and can't work with very big integers, so he does all the operations modulo his favorite prime m. Also, Timofey likes to look for arithmetical progressions everywhere.
One of his birthday presents was a sequence of distinct integers a1, a2, ..., an. ... | ```python
from functools import reduce
def gcd_extended(bigger, less):
if less == 0:
return(bigger, 1, 0)
mod = bigger % less
div = bigger // less
gcd, c_less, c_mod = gcd_extended(less, mod)
#gcd == c_less * less + c_mod * mod
#mod == bigger - div * less
#gcd = (c_less - c_mod * di... |
834_B. The Festive Evening | <image>
It's the end of July – the time when a festive evening is held at Jelly Castle! Guests from all over the kingdom gather here to discuss new trends in the world of confectionery. Yet some of the things discussed here are not supposed to be disclosed to the general public: the information can cause discord in th... | ```python
import sys
n, k = map(int, input().split())
a = list(input())
st = [0] * 26
ed = [0] * 26
for i in range(n):
if st[ord(a[i])-65] == 0:
st[ord(a[i])-65] = i + 1
else:
ed[ord(a[i])-65] = i + 1
for i in range(26):
if st[i] != 0 and ed[i] == 0:
ed[i] = st[i]
n = 52
i = 0
j = 0
maxi = -1 * sys.maxsize
l =... |
879_C. Short Program | Petya learned a new programming language CALPAS. A program in this language always takes one non-negative integer and returns one non-negative integer as well.
In the language, there are only three commands: apply a bitwise operation AND, OR or XOR with a given constant to the current integer. A program can contain an... | ```python
n = int(input())
a, b = 1023, 0
for _ in range(n):
c, d = input().split()
d = int(d)
if c == '|':
a, b = a | d, b | d
elif c == '&':
a, b = a & d, b & d
elif c == '^':
a, b = a ^ d, b ^ d
print('2\n| {}\n^ {}'.format(a ^ b ^ 1023, a ^ 1023))
# Made By Mostafa_... |
925_A. Stairs and Elevators | In the year of 30XX participants of some world programming championship live in a single large hotel. The hotel has n floors. Each floor has m sections with a single corridor connecting all of them. The sections are enumerated from 1 to m along the corridor, and all sections with equal numbers on different floors are l... | ```python
def takeClosest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
if len(myList) == 0:
return 9e10
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
... |
954_B. String Typing | You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard.
Initially, you have an empty string. Until you type the whole string, you may perform the following operation:
* add a character to the end of the string.
Besides, at most once you may perform one... | ```python
n=int(input())
s=input()
i=0
d=""
ls=[]
mx=-1
while i<n:
temp=s[0:i+1]
for j in range(i+1,n+1):
if temp==s[i+1:j]:
mx=max(mx,len(temp))
i+=1
if mx>0:
print(len(temp)-mx+1)
else:
print(len(temp))
``` |
980_A. Links and Pearls | A necklace can be described as a string of links ('-') and pearls ('o'), with the last link or pearl connected to the first one.
<image>
You can remove a link or a pearl and insert it between two other existing links or pearls (or between a link and a pearl) on the necklace. This process can be repeated as many times... | ```python
s =input()
dash = s.count('-')
ring = s.count('o')
k = min(dash,ring)
m = max(dash,ring)
if dash == 0 or ring==0:
print('YES')
else:
if dash%ring==0:
print('YES')
else:
print('NO')
``` |
9_A. Die Roll | Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpr... | ```python
x, y = input().split()
x = int(x)
y = int(y)
z = 7 - max(x, y)
ans = z/6
if ans == (1/6):
print("1/6")
elif ans == (2/6):
print("1/3")
elif ans == (3/6):
print("1/2")
elif ans == (4/6):
print("2/3")
elif ans == (5/6):
print("5/6")
else:
print("1/1")
``` |
p02544 ACL Contest 1 - Shuffle Window | Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the oper... | ```python
import sys
readline = sys.stdin.buffer.readline
mod=998244353
class BIT:
def __init__(self,n):
self.n=n
self.buf=[0]*n
def add(self,i,v):
buf=self.buf
while i<n:
buf[i]+=v
if buf[i]>=mod:
buf[i]-=mod
i+=(i+1)&(-i-1)
def get(self,i):
buf=self.buf
res=0
while i>=0:
res+=bu... |
p02675 AtCoder Beginner Contest 168 - ∴ (Therefore) | The cat Snuke wants to play a popular Japanese game called ÅtCoder, so Iroha has decided to teach him Japanese.
When counting pencils in Japanese, the counter word "本" follows the number. The pronunciation of this word varies depending on the number. Specifically, the pronunciation of "本" in the phrase "N 本" for a pos... | ```python
n = input()
print('bon' if n[-1]=='3' else 'pon' if n[-1] in ['0','1','6','8'] else 'hon')
``` |
p02803 AtCoder Beginner Contest 151 - Maze Master | Takahashi has a maze, which is a grid of H \times W squares with H horizontal rows and W vertical columns.
The square at the i-th row from the top and the j-th column is a "wall" square if S_{ij} is `#`, and a "road" square if S_{ij} is `.`.
From a road square, you can move to a horizontally or vertically adjacent ro... | ```python
import sys
from collections import deque
H,W=map(int,input().split())
S=list(sys.stdin)
ans=0
for i in range(H):
for j in range(W):
if S[i][j]=='#':
continue
dist=[[-1]*W for _ in range(H)]
dist[i][j]=0
que=deque()
que.append((i,j))
while que:
... |
p02939 AtCoder Grand Contest 037 - Dividing a String | Given is a string S consisting of lowercase English letters. Find the maximum positive integer K that satisfies the following condition:
* There exists a partition of S into K non-empty strings S=S_1S_2...S_K such that S_i \neq S_{i+1} (1 \leq i \leq K-1).
Here S_1S_2...S_K represents the concatenation of S_1,S_2,.... | ```python
s = input()
t = ''
k = 0
prev = ''
for i in range(len(s)):
t += s[i]
if prev != t:
k += 1
prev = t
t = ''
print(k)
``` |
p03076 AtCoder Beginner Contest 123 - Five Dishes | The restaurant AtCoder serves the following five dishes:
* ABC Don (rice bowl): takes A minutes to serve.
* ARC Curry: takes B minutes to serve.
* AGC Pasta: takes C minutes to serve.
* APC Ramen: takes D minutes to serve.
* ATC Hanbagu (hamburger patty): takes E minutes to serve.
Here, the time to serve a dish is ... | ```python
A = [-int(input()) for _ in range(5)]
m = max(A, key = lambda x: x%10)
print(-(m-m//10*10+sum([a//10*10 for a in A])))
``` |
p03218 Dwango Programming Contest V - Cyclic GCDs | Niwango-kun has \\(N\\) chickens as his pets. The chickens are identified by numbers \\(1\\) to \\(N\\), and the size of the \\(i\\)-th chicken is a positive integer \\(a_i\\).
\\(N\\) chickens decided to take each other's hand (wing) and form some cycles. The way to make cycles is represented by a permutation \\(p\\)... | ```python
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
from fractions import gcd
from functools import reduce
MOD = 998244353
N,*A = map(int,read().split())
A.sort()
"""
安い鳥から追加していく。(サイクルの個数 -> 美しさ)が多項式倍で遷移する。
Gaus... |
p03529 CODE FESTIVAL 2017 Final - Mancala | Consider the following game:
* The game is played using a row of N squares and many stones.
* First, a_i stones are put in Square i\ (1 \leq i \leq N).
* A player can perform the following operation as many time as desired: "Select an integer i such that Square i contains exactly i stones. Remove all the stones from S... | ```python
"""
https://atcoder.jp/contests/cf17-final/tasks/cf17_final_g
1回の操作で捨てられる石は1個
いくつ捨てられるかを考えた方がいいだろう
大きい方から?→そんなことはない
小さいほうから?→そんなことはない
今i=aiを満たしている中で最小のものからやるべき?→これはそう
数え上げなので…? → X回とれる盤面は何通りあるか(1)
または、あるindexより右をX回選択できるindexより右側の数列は何通りか(2) → 左は自由
(2)の方がやりやすそう(Nはでかいとする)
→ 右端は1通り (Nのみ)
→ 右から2番目は 1回選択が N-1... |
p03690 AtCoder Grand Contest 016 - XOR Replace | There is a sequence of length N: a = (a_1, a_2, ..., a_N). Here, each a_i is a non-negative integer.
Snuke can repeatedly perform the following operation:
* Let the XOR of all the elements in a be x. Select an integer i (1 ≤ i ≤ N) and replace a_i with x.
Snuke's objective is to match a with another sequence b = (... | ```python
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
return self._parent[x]
def unite(self,... |
p00096 Sum of 4 Integers II | Enter a positive integer n of 4,000 or less, with a pair of integers a, b, c, d in the range 0-1000.
a + b + c + d = n
Create a program that outputs the number of combinations that satisfy the conditions.
Input
Given multiple datasets. Each dataset is given n on one row. Please process until the end of the inpu... | ```python
import sys
for n in sys.stdin:print(sum(max(0,min(i,2002-i))*max(0,min(int(n)-i+2,2000-int(n)+i))for i in range(int(n)+2)))
``` |
p00228 Seven Segments | The screen that displays digital numbers that you often see on calculators is called a "7-segment display" because the digital numbers consist of seven parts (segments).
The new product to be launched by Wakamatsu will incorporate a 7-segment display into the product, and as an employee, you will create a program to d... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0228
"""
import sys
from sys import stdin
input = stdin.readline
LED_pattern = [
##-gfedcba
0b0111111, # 0
0b0000110, # 1
0b1011011, # 2
0b1001111, ... |
p00390 A Round Table for Sages | $N$ sages are sitting around a round table with $N$ seats. Each sage holds chopsticks with his dominant hand to eat his dinner. The following happens in this situation.
* If sage $i$ is right-handed and a left-handed sage sits on his right, a level of frustration $w_i$ occurs to him. A right-handed sage on his right d... | ```python
n = int(input())
aw = [[0,0] for i in range(n)]
for i, a in enumerate(map(int, input().split())): aw[i][0] = a
for i, w in enumerate(map(int, input().split())): aw[i][1] = w
migimin = 1001
hidarimin = 1001
for a,w in aw:
if a: hidarimin = min(hidarimin, w)
else: migimin = min(migimin, w)
if hidarimin>... |
p00606 Cleaning Robot | Dr. Asimov, a robotics researcher, loves to research, but hates houseworks and his house were really dirty. So, he has developed a cleaning robot.
As shown in the following figure, his house has 9 rooms, where each room is identified by an alphabet:
<image>
The robot he developed operates as follows:
* If the bat... | ```python
# AOJ 1020: Cleaning Robot
# Python3 2018.7.5 bal4u
mv = ((-1,0),(0,1),(1,0),(0,-1))
while True:
n = int(input())
if n == 0: break
t1, t2, t3 = input().split()
s, t, b = ord(t1)-ord('A'), ord(t2)-ord('A'), ord(t3)-ord('A')
f = [[[0.0 for a in range(3)] for c in range(3)] for r in range(17)]
f[0][s//3][... |
p00743 Discrete Speed | Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there... | ```python
from collections import defaultdict
from heapq import heappop, heappush
while True:
n, m = map(int, input().split())
if n==0 and m==0:
break
s, g = map(int, input().split())
graph = defaultdict(list)
for _ in range(m):
x, y, d, c = map(int, input().split())
graph[x].append((y, d, c))
... |
p01146 Princess in Danger | Princess in Danger
Princess crisis
English text is not available in this practice contest.
A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously inj... | ```python
from heapq import heappop, heappush
def dijkstra(links, n, m, freezables, s, t):
queue = [(0, 0, s, m)]
visited = [0] * n
while queue:
link_cost, cost, node, remain = heappop(queue)
if node == t:
# Congratulations!
if link_cost <= m:
return... |
p01284 Erratic Sleep Habits | Peter is a person with erratic sleep habits. He goes to sleep at twelve o'lock every midnight. He gets up just after one hour of sleep on some days; he may even sleep for twenty-three hours on other days. His sleeping duration changes in a cycle, where he always sleeps for only one hour on the first day of the cycle.
... | ```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 ... |
p01766 Soccer | Problem statement
We played an AI soccer match between Country A and Country B. You have a table that records the player who had the ball at a certain time and its position. The table consists of N rows, and the i-th row from the top consists of the following elements.
* Number of frames f_i
* The uniform number of t... | ```python
import math
n = int(input())
prev = list(map(int, input().split()))
max_disA = -1
max_disB = -1
min_timeA = 10**9
min_timeB = 10**9
for _ in range(n-1):
curr = list(map(int, input().split()))
if prev[1] != curr[1] and prev[2] == curr[2]:
dis = math.sqrt((prev[3] - curr[3])**2 + (prev[4] - c... |
p01900 Mod!Mod! | C: Mod! Mod!
story
That's right! I'm looking for eyewitness testimony! A phantom thief has appeared in Aizu! Everyone's horse stick was stolen! Who is the culprit! ?? Unravel! Mod! Mod!
Problem statement
"Eyes" ... it's a miracle bud that swells in the hearts of the chosen ones ... You can steal anything with the s... | ```python
# AOJ 2800: Mod!Mod!
# Python3 2018.7.11 bal4u
n = int(input())
a = list(map(int, input().split()))
c = [0]*3
for i in a: c[i%3] += 1
if (c[1]|c[2]) == 0: ans = 1
else:
ans, n = c[0], n-c[0]
if n <= 3: ans += n
else:
t = max(-3, min(3, c[1]-c[2]))
if t > 0: ans += 2*c[2]+t
else: ans += 2*c[1]-t
prin... |
p02037 Tile | problem
I want to put as many rectangular tiles as possible on a rectangular wall with a size of $ h $ in height and $ w $ in width, and a size of $ a $ in height and $ b $ in width.
The following conditions must be met when attaching tiles.
* Do not stack tiles.
* Do not apply tiles diagonally, that is, any edge o... | ```python
h,w=map(int,input().split())
a,b=map(int,input().split())
high=(h//a)*a
wide=(w//b)*b
print(h*w-high*wide)
``` |
p02323 Traveling Salesman Problem | For a given weighted directed graph G(V, E), find the distance of the shortest route that meets the following criteria:
* It is a closed cycle where it ends at the same point it starts.
* It visits each vertex exactly once.
Constraints
* 2 ≤ |V| ≤ 15
* 0 ≤ di ≤ 1,000
* There are no multiedge
Input
|V| |E|
s0 t0 d... | ```python
v,e=[int(j) for j in input().split()]
d=[[10**18]*v for i in range(v)]
dp=[[-1]*v for i in range(1<<v)]
for i in range(e):
s,t,w=[int(j) for j in input().split()]
d[s][t]=w
def f(s,n,dp):
if dp[s][n]>=0:
return dp[s][n]
if s==(1<<v)-1 and n==0:
dp[s][n]=0
return 0
... |
p02468 Power | For given integers m and n, compute mn (mod 1,000,000,007). Here, A (mod M) is the remainder when A is divided by M.
Constraints
* 1 ≤ m ≤ 100
* 1 ≤ n ≤ 109
Input
m n
Two integers m and n are given in a line.
Output
Print mn (mod 1,000,000,007) in a line.
Examples
Input
2 3
Output
8
Input
5 8
Output... | ```python
# https://onlinejudge.u-aizu.ac.jp/courses/library/6/NTL/1/NTL_1_B
# pythonのpowが優秀でMODまで取ることができる
MOD = 10**9 + 7
a, b = list(map(int, input().split()))
print(pow(a, b, MOD))
``` |
1003_C. Intense Heat | The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually cal... | ```python
n, k = map(int, input().split())
ar = list(map(int, input().split()))
average = M = 0
for i in range(n):
s = 0
for j in range(i,n):
s += ar[j]
if (j-i+1) >= k:
average = s / (j-i+1)
M = max(M, average)
print(M)
``` |
1027_D. Mouse Hunt | Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 4 (hopefully) years.
The dormitory consists of n rooms and a single mouse! Girls decided to set mouse tra... | ```python
n = int(input())
C = [int(s) for s in input().split(" ")]
A = [int(s)-1 for s in input().split(" ")]
al = [False for i in range(0, n)]
ans = 0
for v in range(0, n):
if al[v]:
continue
sequence = []
while not al[v]:
sequence.append(v)
al[v] = True
v = A[v]
if v i... |
1046_C. Space Formula | Formula 1 officials decided to introduce new competition. Cars are replaced by space ships and number of points awarded can differ per race.
Given the current ranking in the competition and points distribution for the next race, your task is to calculate the best possible ranking for a given astronaut after the next r... | ```python
n,k=map(int,input().strip().split())
cr = list(map(int,input().strip().split()))
pa = list(map(int,input().strip().split()))
x = cr[k-1]+pa[0]
p = 0
if k==1:
print(1)
else:
for i in range(k-1):
if cr[i]+pa[-1]<=x:
p +=1
del pa[-1]
print(k-p)
``` |
1070_B. Berkomnadzor | Berkomnadzor — Federal Service for Supervision of Communications, Information Technology and Mass Media — is a Berland federal executive body that protects ordinary residents of Berland from the threats of modern internet.
Berkomnadzor maintains a list of prohibited IPv4 subnets (blacklist) and a list of allowed IPv4 ... | ```python
#!/usr/bin/env python3
# Copied solution
import collections
import sys
import traceback
class Input(object):
def __init__(self):
self.fh = sys.stdin
def next_line(self):
while True:
line = sys.stdin.readline()
if line == '\n':
continue
... |
1091_F. New Year and the Mallard Expedition | Bob is a duck. He wants to get to Alice's nest, so that those two can duck!
<image> Duck is the ultimate animal! (Image courtesy of See Bang)
The journey can be represented as a straight line, consisting of n segments. Bob is located to the left of the first segment, while Alice's nest is on the right of the last seg... | ```python
from heapq import heappush, heappop
n = int(input())
L = list(map(int, input().split()))
T = input()
# fly -> walk, time cost: +4s, stamina: +2
# walk in place, time cost: +5s, stamina: +1
#fly -> swim, time cost: +2s, stamina: +2
#swim in place, time cost: +3s, stamina:+1
ans = sum(L)
Q = []
for l, t in... |
1110_D. Jongmah | You are playing a game of Jongmah. You don't need to know the rules to solve this problem. You have n tiles in your hand. Each tile has an integer between 1 and m written on it.
To win the game, you will need to form some number of triples. Each triple consists of three tiles, such that the numbers written on the tile... | ```python
from collections import Counter
n, m = map(int, input().split())
B = list(map(int, input().split()))
cnt = Counter(B)
A = sorted(cnt.keys())
n = len(A)
dp = [[0] * 3 for _ in range(3)]
for i, a in enumerate(A):
dp2 = [[0] * 3 for _ in range(3)]
for x in range(1 if i >= 2 and a - 2 != A[i - 2] else 3):... |
1140_A. Detective Book | Ivan recently bought a detective book. The book is so interesting that each page of this book introduces some sort of a mystery, which will be explained later. The i-th page contains some mystery that will be explained on page a_i (a_i ≥ i).
Ivan wants to read the whole book. Each day, he reads the first page he didn'... | ```python
import sys
#p = [[] for i in range(N)]
#for i in range(N):
# p[i] += map(int, sys.stdin.readline().split())
#Q = input()
#for i in range(Q):
# print(list(map(int, sys.stdin.readline().split())))
n = int(input())
a = [int(c) for c in sys.stdin.readline().split()]
aktmax, d = 0, 0
for i, c in enumerate(a... |
1180_D. Tolik and His Uncle | This morning Tolik has understood that while he was sleeping he had invented an incredible problem which will be a perfect fit for Codeforces! But, as a "Discuss tasks" project hasn't been born yet (in English, well), he decides to test a problem and asks his uncle.
After a long time thinking, Tolik's uncle hasn't any... | ```python
# [0,0,0]
# [0,0,0]
# [1,0,0]
# [0,0,0]
# [0,0,0]
# [1,0,1]
# [0,0,0]
# [0,0,0]
# [1,1,1]
# [0,0,0]
# [0,0,0]
# [1,1,1]
# [0,0,1]
# [0,0,0]
# [0,0,0] 3,2
#
# 0,0 3,2
# 0,1 3,1
# 0,2 3,0
# 1,0 2,2
# 1,1 2,1
# 1,2 2,0
n, m = map(int, input().split())
ans = []
if n % 2 == 0:
for i in range(int(n / 2))... |
1199_D. Welfare State | There is a country with n citizens. The i-th of them initially has a_{i} money. The government strictly controls the wealth of its citizens. Whenever a citizen makes a purchase or earns some money, they must send a receipt to the social services mentioning the amount of money they currently have.
Sometimes the governm... | ```python
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def main():
n = int(input())
A = list(map(int, input().split()))
q = int(input())
Q = []
for i in range(q):
temp = list(map(int, input().split()))
t = temp[0]
if t == 1:
... |
1216_C. White Sheet | There is a white sheet of paper lying on a rectangle table. The sheet is a rectangle with its sides parallel to the sides of the table. If you will take a look from above and assume that the bottom left corner of the table has coordinates (0, 0), and coordinate axes are left and bottom sides of the table, then the bott... | ```python
a=list(map(int,input().split()))
x1,y1,x2,y2=a[0],a[1],a[2],a[3]
a=list(map(int,input().split()))
x3,y3,x4,y4=a[0],a[1],a[2],a[3]
a=list(map(int,input().split()))
x5,y5,x6,y6=a[0],a[1],a[2],a[3]
l1=l2=l3=l4=1
if (x1>=x5 and x2<=x6 and y1>=y5 and y1<=y6) or (x1>=x3 and x2<=x4 and y1>=y3 and y1<=y4) or (y1>=y5 ... |
1257_F. Make Them Similar | Let's call two numbers similar if their binary representations contain the same number of digits equal to 1. For example:
* 2 and 4 are similar (binary representations are 10 and 100);
* 1337 and 4213 are similar (binary representations are 10100111001 and 1000001110101);
* 3 and 2 are not similar (binary repr... | ```python
def main():
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
dic1 = {}
dic2 = {}
A1 = [0] * N
for i, a in enumerate(A):
A1[i] = a>>15
for i in range(2**15):
tmp = [0] * N
for j, a in enumerate(A1):
... |
1281_A. Suffix Three | We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | ```python
n = int(input())
for _ in range(n):
s = input().split("_")[-1:][0]
if s[-2:] == "po":
print("FILIPINO")
elif s[-4:] == "desu" or s[-4:] == "masu":
print("JAPANESE")
else:
print("KOREAN")
``` |
1301_A. Three Strings | You are given three strings a, b and c of the same length n. The strings consist of lowercase English letters only. The i-th letter of a is a_i, the i-th letter of b is b_i, the i-th letter of c is c_i.
For every i (1 ≤ i ≤ n) you must swap (i.e. exchange) c_i with either a_i or b_i. So in total you'll perform exactly... | ```python
t = int(input())
for T in range(t):
a = input()
b = input()
c = input()
n = len(a)
count = 0
for i in range(n):
if a[i] == c[i] or b[i] == c[i]:
count += 1
if count == n:
print("YES")
else:
print("NO")
``` |
1325_A. EhAb AnD gCd | You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | ```python
# your code goes here
for _ in range(int(input())):
x=int(input())
print(1,end=" ")
print(x-1)
``` |
1343_F. Restore the Permutation by Sorted Segments | We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you.
For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in s... | ```python
for _ in range(int(input())):
n = int(input())
segs = [tuple(sorted(int(x) for x in input().split()[1:])) for __ in range(n - 1)]
segs_having = [[j for j, seg in enumerate(segs) if i in seg] for i in range(n + 1)]
segs_set = set(segs)
for first in range(1, n + 1):
try:
... |
1385_G. Columns Swaps | You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n.
In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once.
Your task is to find the minimum number of moves required to obtain pe... | ```python
for t in range(int(input())):
n = int(input())
aa = [
[int(s)-1 for s in input().split(' ')]
for _ in [0, 1]
]
maxv = max(max(aa[0]), max(aa[1]))
minv = min(min(aa[0]), min(aa[1]))
if minv != 0 or maxv != n - 1:
print(-1)
continue
counts = [0] * n
... |
1407_E. Egor in the Republic of Dagestan | Egor is a famous Russian singer, rapper, actor and blogger, and finally he decided to give a concert in the sunny Republic of Dagestan.
There are n cities in the republic, some of them are connected by m directed roads without any additional conditions. In other words, road system of Dagestan represents an arbitrary d... | ```python
import sys
input = sys.stdin.readline
from collections import deque
n, m = map(int, input().split())
back = [[] for i in range(n)]
for _ in range(m):
u, v, w = map(int, input().split())
u -= 1
v -= 1
back[v].append((u,w))
out = [2] * n
outl = [-1] * n
outl[-1] = 0
q = deque([n - 1])... |
1428_C. ABBB | Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | ```python
# from debug import *
import sys;input = sys.stdin.readline
for _ in range(int(input())):
s = input().strip()
stack = []
for i in s:
if stack and i == 'B': stack.pop()
else: stack.append(i)
print(len(stack))
``` |
1451_C. String Equality | Ashish has two strings a and b, each of length n, and an integer k. The strings only contain lowercase English letters.
He wants to convert string a into string b by performing some (possibly zero) operations on a.
In one move, he can either
* choose an index i (1 ≤ i≤ n-1) and swap a_i and a_{i+1}, or
* choos... | ```python
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n,k=map(int,input().split())
a=input()
b=input()
l1=[0]*26
l2=[0]*26
for i in range(n):
l1[ord(a[i])-97]+=1
l2[ord(b[i])-97]+=1
f=False
for i in range(25):
z=l1[i]-l2[i]
if(z<0 o... |
1475_C. Ball in Berland | At the school where Vasya is studying, preparations are underway for the graduation ceremony. One of the planned performances is a ball, which will be attended by pairs of boys and girls.
Each class must present two couples to the ball. In Vasya's class, a boys and b girls wish to participate. But not all boys and not... | ```python
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 27 00:37:06 2021
@author: rishi
"""
import math
def ncr(n,r):
p=1
k=1
if(n-r<r):
r=n-r;
if(r!=0):
while(r>0):
p*=n
k*=r
m=math.gcd(p,k)
p//=m
k//=m
n-=1
... |
1500_A. Going Home | It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a.
Several hours after starting her journey home Nastya remembered about the present. To ente... | ```python
def show(x, y, z, w):
print("YES")
print(x+1, y+1, z+1, w+1)
exit(0)
n=int(input())
ara=list(int(x) for x in input().split())
n=min(n, 2000)
found={}
for i in range(0, n):
for j in range(i+1, n):
cur_sm=ara[i]+ara[j]
if cur_sm in found.keys() and found[cur_sm][0]!=i and found[cur_sm][1]!=j and found... |
1525_C. Robot Collisions | There are n robots driving along an OX axis. There are also two walls: one is at coordinate 0 and one is at coordinate m.
The i-th robot starts at an integer coordinate x_i~(0 < x_i < m) and moves either left (towards the 0) or right with the speed of 1 unit per second. No two robots start at the same coordinate.
Whe... | ```python
from collections import deque
def main():
t=int(input())
allans=[]
for _ in range(t):
n,m=readIntArr()
xes=readIntArr()
direction=input().split()
ans=[-1]*n
# moving to each other will collide first, followed by moving in same directi... |
177_G2. Fibonacci Strings | Fibonacci strings are defined as follows:
* f1 = «a»
* f2 = «b»
* fn = fn - 1 fn - 2, n > 2
Thus, the first five Fibonacci strings are: "a", "b", "ba", "bab", "babba".
You are given a Fibonacci string and m strings si. For each string si, find the number of times it occurs in the given Fibonacci string as... | ```python
F = ['', 'a', 'b', 'ba', 'bab', 'babba', 'babbabab', 'babbababbabba', 'babbababbabbababbabab', 'babbababbabbababbababbabbababbabba', 'babbababbabbababbababbabbababbabbababbababbabbababbabab', 'babbababbabbababbababbabbababbabbababbababbabbababbababbabbababbabbababbababbabbababbabba', 'babbababbabbababbababbab... |
19_A. World Football Cup | Everyone knows that 2010 FIFA World Cup is being held in South Africa now. By the decision of BFA (Berland's Football Association) next World Cup will be held in Berland. BFA took the decision to change some World Cup regulations:
* the final tournament features n teams (n is always even)
* the first n / 2 teams ... | ```python
import sys
# from itertools import product
import logging
logging.root.setLevel(level=logging.INFO)
team_size = int(sys.stdin.readline())
teams = {}
for _ in range(team_size):
name = sys.stdin.readline().strip()
teams[name] = {
"point":0,
"delta":0,
"score":0
}
contest_si... |
223_B. Two Strings | A subsequence of length |x| of string s = s1s2... s|s| (where |s| is the length of string s) is a string x = sk1sk2... sk|x| (1 ≤ k1 < k2 < ... < k|x| ≤ |s|).
You've got two strings — s and t. Let's consider all subsequences of string s, coinciding with string t. Is it true that each character of string s occurs in at... | ```python
import bisect
import string
s = input()
t = input()
max_match = [0 for i in range(len(s))]
min_match = [0 for i in range(len(s))]
char_idx = [0 for i in range(30)]
char_occur = [ [] for i in range(30) ]
for (i, ch) in enumerate(t):
idx = ord(ch) - ord('a')
char_occur[idx].append(i)
for ch in strin... |
272_A. Dima and Friends | Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t... | ```python
def solve(n,d):
other = 0
for i in d:
other += i
ways = 0
for i in range(1,6):
if (other + i) % (n + 1) != 1:
ways += 1
print(ways)
def main():
n = int(input())
d = input()
d = [int(i) for i in d.split()]
solve(n,d)
main()
``` |
295_C. Greg and Friends | One day Greg and his friends were walking in the forest. Overall there were n people walking, including Greg. Soon he found himself in front of a river. The guys immediately decided to get across the river. Luckily, there was a boat by the river bank, just where the guys were standing. We know that the boat can hold pe... | ```python
from collections import deque
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
c50 = sum([1 for i in a if i == 50])
c100 = sum([1 for i in a if i == 100])
c = [[0] * 51 for i in range(51)]
c[0][0] = 1
c[1][0] = 1
c[1][1] = 1
for x in range(2, 51):
for y in range(x + 1):
... |
319_A. Malek Dance Club | As a tradition, every year before IOI all the members of Natalia Fan Club are invited to Malek Dance Club to have a fun night together. Malek Dance Club has 2n members and coincidentally Natalia Fan Club also has 2n members. Each member of MDC is assigned a unique id i from 0 to 2n - 1. The same holds for each member o... | ```python
s = input()
res = pow(2, len(s)-1)*(int(s, 2))
print (res%1000000007)
``` |
343_A. Rational Resistance | Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value.
However, all Mike has is lots of identical resistors with unit resistance R0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will co... | ```python
I = lambda : list(map(int, input().split(' ')))
a, b = I()
ans = 0
while a > 0 and b > 0 and a//b > 0 or b//a > 0:
ans += a//b
a, b = b, a%b
print(ans)
``` |
366_C. Dima and Salad | Dima, Inna and Seryozha have gathered in a room. That's right, someone's got to go. To cheer Seryozha up and inspire him to have a walk, Inna decided to cook something.
Dima and Seryozha have n fruits in the fridge. Each fruit has two parameters: the taste and the number of calories. Inna decided to make a fruit sala... | ```python
from bisect import bisect_right
n, k = map(int, input().split())
t = sorted((u - k * v, v) for u, v in zip(*(map(int, input().split()), map(int, input().split()))))
m = n - bisect_right(t, (0, 0))
l, p, t = 0, [0] * 100001, t[:: -1]
for d, v in t[: m]:
for j in range(l, 0, -1):
if p[j]: p[j + d] =... |
38_B. Chess | Two chess pieces, a rook and a knight, stand on a standard chessboard 8 × 8 in size. The positions in which they are situated are known. It is guaranteed that none of them beats the other one.
Your task is to find the number of ways to place another knight on the board so that none of the three pieces on the board bea... | ```python
l=[]
for i in range(1,9):
for j in range(1,9):
l.append(int(str(i)+str(j)))
l2=[]
def check(l2,c,d):
if c+1<=8 and d+2<=8:
l2.append(int(str(c+1)+str(d+2)))
if c+2<9 and d+1<9:
l2.append(int(str(c+2)+str(d+1)))
if c-1>0 and d-2>0:
l2.append(int(str(c-1)+str(d-... |
40_A. Find Color | Not so long ago as a result of combat operations the main Berland place of interest — the magic clock — was damaged. The cannon's balls made several holes in the clock, that's why the residents are concerned about the repair. The magic clock can be represented as an infinite Cartesian plane, where the origin correspond... | ```python
# _
#####################################################################################################################
from math import sqrt, ceil
def colorOfDamagedArea(x, y):
location = sqrt(x*x+y*y)
area_sBorder = ceil(location)
if location == area_sBorder:
return 'black'
are... |
483_A. Counterexample | Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the... | ```python
s, e = [int(num) for num in input().split()]
def GCD(a, b):
return GCD(b, a % b) if b else a
result = -1
for i in range(s, e + 1):
for j in range(i + 1, e + 1):
if GCD(i, j) == 1:
for k in range(j + 1, e + 1):
if GCD(j, k) == 1 and GCD(i, k) != 1:
... |
507_A. Amr and Music | Amr is a young coder who likes music a lot. He always wanted to learn how to play music but he was busy coding so he got an idea.
Amr has n instruments, it takes ai days to learn i-th instrument. Being busy, Amr dedicated k days to learn how to play the maximum possible number of instruments.
Amr asked for your help ... | ```python
I = lambda: map(int, input().split())
n, k = I()
l = sorted(zip(I(), range(1, n+1)))
h = []
for i, j in l:
k -= i
if k>=0: h.append(j)
print(len(h));print(*h)
``` |
556_B. Case of Fake Numbers | Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers f... | ```python
import functools as ft
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
b = [i for i in range(n)]
for i in range(1, n + 1):
a = [(a[j] + 1) % n if not j % 2 else (a[j] - 1) % n for j in range(n)]
cnt = ft.reduce(lambda x, y: x + y, [a[j] == b[j]... |
626_C. Block Towers | Students in a class are making towers of blocks. Each student makes a (non-zero) tower by stacking pieces lengthwise on top of each other. n of the students use pieces made of two blocks and m of the students use pieces made of three blocks.
The students don’t want to use too many blocks, but they also want to be uniq... | ```python
n, m = map(int, input().split())
x = max(n*2, m*3)
while x//2+x//3-x//6 < m+n:
x += 1
print(x)
``` |
650_A. Watchmen | Watchmen are in a danger and Doctor Manhattan together with his friend Daniel Dreiberg should warn them as soon as possible. There are n watchmen on a plane, the i-th watchman is located at point (xi, yi).
They need to arrange a plan, but there are some difficulties on their way. As you know, Doctor Manhattan consider... | ```python
import collections
r=0;a,b,c=[collections.Counter() for _ in [0,0,0]]
for _ in range(int(input())):
x,y=map(int, input().split())
r+=a[x]+b[y]-c[(x,y)]
a[x]+=1;b[y]+=1;c[(x,y)]+=1
print(r)
``` |
675_D. Tree Construction | During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help.
You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal d... | ```python
__author__ = "House"
import bisect
if __name__ == "__main__":
n = int(input())
s = [int(i) for i in input().split()]
f = [[s[0], 0]]
outp = list()
for i in range(1, n):
now = [s[i], i]
idx = bisect.bisect_left(f, now)
ans = 0
if idx == 0:
ans =... |
765_C. Table Tennis Game 2 | Misha and Vanya have played several table tennis sets. Each set consists of several serves, each serve is won by one of the players, he receives one point and the loser receives nothing. Once one of the players scores exactly k points, the score is reset and a new set begins.
Across all the sets Misha scored a points ... | ```python
""" Created by Henrikh Kantuni on 2/14/17 """
if __name__ == '__main__':
k, a, b = [int(x) for x in input().split()]
score_a = 0
if a >= k:
score_a = a // k
score_b = 0
if b >= k:
score_b = b // k
if score_a == 0 and score_b == 0:
print(-1)
else:
... |
80_B. Depression | Do you remember a kind cartoon "Beauty and the Beast"? No, no, there was no firing from machine guns or radiation mutants time-travels!
There was a beauty named Belle. Once she had violated the Beast's order and visited the West Wing. After that she was banished from the castle...
Everybody was upset. The beautiful ... | ```python
#
# solving:
# from: https://vjudge.net/contest/417235#problem/D
def main():
inlist = input().split(":")
hh, mm = int(inlist[0]), int(inlist[1])
deg_per_h = 360/12
deg_per_m = 360/60
print("{} {}".format(((hh+mm/60) * deg_per_h) % 360, (mm * deg_per_m) % 360))
main()
... |
87_A. Trains | Vasya the programmer lives in the middle of the Programming subway branch. He has two girlfriends: Dasha and Masha, who live at the different ends of the branch, each one is unaware of the other one's existence.
When Vasya has some free time, he goes to one of his girlfriends. He descends into the subway at some time,... | ```python
a,b=map(int,input().split())
if(a==b):
print('Equal')
exit()
import math
lcm=(a*b)//(math.gcd(a,b))
if(a<b):
da=(lcm//a)-1
ma=lcm//b
if(da>ma):
print('Dasha')
elif(da<ma):
print('Masha')
else:
print('Equal')
else:
da=(lcm//a)
ma=(lcm//b)-1
if(da... |
903_C. Boxes Packing | Mishka has got n empty boxes. For every i (1 ≤ i ≤ n), i-th box is a cube with side length ai.
Mishka can put a box i into another box j if the following conditions are met:
* i-th box is not put into another box;
* j-th box doesn't contain any other boxes;
* box i is smaller than box j (ai < aj).
Mishka ... | ```python
from sys import stdin,stdout
from collections import Counter
def ai(): return list(map(int, stdin.readline().split()))
def ei(): return map(int, stdin.readline().split())
def ip(): return int(stdin.readline().strip())
def op(ans): return stdout.write(str(ans) + '\n')
t = ip()
li = ai()
x = max(li)
c = Count... |
954_E. Water Taps | Consider a system of n water taps all pouring water into the same container. The i-th water tap can be set to deliver any amount of water from 0 to ai ml per second (this amount may be a real number). The water delivered by i-th tap has temperature ti.
If for every <image> you set i-th tap to deliver exactly xi ml of ... | ```python
n,t=map(int,input().strip().split(' '))
x= list(map(int,input().strip().split(' ')))
temp= list(map(int,input().strip().split(' ')))
for i in range(n):
temp[i]-=t
pos = []
neg = []
ans = 0
negsum = 0
possum = 0
for i in range(n):
if(temp[i]<0):
negsum+=temp[i]*x[i]
neg.append([temp[i]*-1,x[i]])
... |
980_D. Perfect Groups | SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square.
Each integer must be in exactly one gro... | ```python
#!/usr/bin/env python3
from math import sqrt
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193,
197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 2... |
9_D. How many trees? | In one very old text file there was written Great Wisdom. This Wisdom was so Great that nobody could decipher it, even Phong — the oldest among the inhabitants of Mainframe. But still he managed to get some information from there. For example, he managed to learn that User launches games for pleasure — and then terribl... | ```python
n,h=map(int,input().split())
L=[]
for i in range(n+1):
g=[]
for j in range(n+1):
g.append(0)
L.append(g)
L[0][0]=1
for i in range(1,n+1):
for j in range(1,n+1):
sumu=0
for m in range(1,i+1):
t1=L[m-1][j-1]
tot=0
for k in range(0,j):
... |
p02547 AtCoder Beginner Contest 179 - Go to Jail | Tak performed the following action N times: rolling two dice. The result of the i-th roll is D_{i,1} and D_{i,2}.
Check if doublets occurred at least three times in a row. Specifically, check if there exists at lease one i such that D_{i,1}=D_{i,2}, D_{i+1,1}=D_{i+1,2} and D_{i+2,1}=D_{i+2,2} hold.
Constraints
* 3 \... | ```python
n=int(input())
ans=0
flg=0
aa="No"
for _ in range(n):
a,b=map(int,input().split())
if a==b:
ans+=1
else:
ans=0
if ans==3:
aa="Yes"
print(aa)
``` |
p02678 AtCoder Beginner Contest 168 - .. (Double Dots) | There is a cave.
The cave has N rooms and M passages. The rooms are numbered 1 to N, and the passages are numbered 1 to M. Passage i connects Room A_i and Room B_i bidirectionally. One can travel between any two rooms by traversing passages. Room 1 is a special room with an entrance from the outside.
It is dark in th... | ```python
from collections import deque
N,M=map(int,input().split())
G=[ [] for _ in range(N) ]
for i in range(M):
A,B=map(int,input().split())
A-=1
B-=1
G[A].append(B)
G[B].append(A)
searched=[0]*N
searched[0]=1
ans=[-1]*N
d=deque()
d.append(0)
while(len(d)!=0):
tmp=d.popleft()
for g in G[tmp]:
if s... |
p02806 Dwango Programming Contest 6th - Falling Asleep | Niwango created a playlist of N songs. The title and the duration of the i-th song are s_i and t_i seconds, respectively. It is guaranteed that s_1,\ldots,s_N are all distinct.
Niwango was doing some work while playing this playlist. (That is, all the songs were played once, in the order they appear in the playlist, w... | ```python
n = int(input())
slst = []
tlst = []
for _ in range(n):
s,t = map(str,input().split())
slst.append(s)
tlst.append(int(t))
x = input()
print(sum(tlst[slst.index(x)+1:]))
``` |
p02942 AtCoder Grand Contest 037 - Sorting a Grid | We have a grid with N rows and M columns of squares. Each integer from 1 to NM is written in this grid once. The number written in the square at the i-th row from the top and the j-th column from the left is A_{ij}.
You need to rearrange these numbers as follows:
1. First, for each of the N rows, rearrange the number... | ```python
from collections import defaultdict, deque
N, M = map(int, input().split())
A = [[0] * M for _ in range(N)]
B = [[0] * M for _ in range(N)]
C = [[0] * M for _ in range(N)]
G = defaultdict(lambda: defaultdict(int))
F = defaultdict(lambda: defaultdict(int))
rows = [0] * (N * M + 1)
for i in range(N):
A_l... |
p03079 ExaWizards 2019 - Regular Triangle | You are given three integers A, B and C.
Determine if there exists an equilateral triangle whose sides have lengths A, B and C.
Constraints
* All values in input are integers.
* 1 \leq A,B,C \leq 100
Input
Input is given from Standard Input in the following format:
A B C
Output
If there exists an equilateral ... | ```python
s = input().split(" ")
if s[0] == s[1] == s[2]:
print("Yes")
else:
print("No")
``` |
p03222 AtCoder Beginner Contest 113 - Number of Amidakuji | Amidakuji is a traditional method of lottery in Japan.
To make an amidakuji, we first draw W parallel vertical lines, and then draw horizontal lines that connect them. The length of each vertical line is H+1 [cm], and the endpoints of the horizontal lines must be at 1, 2, 3, ..., or H [cm] from the top of a vertical l... | ```python
H,W,K = map(int,input().split())
dp = []
for i in range(H+1):
L = [0]*W
dp.append(L)
fb = [1,1]
for i in range(W-2):
fb.append(fb[i]+fb[i+1])
dp[0][0] = 1
if W != 1:
for i in range(1,H+1):
for j in range(W):
if 1 <= j <= W-2:
dp[i][j] = dp[i-1][j-1]*fb[j-1]*fb[W-j-1]+dp[i-1][j]*fb[j]... |
p03370 AtCoder Beginner Contest 095 - Bitter Alchemy | Akaki, a patissier, can make N kinds of doughnut using only a certain powder called "Okashi no Moto" (literally "material of pastry", simply called Moto below) as ingredient. These doughnuts are called Doughnut 1, Doughnut 2, ..., Doughnut N. In order to make one Doughnut i (1 ≤ i ≤ N), she needs to consume m_i grams o... | ```python
N,X = map(int, input().split())
M = [int(input()) for _ in range(N)]
X = X - sum(M)
print(N + X//min(M))
``` |
p03693 AtCoder Beginner Contest 064 - RGB Cards | AtCoDeer has three cards, one red, one green and one blue.
An integer between 1 and 9 (inclusive) is written on each card: r on the red card, g on the green card and b on the blue card.
We will arrange the cards in the order red, green and blue from left to right, and read them as a three-digit integer.
Is this integer... | ```python
print("YES" if int(input()[0::2])%4==0 else "NO")
``` |
p03846 AtCoder Beginner Contest 050 - Lining Up | There are N people, conveniently numbered 1 through N. They were standing in a row yesterday, but now they are unsure of the order in which they were standing. However, each person remembered the following fact: the absolute difference of the number of the people who were standing to the left of that person, and the nu... | ```python
n=int(input())
A=list(map(int,input().split()))
cnt=[abs(i-(n-i-1)) for i in range(n)]
if sorted(A)==sorted(cnt):
print((2**(n//2))%(10**9+7))
else:
print(0)
``` |
p04014 AtCoder Beginner Contest 044 - Digit Sum | For integers b (b \geq 2) and n (n \geq 1), let the function f(b,n) be defined as follows:
* f(b,n) = n, when n < b
* f(b,n) = f(b,\,{\rm floor}(n / b)) + (n \ {\rm mod} \ b), when n \geq b
Here, {\rm floor}(n / b) denotes the largest integer not exceeding n / b, and n \ {\rm mod} \ b denotes the remainder of n div... | ```python
n=int(input())
s=int(input())
b_ans=1
if n==s:
b_ans=n+1
if b_ans==1:
for b in range(2,int(n**0.5)+1):
nn=n
st=[]
while(nn>0):
st.append(nn%b)
nn=(nn-st[-1])/b
if sum(st)==s:
b_ans=b
break
if b_ans==1:
for p in range(int(n**0.5),0,-1):
b=(n-s+p)/p
... |
p00099 Surf Smelt Fishing Contest II | A smelt fishing tournament was held at Lake Hibara. It seems that catch and release is recommended this time.
Create a program that reads the participant number and the number of fish caught or released in order as one event, and outputs the participant number and the number of animals that have acquired the most smel... | ```python
# AOJ 0099 Surf Smelt Fishing Contest II
# Python3 2018.6.22 bal4u
import heapq
MAX = 1000000
SFT = 20 # 2**20 = 1048576 > MAX
Q = []
# tbl[0:キー, 1:Magic]
n, q = list(map(int, input().split()))
tbl = [0]*(n+1)
for i in range(q):
id, v = list(map(int, input().split()))
tbl[id] += v
heapq.heappush(Q, ((-tb... |
p00231 Dangerous Bridge | In Aizuwakamatsu Village, which is located far north of Aizuwakamatsu City, a bridge called "Yabashi" is the only way to move to the surrounding villages. Despite the large number of passers-by, the bridge is so old that it is almost broken.
<image>
Yabashi is strong enough to withstand up to 150 [kg]. For example,... | ```python
# coding: utf-8
# Your code here!
class Sch:
def __init__(self, m, t):
self.m = m
self.t = t
def __lt__(self,other):
if self.t == other.t:
return self.m < other.m
else:
return self.t < other.t
while True:
N = int(input())
... |
p00393 Beautiful Sequence | Alice is spending his time on an independent study to apply to the Nationwide Mathematics Contest. This year’s theme is "Beautiful Sequence." As Alice is interested in the working of computers, she wants to create a beautiful sequence using only 0 and 1. She defines a "Beautiful" sequence of length $N$ that consists on... | ```python
MOD = 1000000007
N, M = (int(x) for x in input().split())
pow = [0] * (N + 1)
dp = [0] * (N + 1)
pow[0] = 1
for i in range(1, N + 1):
pow[i] = pow[i - 1] * 2
pow[i] %= MOD
dp[0] = 1
for i in range(1, M + 1):
dp[i] = pow[i]
dp[M] -= 1
for i in range(M + 1, N + 1):
dp[i] = dp[i - 1] + (d... |
p00746 Pablo Squarson's Headache | Pablo Squarson is a well-known cubism artist. This year's theme for Pablo Squarson is "Squares". Today we are visiting his studio to see how his masterpieces are given birth.
At the center of his studio, there is a huuuuuge table and beside it are many, many squares of the same size. Pablo Squarson puts one of the squ... | ```python
while True:
N = int(input())
w=[0]*N
h=[0]*N
wx=[-1,0,1,0]
hy=[0,-1,0,1]
if N == 0:
break
for i in range(1,N):
n,d = map(int,input().split())
w[i] = w[n]+wx[d]
h[i] = h[n]+hy[d]
print(max(w)-min(w)+1,max(h)-min(h)+1)
``` |
p00885 Balloon Collecting | "Balloons should be captured efficiently", the game designer says. He is designing an oldfashioned game with two dimensional graphics. In the game, balloons fall onto the ground one after another, and the player manipulates a robot vehicle on the ground to capture the balloons. The player can control the vehicle to mov... | ```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 ... |
p01016 Password | Taro had his own personal computer and set a password for login. However, Taro inadvertently forgot the password. Then, remembering that there was a piece of paper with the password written down, Taro found the paper and was surprised to see it. The paper was cut and there were only fragments, and there were some stain... | ```python
a = input()
b = input()
length_a = len(a)
length_b = len(b)
def check():
for i in range(length_a - length_b + 1):
for j in range(length_b):
if b[j] == "_" or a[i + j] == b[j]:continue
else:break
else:
print("Yes")
return
print("No")
... |
p01288 Marked Ancestor | You are given a tree T that consists of N nodes. Each node is numbered from 1 to N, and node 1 is always the root node of T. Consider the following two operations on T:
* M v: (Mark) Mark node v.
* Q v: (Query) Print the index of the nearest marked ancestor of node v which is nearest to it. Initially, only the root no... | ```python
def root(x):
while P[x] != x:
x = P[x]
return x
def mark(x):
P[x-1] = x-1
def query(x):
v = root(x-1) +1
return v
while True:
N,Q = map(int,input().strip().split(" "))
if N == Q == 0:
break
P = []
P.append(0)
for i in range(N-1):
p_i = int(input... |
p01457 Carpenters' Language | International Carpenters Professionals Company (ICPC) is a top construction company with a lot of expert carpenters. What makes ICPC a top company is their original language.
The syntax of the language is simply given in CFG as follows:
S -> SS | (S) | )S( | ε
In other words, a right parenthesis can be closed by a... | ```python
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 998244353
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split... |
p01769 Hopping Hearts | Problem statement
N-winged rabbit is on a balance beam of length L-1. The initial position of the i-th rabbit is the integer x_i, which satisfies 0 ≤ x_ {i} \ lt x_ {i + 1} ≤ L−1. The coordinates increase as you move to the right. Any i-th rabbit can jump to the right (ie, move from x_i to x_i + a_i) any number of tim... | ```python
def main():
MOD = 1000000007
n, l = map(int, input().split())
xlst = map(int, input().split())
alst = map(int, input().split())
can_use = []
for x, a in zip(xlst, alst):
if a == 0:s = {x}
else:s = {k for k in range(x, l, a)}
can_use.append(s)
dp = [[0] * l for _ in range(n)]
for... |
p02041 LISum | problem
Given the sequence $ A $ of length $ N $. Find the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $.
The longest increasing subsequence of the sequence $ A $ is the longest subsequence that satisfies $ A_i <A_j $ with all $ i <j $.
output
Outp... | ```python
import bisect
N = int(input())
A = list(map(int,input().split()))
lis = []
hist = []
for a in A:
i = bisect.bisect_left(lis,a)
if i == len(lis):
lis.append(a)
hist.append([a])
else:
lis[i] = a
hist[i].append(a)
ans = last = hist[-1][0]
for row in reversed(hist[:-... |
p02184 Canisar Cipher | C: Canisal cryptography
problem
Ebi-chan was given the string C obtained by encrypting a non-negative integer D with "canisal cipher". This cipher replaces each number in decimal notation with a fixed number (not necessarily different from the original). Different numbers will not be replaced with the same number, an... | ```python
# 半分全列挙
from itertools import permutations, combinations
M = int(input())
C = list(map(int, input()))
if len(C)==1 and M==0:
print(0)
exit()
mod = 10**9 + 7
L = [0] * 10
b = 1
for c in C[::-1]:
L[c] += b
b = b * 10 % mod
for t_half1 in combinations(range(10), 5):
L1, L2 = L[:5], L[5:]
... |
p02326 Largest Square | Given a matrix (H × W) which contains only 1 and 0, find the area of the largest square matrix which only contains 0s.
Constraints
* 1 ≤ H, W ≤ 1,400
Input
H W
c1,1 c1,2 ... c1,W
c2,1 c2,2 ... c2,W
:
cH,1 cH,2 ... cH,W
In the first line, two integers H and W separated by a space character are given. In the follo... | ```python
h,w=map(int,input().split())
grid=[list(map(int,input().split())) for i in range(h)]
def Largest_Square(grid):
h=len(grid);w=len(grid[0])
dp=[[0]*w for i in range(h)]
maxlenth=0
for i in range(h):
for j in range(w):
dp[i][j]=(grid[i][j]+1)%2
maxlenth=max(maxlen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.