name stringlengths 9 112 | description stringlengths 29 13k | solutions stringlengths 24 49.8k |
|---|---|---|
p00011 Drawing Lots | Let's play Amidakuji.
In the following example, there are five vertical lines and four horizontal lines. The horizontal lines can intersect (jump across) the vertical lines.
<image>
In the starting points (top of the figure), numbers are assigned to vertical lines in ascending order from left to right. At the first... | ```python
w = int(input()) + 1
l = [i for i in range(w)]
n = int(input())
for i in range(n):
a, b = map(int, input().split(","))
l[a], l[b] = l[b], l[a]
for i in range(1, w):
print(l[i])
``` |
p00143 Altair and Vega | Zhinü was a child of the Emperor, but he was weaving the machine even if he opened it at the request of his father.
It was a pleasure of the Emperor to wear clothes made of a splendid cloth called Unnishiki woven by Zhinü. Unnishiki has a short lifespan and deteriorates quickly, but there was no problem because the ha... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0143
"""
import sys
from sys import stdin
input = stdin.readline
from math import sqrt, atan2, acos, sin, cos
class Point(object):
epsilon = 1e-10
def __init__(self, x=0.0, y=0.0):
if isinstance(x, tuple):... |
p00276 Formation | At Akabe High School, which is a programmer training school, the roles of competition programmers in team battles are divided into the following three types.
C: | Coder | I am familiar with the language and code.
--- | --- | ---
A: | Algorithm | I am good at logical thinking and think about algorithms.
N: | Navigator |... | ```python
# -*- coding: utf-8 -*-
"""
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0281
"""
import sys
from sys import stdin
input = stdin.readline
def solve(c, a, n):
CCA, CCC, CAN = 0, 0, 0
CAN = min(c, a, n) # CAN??????????????°
c -= CAN
a -= CAN
if a > 0 and ... |
p00464 Walk | problem
One day, Taro, who lives in JOI town, decided to take a walk as a daily routine to improve his health. In JOI town, where Taro lives, he runs in the east-west direction as shown in the figure (H + 1). The road and the north-south direction (W + 1) run through the road in a grid pattern. Taro's house is at the ... | ```python
#!/usr/bin/env python
import string
import sys
from itertools import chain, takewhile
def read(
f, *shape, it=chain.from_iterable(sys.stdin), whitespaces=set(string.whitespace)
):
def read_word():
return f("".join(takewhile(lambda c: c not in whitespaces, it)).strip())
if not shape:
... |
p00654 Squid Multiplication | Problem H: Squid Multiplication
Squid Eiko loves mathematics. Especially she loves to think about integer. One day, Eiko found a math problem from a website.
"A sequence b ={ai + aj | i < j } is generated from a sequence a ={a0 , ... , an | ai is even if i is 0, otherwise ai is odd}. Given the sequence b , find the s... | ```python
# AOJ 1069: Squid Multiplication
# Python3 2018.7.10 bal4u
def gcd(a, b):
while b != 0:
r = a % b
a, b = b, r
return a
while True:
n = int(input())
if n == 0: break
even, odd = [], []
b = list(map(int, input().split()))
for i in b:
if i & 1: odd.append(i)
else: even.append(i)
even.sort()
od... |
p00930 Flipping Parentheses | Example
Input
6 3
((()))
4
3
1
Output
2
2
1 | ```python
from heapq import heappush, heappop, heapify
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, Q = map(int, readline().split())
INF = 2**31-1
LV = (N-1).bit_length()
N0 = 2**LV
data = [0]*(2*N0)
lazy = [0]*(2*N0)
L0 = [0]*(2*N0)
L1 = [0]*(2*N0... |
p01333 Summer of KMC | Description
KMC sells CDs every year at a coterie spot sale called Comic Market. F was supposed to sell CDs at the comic market, but due to the popularity of F, the KMC sales floor was flooded with people, and the calculation of change could not keep up. So F decided to write a program that would output the change as ... | ```python
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:break
w = b - a
x = w // 1000
w %= 1000
y = w // 500
w %= 500
z = w // 100
print(z, y, x)
``` |
p01813 An Equation in a Mine | Tunnel formula
One day while exploring an abandoned mine, you found a long formula S written in the mine. If you like large numbers, you decide to take out the choke and add `(` or `)` so that the result of the formula calculation is as large as possible. If it has to be a mathematical formula even after adding it, ho... | ```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 ... |
p02235 Longest Common Subsequence | For given two sequences $X$ and $Y$, a sequence $Z$ is a common subsequence of $X$ and $Y$ if $Z$ is a subsequence of both $X$ and $Y$. For example, if $X = \\{a,b,c,b,d,a,b\\}$ and $Y = \\{b,d,c,a,b,a\\}$, the sequence $\\{b,c,a\\}$ is a common subsequence of both $X$ and $Y$. On the other hand, the sequence $\\{b,c,a... | ```python
def lcs(x,y):
L=[]
for chk in y:
bg_i=0
for i,chr_i in enumerate(L):
cur_i=x.find(chk,bg_i)+1
if not cur_i:
break
L[i]=min(cur_i,chr_i)
bg_i=chr_i
else:
cur_i=x.find(chk,bg_i)+1
if cur_i:
... |
p02381 Standard Deviation | You have final scores of an examination for n students. Calculate standard deviation of the scores s1, s2 ... sn.
The variance α2 is defined by
α2 = (∑ni=1(si - m)2)/n
where m is an average of si. The standard deviation of the scores is the square root of their variance.
Constraints
* n ≤ 1000
* 0 ≤ si ≤ 100
Inpu... | ```python
import math
n = int(input())
while not n == 0:
ss = [float(i) for i in input().split(' ')]
m = sum(ss)/n
a2 = sum([(i-m)**2 for i in ss]) / n
print(math.sqrt(a2))
n = int(input())
``` |
1006_A. Adjacent Replacements | Mishka got an integer array a of length n as a birthday present (what a surprise!).
Mishka doesn't like this present and wants to change it somehow. He has invented an algorithm and called it "Mishka's Adjacent Replacements Algorithm". This algorithm can be represented as a sequence of steps:
* Replace each occurre... | ```python
if __name__ == "__main__":
_ = int(input())
arr = [int(num) for num in input().split()]
for i in arr:
if i % 2 == 0:
print(i - 1, end=" ")
else:
print(i, end=" ")
``` |
1029_F. Multicolored Markers | There is an infinite board of square tiles. Initially all tiles are white.
Vova has a red marker and a blue marker. Red marker can color a tiles. Blue marker can color b tiles. If some tile isn't white then you can't use marker of any color on it. Each marker must be drained completely, so at the end there should be e... | ```python
a, b = map(int,input().split())
ad = []
for i in range(1,a+1):
if i*i > a:
break
if a % i == 0:
ad.append(i)
if i*i != a:
ad.append(a//i)
bd = []
for i in range(1,b+1):
if i*i > b:
break
if b % i == 0:
bd.append(i)
if i*i != b:
bd.append(b//i)
ab = a+b
abd = []
for i in range(1,ab+1):
i... |
1073_A. Diverse Substring | You are given a string s, consisting of n lowercase Latin letters.
A substring of string s is a continuous segment of letters from s. For example, "defor" is a substring of "codeforces" and "fors" is not.
The length of the substring is the number of letters in it.
Let's call some string of length n diverse if and o... | ```python
length=int(input())
def AllSubsets(s) : # accepts a string , returns a list of all non empty subsets
l=[]
for i in range (len(s)) :
if i <len(s)-1:
for j in range (i+2,len(s)+1):
l+=[s[i:j]]
else :
l+=[s[i]]
return l
#print(AllSubsets("string"))
def diverse(st) : # accepts string , re... |
1095_A. Repeating Cipher | Polycarp loves ciphers. He has invented his own cipher called repeating.
Repeating cipher is used for strings. To encrypt the string s=s_{1}s_{2} ... s_{m} (1 ≤ m ≤ 10), Polycarp uses the following algorithm:
* he writes down s_1 ones,
* he writes down s_2 twice,
* he writes down s_3 three times,
* ...
... | ```python
try:
t = int(input())
s = input()
_ = 1
i = 0
l = []
while((i)<=(len(s)-1)):
#print(i)
l.append(s[i])
_+=1
i = i+_
s = "".join(l)
print(s)
except:
pass
``` |
1114_B. Yet Another Array Partitioning Task | An array b is called to be a subarray of a if it forms a continuous subsequence of a, that is, if it is equal to a_l, a_{l + 1}, …, a_r for some l, r.
Suppose m is some known constant. For any array, having m or more elements, let's define it's beauty as the sum of m largest elements of that array. For example:
* ... | ```python
from operator import itemgetter
from itertools import accumulate
from sys import stdin, stdout
n, m, k = [int(x) for x in stdin.readline().split()]
a = [int(x) for x in stdin.readline().split()]
id = [x for x in range(n)]
b = list(zip(a, id))
a.sort(reverse = True)
b.sort(reverse = True)
c = [p[1] for p in b[... |
1142_C. U2 | Recently Vasya learned that, given two points with different x coordinates, you can draw through them exactly one parabola with equation of type y = x^2 + bx + c, where b and c are reals. Let's call such a parabola an U-shaped one.
Vasya drew several distinct points with integer coordinates on a plane and then drew an... | ```python
import sys
def cross(o, a, b):
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
N = int(input())
A = [None]*N
for i in range(N):
x, y = map(int, sys.stdin.readline().split())
A[i] = (x, y-x*x)
A.sort()
upper = []
for p in reversed(A):
while len(upper) >= 2 and cross(upper[... |
1162_E. Thanos Nim | Alice and Bob are playing a game with n piles of stones. It is guaranteed that n is an even number. The i-th pile has a_i stones.
Alice and Bob will play a game alternating turns with Alice going first.
On a player's turn, they must choose exactly n/2 nonempty piles and independently remove a positive number of stone... | ```python
n = int(input())
L = [int(i) for i in input().split()]
s = 0
m = L[0]
for i in L:
if i == 1:
s += 1
if i < m:
m = i
if s > n // 2:
print('Bob')
elif s <= n // 2 and s > 0:
print('Alice')
elif s == 0:
ss = 0
for j in L:
if j == m:
ss += 1
if ss <... |
1183_D. Candy Box (easy version) | This problem is actually a subproblem of problem G from the same contest.
There are n candies in a candy box. The type of the i-th candy is a_i (1 ≤ a_i ≤ n).
You have to prepare a gift using some of these candies with the following restriction: the numbers of candies of each type presented in a gift should be all di... | ```python
q=int(input())
for i in range(q):
n=int(input())
a=list(map(int,input().split()))
counts=[0]*(len(a)+1)
ans=0
for i in range(len(a)):
counts[a[i]]+=1
counts.sort(reverse=True)
w=counts[0]+1
for i in counts:
w=max(min(w-1,i),0)
ans+=w
print(ans)
``` |
1200_E. Compress Words | Amugae has a sentence consisting of n words. He want to compress this sentence into one word. Amugae doesn't like repetitions, so when he merges two words into one word, he removes the longest prefix of the second word that coincides with a suffix of the first word. For example, he merges "sample" and "please" into "sa... | ```python
from sys import stdin, stdout
def compresswords(n, words):
a = []
for c in words[0]:
a.append(c)
for i in range(1, len(words)):
lps = getlps(words[i])
#print(lps)
idx = getsuffixmatchIdx(a, words[i], lps)
#print(idx)
#if idx == -1:
# ... |
1261_D1. Wrong Answer on test 233 (Easy Version) | Your program fails again. This time it gets "Wrong answer on test 233"
.
This is the easier version of the problem. In this version 1 ≤ n ≤ 2000. You can hack this problem only if you solve and lock both problems.
The problem is about a test containing n one-choice-questions. Each of the questions contains k options... | ```python
def main():
M=998244353
n,k,*h=map(int,open(0).read().split())
m=sum(i!=j for i,j in zip(h,h[1:]+h[:1]))
f=[0]*(m+1)
f[0]=b=1
for i in range(1,m+1):f[i]=b=b*i%M
inv=[0]*(m+1)
inv[m]=b=pow(f[m],M-2,M)
for i in range(m,0,-1):inv[i-1]=b=b*i%M
comb=lambda n,k:f[n]*inv[n-k]*... |
1283_F. DIY Garland | Polycarp has decided to decorate his room because the New Year is soon. One of the main decorations that Polycarp will install is the garland he is going to solder himself.
Simple garlands consisting of several lamps connected by one wire are too boring for Polycarp. He is going to solder a garland consisting of n lam... | ```python
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, ... |
1303_B. National Project | Your company was appointed to lay new asphalt on the highway of length n. You know that every day you can either repair one unit of the highway (lay new asphalt over one unit of the highway) or skip repairing.
Skipping the repair is necessary because of the climate. The climate in your region is periodical: there are ... | ```python
def ceil(a):
if(a//1 == a):
return int(a)
else:
return(int(a)+1)
for i in range(0,int(input())):
n,g,b = list(map(int, input().split()))
if(g>=b):
print(n)
else:
u = ceil(n/2)
# print(u)
k = ceil((u)/g) - 1
# print(k)
if(k*(g+... |
1327_C. Game with Chips | Petya has a rectangular Board of size n × m. Initially, k chips are placed on the board, i-th chip is located in the cell at the intersection of sx_i-th row and sy_i-th column.
In one action, Petya can move all the chips to the left, right, down or up by 1 cell.
If the chip was in the (x, y) cell, then after the oper... | ```python
n,m,k=map(int, input().split())
for i in range(2*k):
map(int, input().split())
ans = (m-1)*'L' + (n-1)*'U'
for i in range(n):
if i%2==0:
ans += 'R'*(m-1)
else:
ans += 'L'*(m-1)
if i < n-1:
ans+='D'
print(len(ans))
print(ans)
``` |
1368_C. Even Picture | Leo Jr. draws pictures in his notebook with checkered sheets (that is, each sheet has a regular square grid printed on it). We can assume that the sheets are infinitely large in any direction.
To draw a picture, Leo Jr. colors some of the cells on a sheet gray. He considers the resulting picture beautiful if the follo... | ```python
import sys
def minp():
return sys.stdin.readline().strip()
def mint():
return int(minp())
def mints():
return map(int, minp().split())
def solve():
n = mint()
print((n+1)*3+1)
for i in range(n+1):
print(i,i)
print(1+i,i)
print(i,1+i)
print(n+1,n+1)
#for i in range(mint()):
solve()
``` |
1389_E. Calendar Ambiguity | Berland year consists of m months with d days each. Months are numbered from 1 to m. Berland week consists of w days. The first day of the year is also the first day of the week. Note that the last week of the year might be shorter than w days.
A pair (x, y) such that x < y is ambiguous if day x of month y is the same... | ```python
import sys
input = sys.stdin.readline
aaaa = list()
for kek in range(int(input())):
(m, d, w) = map(int, input().split())
g = min(m,d)
d -=1
i = 2
while i < d**(1/2)+2:
if d % i == 0:
d //= i
if w % i == 0:
w //= i
else:
i... |
140_B. New Year Cards | As meticulous Gerald sets the table, Alexander finished another post on Codeforces and begins to respond to New Year greetings from friends. Alexander has n friends, and each of them sends to Alexander exactly one e-card. Let us number his friends by numbers from 1 to n in the order in which they send the cards. Let's ... | ```python
n = int(input())
arr = [list(map(int, input().split())) for _ in range(n+1)]
res = [0] * n
for i in range(n):
p = [0] * (n+1)
for j in range(n):
p[arr[i][j]] = j
u, t, b = 0, int(1e5), int(1e5)
for x in arr[n]:
if x != i+1 and x < b:
if p[x] < t:
u... |
1430_F. Realistic Gameplay | Recently you've discovered a new shooter. They say it has realistic game mechanics.
Your character has a gun with magazine size equal to k and should exterminate n waves of monsters. The i-th wave consists of a_i monsters and happens from the l_i-th moment of time up to the r_i-th moments of time. All a_i monsters spa... | ```python
from bisect import *
from collections import *
from math import *
from heapq import *
from typing import List
from itertools import *
from operator import *
from functools import *
#------------------------------------------------------------------------
import os
import sys
from io import BytesIO, IOBase
# ... |
1454_B. Unique Bid Auction | There is a game called "Unique Bid Auction". You can read more about it here: https://en.wikipedia.org/wiki/Unique_bid_auction (though you don't have to do it to solve this problem).
Let's simplify this game a bit. Formally, there are n participants, the i-th participant chose the number a_i. The winner of the game is... | ```python
t=int(input())
for i in range(t):
n=int(input())
l=list(map(int,input().split()))
d={}
for i in range(len(l)):
if l[i] in d:
d[l[i]].append(i+1)
else:
d[l[i]]=[i+1]
a=[]
flag=0
for i in d:
if len(d[i])==1:
flag=1
... |
1505_B. DMCA | Many people are aware of DMCA – Digital Millennium Copyright Act. But another recently proposed DMCA – Digital Millennium Calculation Act – is much less known.
In this problem you need to find a root of a number according to this new DMCA law.
Input
The input contains a single integer a (1 ≤ a ≤ 1000000).
Output
O... | ```python
n = int(input())
sumo = n
while n>=10:
sumo = 0
while n!=0:
sumo+=n%10
n//=10
n = sumo
print(sumo)
``` |
1528_C. Trees of Tranquillity | Soroush and Keshi each have a labeled and rooted tree on n vertices. Both of their trees are rooted from vertex 1.
Soroush and Keshi used to be at war. After endless decades of fighting, they finally became allies to prepare a Codeforces round. To celebrate this fortunate event, they decided to make a memorial graph o... | ```python
from __future__ import print_function
import sys
import traceback
from bisect import bisect_left, bisect_right, insort
from itertools import chain, repeat, starmap
from math import log
from operator import add, eq, ne, gt, ge, lt, le, iadd
from textwrap import dedent
try:
from collections.abc import ... |
15_B. Laser | Petya is the most responsible worker in the Research Institute. So he was asked to make a very important experiment: to melt the chocolate bar with a new laser device. The device consists of a rectangular field of n × m cells and a robotic arm. Each cell of the field is a 1 × 1 square. The robotic arm has two lasers po... | ```python
n = int(input())
for i in range(n):
n, m, x1, y1, x2, y2 = map(int, input().split())
#print(n, m, x1, y1, x2, y2)
if x1 <= x2 and y1 <= y2:
pass
elif x1 >= x2 and y1 >= y2:
x1, y1, x2, y2 = x2, y2, x1, y1
else:
x1, y1, x2, y2 = x2, y1, x1, y2
if x1 <= x2 ... |
201_E. Thoroughly Bureaucratic Organization | Once n people simultaneously signed in to the reception at the recently opened, but already thoroughly bureaucratic organization (abbreviated TBO). As the organization is thoroughly bureaucratic, it can accept and cater for exactly one person per day. As a consequence, each of n people made an appointment on one of the... | ```python
def go(m, k):
rem, ans, binom = m*k, 0, 1
ones = 0
while ones <= k:
take = min(1 if ones == 0 else rem//ones, binom)
if take == 0:
break
ans += take
rem -= ones * take
binom = binom*(k-ones)//(ones+1)
ones += 1
return ans
def solve():
n, m = map(int, input().split())
ans = 1;
while go(... |
226_D. The table | Harry Potter has a difficult homework. Given a rectangular table, consisting of n × m cells. Each cell of the table contains the integer. Harry knows how to use two spells: the first spell change the sign of the integers in the selected row, the second — in the selected column. Harry's task is to make non-negative the ... | ```python
import math
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
a = [[] for _ in range(n)]
for i in range(n):
a[i] = [int(_) for _ in input().split()]
row = []
col = []
rowStat = [1] * n
colStat = [1] * m
while True:
bad = False
for i in range(n):
total = 0
for j... |
250_B. Restoring IPv6 | An IPv6-address is a 128-bit number. For convenience, this number is recorded in blocks of 16 bits in hexadecimal record, the blocks are separated by colons — 8 blocks in total, each block has four hexadecimal digits. Here is an example of the correct record of a IPv6 address: "0124:5678:90ab:cdef:0124:5678:90ab:cdef".... | ```python
for i in range(int(input())):
t = input().split(':')
if t[-1] == '': t.pop()
elif t[0] == '': t.pop(0)
if '' in t: t[t.index('')] = ('0000:' * (9 - len(t)))[: -1]
print(':'.join('0' * (4 - len(i)) + i for i in t))
``` |
275_C. k-Multiple Free Set | A k-multiple free set is a set of integers where there is no pair of integers where one is equal to another integer multiplied by k. That is, there are no two integers x and y (x < y) from the set, such that y = x·k.
You're given a set of n distinct positive integers. Your task is to find the size of it's largest k-mu... | ```python
def solve():
n,k=map(int,input().split())
a=sorted([int(i) for i in input().split()])
b=set(a)
if k!=1:
for i in a:
if i in b:
b.discard(i*k)
print(len(b))
solve()
``` |
346_A. Alice and Bob | It is so boring in the summer holiday, isn't it? So Alice and Bob have invented a new game to play. The rules are as follows. First, they get a set of n distinct integers. And then they take turns to make the following moves. During each move, either Alice or Bob (the player whose turn is the current) can choose two di... | ```python
from sys import stdin,stdout
from math import gcd
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
n=nmbr()
a=lst()
g=a[0]
for v in a[1:]:
g=gcd(g,v)
mx=max(a)
terms=abs(n-mx//g)
print('Alice' if terms&1 ... |
440_B. Balancer | Petya has k matches, placed in n matchboxes lying in a line from left to right. We know that k is divisible by n. Petya wants all boxes to have the same number of matches inside. For that, he can move a match from its box to the adjacent one in one move. How many such moves does he need to achieve the desired configura... | ```python
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write i... |
462_D. Appleman and Tree | Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white.
Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree... | ```python
n = int(input())
edges = [int(x) for x in input().split()]
color = [int(x) for x in input().split()]
graph = [[] for _ in range(n)]
for a,b in enumerate(edges):
graph[a+1].append(b)
graph[b].append(a+1)
dp = [[0]*2 for _ in range(n)]
visited = [0]*n
stack = [0]
while stack:
v = stack[-1]
vis... |
486_C. Palindrome Transformation | Nam is playing with a string on his computer. The string consists of n lowercase English letters. It is meaningless, so Nam decided to make the string more beautiful, that is to make it be a palindrome by using 4 arrow keys: left, right, up, down.
There is a cursor pointing at some symbol of the string. Suppose that c... | ```python
import sys
input=sys.stdin.readline
n,p=map(int,input().split())
s=input().rstrip()
if p>=n//2:
s=s[::-1]
p=n+1-p
p-=1
ans1=0;ans2=0
l=10**6;r=-1
for i in range(n//2):
if s[i]!=s[n-1-i]:
l=min(l,i)
r=max(r,i)
use=set()
if l<=p<=r:
if r!=-1:
for i in range(p,r+1):
if s[i]!=s[n-1-i] an... |
50_B. Choosing Symbol Pairs | There is a given string S consisting of N symbols. Your task is to find the number of ordered pairs of integers i and j such that
1. 1 ≤ i, j ≤ N
2. S[i] = S[j], that is the i-th symbol of string S is equal to the j-th.
Input
The single input line contains S, consisting of lowercase Latin letters and digits. It is ... | ```python
'''
Solução de Problemas Computacionais - 2017/01
Carolina Coimbra Vieira - 2014032941
PROBLEMA: Choosing Symbol Pairs (Codeforces_CF50B)
O problema consiste em ler uma string S de tamanho N e determinar a quantidade de pares (i,j)
que podem ser formados de forma que 1 <= i, j <= N e S[i] = S[j]. Como os ca... |
534_D. Handshakes | On February, 30th n students came in the Center for Training Olympiad Programmers (CTOP) of the Berland State University. They came one by one, one after another. Each of them went in, and before sitting down at his desk, greeted with those who were present in the room by shaking hands. Each of the students who came in... | ```python
def read_int():
return int(input().strip())
def read_ints():
return list(map(int, input().strip().split(' ')))
def solve():
"""
4 2 1 3 5
0 2 3 4 1 1 0 2 2
x x x x x x x x x
1 5 8 3 4 2 7 6 9
10
0 3 4 2
0 1 2 3 4 5
"""
N = read_int()
shakes = [[] for _ in rang... |
585_B. Phillip and Trains | The mobile application store has a new game called "Subway Roller".
The protagonist of the game Philip is located in one end of the tunnel and wants to get out of the other one. The tunnel is a rectangular field consisting of three rows and n columns. At the beginning of the game the hero is in some cell of the leftmo... | ```python
# import sys
# sys.stdin = open('cf586d.in')
def handle_test():
n, k = [int(v) for v in input().split()]
field = [input() for _ in range(3)]
if field[0][0] == 's':
cpos = [0, 0]
elif field[1][0] == 's':
cpos = [1, 0]
else:
cpos = [2, 0]
available = [[False] * len(field[0]) for _... |
607_B. Zuma | Genos recently installed the game Zuma on his phone. In Zuma there exists a line of n gemstones, the i-th of which has color ci. The goal of the game is to destroy all the gemstones in the line as quickly as possible.
In one second, Genos is able to choose exactly one continuous substring of colored gemstones that is ... | ```python
dp=[]
def calculate(i,j,colors):
if i>j: return 0
if dp[i][j]==-1:
if i==j:
return 1
dp[i][j] = 10000
dp[i][j] = min(dp[i][j],1+calculate(i+1,j,colors))
# print(i,j)
if colors[i]==colors[i+1]:
dp[i][j] = min(dp[i][j],1+calculate(i+2,j,co... |
629_A. Far Relative’s Birthday Cake | Door's family is going celebrate Famil Doors's birthday party. They love Famil Door so they are planning to make his birthday cake weird!
The cake is a n × n square consisting of equal squares with side length 1. Each square is either empty or consists of a single chocolate. They bought the cake and randomly started t... | ```python
def fac(n):
S=1
for i in range(1,n+1):
S=S*i
return(S)
def comb(n,p):
return int((fac(n)/(fac(p)*fac(n-p))))
n=int(input())
d=[]
somme=0
for i in range(n):
ch=input()
d.append(ch)
S=0
for j in range(len(ch)):
if ch[j]=="C":
S=S+1
somme=somme+comb... |
653_B. Bear and Compressing | Limak is a little polar bear. Polar bears hate long strings and thus they like to compress them. You should also know that Limak is so young that he knows only first six letters of the English alphabet: 'a', 'b', 'c', 'd', 'e' and 'f'.
You are given a set of q possible operations. Limak can perform them in any order, ... | ```python
# You lost the game.
n, q = map(int, input().split())
L = [list(str(input()).split(" ")) for _ in range(q)]
A = [[] for _ in range(6)]
B = "abcdef"
for i in range(q):
e = B.index(L[i][1])
A[e] = A[e] + [L[i][0]]
R = [1,0,0,0,0,0]
for i in range(1,n):
K = [0,0,0,0,0,0]
for j in range(6):
... |
701_A. Cards | There are n cards (n is even) in the deck. Each card has a positive integer written on it. n / 2 people will play new card game. At the beginning of the game each player gets two cards, each card is given to exactly one player.
Find the way to distribute cards such that the sum of values written of the cards will be ... | ```python
n = int(input())
s = list(map(int, input().split()))
dif = 2 * sum(s) // n
t = []
for i in range(n):
for j in range(n):
if s[i] + s[j] == dif and i not in t and j not in t and i != j:
print(i + 1, j + 1)
t.append(i)
t.append(j)
``` |
723_B. Text Document Analysis | Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters.
In this problem you should implement the similar functionality.
You are given a string which only consists of:
* uppercase and lowercase English... | ```python
length = int(input())
string = input()
outer = ""
inner = ""
i = 0
while i < length:
if string[i] == '(':
i += 1
inner += " "
while string[i] != ')':
if string[i] != '_' and string[i] != '&':
inner += string[i]
else:
inner +=... |
745_A. Hongcow Learns the Cyclic Shift | Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word.
Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ... | ```python
from collections import Counter
s = input()
counter = Counter()
for i in range(len(s)):
counter[s[i:len(s)] + s[0:i]] = 1
print(sum(counter.values()))
``` |
768_C. Jon Snow and his Favourite Number | Jon Snow now has to fight with White Walkers. He has n rangers, each of which has his own strength. Also Jon Snow has his favourite number x. Each ranger can fight with a white walker only if the strength of the white walker equals his strength. He however thinks that his rangers are weak and need to improve. Jon now t... | ```python
n,k,x=map(int,input().split())
r=list(map(int,input().split()))
k%=64
while k:
k-=1
r.sort()
for i in range(0,n,2):#alternate
r[i]^=x
print(max(r),min(r))
``` |
792_B. Counting-out Rhyme | n children are standing in a circle and playing the counting-out game. Children are numbered clockwise from 1 to n. In the beginning, the first child is considered the leader. The game is played in k steps. In the i-th step the leader counts out ai people in clockwise order, starting from the next person. The last one ... | ```python
n,y=input().split()
n=int(n)
y=int(y)
liste=list(range(1,n+1))
x=0
z=0
liste2=list(map(int,input().split()))
while x<y:
z=((z+liste2[x])%len(liste))
print(liste[z])
liste.pop(z)
x+=1
``` |
812_D. Sagheer and Kindergarten | Sagheer is working at a kindergarten. There are n children and m different toys. These children use well-defined protocols for playing with the toys:
* Each child has a lovely set of toys that he loves to play with. He requests the toys one after another at distinct moments of time. A child starts playing if and onl... | ```python
from sys import stdin
from sys import stdout
n, m, k, q = map(int, stdin.readline().split())
d = [None for i in range(m)]
roots = set(range(n))
matrix = [[] for i in range(n)]
for i in range(k):
x, y = map(int, stdin.readline().split())
if d[y - 1] is None:
d[y - 1] = x - 1
else:
... |
838_D. Airplane Arrangements | There is an airplane which has n rows from front to back. There will be m people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the pla... | ```python
MOD = 10 ** 9 + 7
n, m = input().split(' ')
n = int(n)
m = int(m)
ans = pow(2 * (n + 1), m, MOD)
ans = (ans * (n + 1 - m)) % MOD
ans = (ans * pow(n + 1, MOD - 2, MOD)) % MOD
print(ans)
``` |
859_A. Declined Finalists | This year, as in previous years, MemSQL is inviting the top 25 competitors from the Start[c]up qualification round to compete onsite for the final round. Not everyone who is eligible to compete onsite can afford to travel to the office, though. Initially the top 25 contestants are invited to come onsite. Each eligible ... | ```python
#!/usr/bin/python3
k = int(input())
a = set(map(int, input().split()))
c = 1
while len(a) < 25:
if c not in a:
a.add(c)
else:
c += 1
b = list(a)
b.sort()
ans = 0
y = 0
for x in b:
ans += x - y - 1
y = x
print(ans)
``` |
883_M. Quadcopter Competition | Polycarp takes part in a quadcopter competition. According to the rules a flying robot should:
* start the race from some point of a field,
* go around the flag,
* close cycle returning back to the starting point.
Polycarp knows the coordinates of the starting point (x1, y1) and the coordinates of the poin... | ```python
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
if x1 != x2 and y1 != y2:
ans = abs(x1 - x2) + abs(y1 - y2) + 2
print(ans * 2)
else:
ans = abs(x1 - x2) + abs(y1 - y2) + 3
print(ans * 2)
``` |
908_B. New Year and Buggy Bot | Bob programmed a robot to navigate through a 2d maze.
The maze has some obstacles. Empty cells are denoted by the character '.', where obstacles are denoted by '#'.
There is a single robot in the maze. Its start position is denoted with the character 'S'. This position has no obstacle in it. There is also a single ex... | ```python
res = 0
n, m = map(int, input().split())
a = ['#' * (m + 2)] + ['#' + input() + '#' for i in range(n)] + ['#' * (m + 2)]
s = input()
start = []
fin = []
for i in range(n + 2):
for j in range(m + 2):
if a[i][j] == 'S':
start = [i, j]
if a[i][j] == 'E':
fin = [i, j]
... |
92_A. Chips | There are n walruses sitting in a circle. All of them are numbered in the clockwise order: the walrus number 2 sits to the left of the walrus number 1, the walrus number 3 sits to the left of the walrus number 2, ..., the walrus number 1 sits to the left of the walrus number n.
The presenter has m chips. The presenter... | ```python
n, m = [int(x) for x in input().split()]
m %= int(n*(n+1)/2)
for i in range(1,n):
if m<i: break
m -= i
print(m)
``` |
958_A2. Death Stars (medium) | The stardate is 1983, and Princess Heidi is getting better at detecting the Death Stars. This time, two Rebel spies have yet again given Heidi two maps with the possible locations of the Death Star. Since she got rid of all double agents last time, she knows that both maps are correct, and indeed show the map of the so... | ```python
n, m = [int(x) for x in input().split()]
list1 = []
list2 = []
for i in range(n):
list1.append(input())
for j in range(m):
list2.append(input())
list3 = []
for i in range(n - m + 1):
y = ""
for j in range(m):
y += list1[j + i]
list3.append(y)
list4 = []
for i in range(n - m + 1)... |
983_A. Finite or not? | You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b is a finite fraction.
A fraction in notation with base b is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction ... | ```python
import sys
import math
ini = lambda: int(sys.stdin.readline())
inl = lambda: [int(x) for x in sys.stdin.readline().split()]
def solve():
p, q, b = inl()
if p == 0:
return True
g = math.gcd(p, q)
p //= g
q //= g
if q == 1:
return True
return pow(b, 64, q) == 0
n... |
p02564 AtCoder Library Practice Contest - SCC | You are given a directed graph with N vertices and M edges, not necessarily simple. The i-th edge is oriented from the vertex a_i to the vertex b_i. Divide this graph into strongly connected components and print them in their topological order.
Constraints
* 1 \leq N \leq 500,000
* 1 \leq M \leq 500,000
* 0 \leq a_i,... | ```python
class csr:
def __init__(self,N,edges):
self.start = [0]*(N+1)
self.elist = [0]*len(edges)
for e in edges:
self.start[e[0]+1] += 1
for i in range(1,N+1):
self.start[i] += self.start[i-1]
counter = self.start[:]
for e in edges:
... |
p02695 AtCoder Beginner Contest 165 - Many Requirements | Given are positive integers N, M, Q, and Q quadruples of integers ( a_i , b_i , c_i , d_i ).
Consider a sequence A satisfying the following conditions:
* A is a sequence of N positive integers.
* 1 \leq A_1 \leq A_2 \le \cdots \leq A_N \leq M.
Let us define a score of this sequence as follows:
* The score is the ... | ```python
from itertools import combinations_with_replacement as comb
n,m,q = map(int,input().split())
ans = 0
query = [[int(i) for i in input().split()] for _ in range(q)]
for A in comb(range(1,m+1),n):
cnt = 0
for i in range(q):
a,b,c,d = query[i]
if A[b-1]-A[a-1] == c: cnt += d
ans = max(... |
p02824 AtCoder Grand Contest 041 - Voting Judges | N problems are proposed for an upcoming contest. Problem i has an initial integer score of A_i points.
M judges are about to vote for problems they like. Each judge will choose exactly V problems, independently from the other judges, and increase the score of each chosen problem by 1.
After all M judges cast their vo... | ```python
import sys
read = sys.stdin.buffer.read
input = sys.stdin.buffer.readline
inputs = sys.stdin.buffer.readlines
# mod=10**9+7
# rstrip().decode('utf-8')
# map(int,input().split())
#import numpy as np
def main():
n,m,v,p=map(int,input().split())
A=list(map(int,input().split()))
A.sort(reverse=True)
teki=... |
p02960 AtCoder Beginner Contest 135 - Digits Parade | Given is a string S. Each character in S is either a digit (`0`, ..., `9`) or `?`.
Among the integers obtained by replacing each occurrence of `?` with a digit, how many have a remainder of 5 when divided by 13? An integer may begin with 0.
Since the answer can be enormous, print the count modulo 10^9+7.
Constraints... | ```python
M = 10**9 + 7
a = [1] + [0] * 12
p = 1
for c in reversed(input()):
r = range(10) if c == '?' else (int(c),)
a = [sum(a[(i - p * j) % 13] for j in r) % M for i in range(13)]
p = p * 10 % 13
print(a[5])
``` |
p03096 AtCoder Grand Contest 031 - Reversi | There are N stones arranged in a row. The i-th stone from the left is painted in the color C_i.
Snuke will perform the following operation zero or more times:
* Choose two stones painted in the same color. Repaint all the stones between them, with the color of the chosen stones.
Find the number of possible final s... | ```python
from collections import defaultdict
import sys
input = sys.stdin.buffer.readline
mod = 10**9+7
N = int(input())
dp = [0] * (N+1)
dp[0] = 1
prev = defaultdict(lambda: -1)
for i in range(1, N+1):
c = int(input())
dp[i] = dp[i-1]
if prev[c] >= 0:
if prev[c] != i-1:
dp[i] = (dp[i]... |
p03242 AtCoder Beginner Contest 111 - AtCoder Beginner Contest 999 | Cat Snuke is learning to write characters. Today, he practiced writing digits `1` and `9`, but he did it the other way around.
You are given a three-digit integer n written by Snuke. Print the integer obtained by replacing each digit `1` with `9` and each digit `9` with `1` in n.
Constraints
* 111 \leq n \leq 999
* ... | ```python
s = input()
print(s.translate(str.maketrans({"1": "9", "9": "1"})))
``` |
p03395 AtCoder Grand Contest 022 - Remainder Game | Aoki is playing with a sequence of numbers a_{1}, a_{2}, ..., a_{N}. Every second, he performs the following operation :
* Choose a positive integer k. For each element of the sequence v, Aoki may choose to replace v with its remainder when divided by k, or do nothing with v. The cost of this operation is 2^{k} (regar... | ```python
# -*- coding: utf-8 -*-
def inpl(): return tuple(map(int, input().split()))
N = int(input())
A = inpl()
B = inpl()
for a, b in zip(A, B):
if a < b:
print(-1)
exit()
M = max(max(A), max(B))
S = [i for i in range(1, M+1)]
T = len(S)
def dfs(a, b, G):
visited = [False]*(M+1)
... |
p03559 AtCoder Regular Contest 084 - Snuke Festival | The season for Snuke Festival has come again this year. First of all, Ringo will perform a ritual to summon Snuke. For the ritual, he needs an altar, which consists of three parts, one in each of the three categories: upper, middle and lower.
He has N parts for each of the three categories. The size of the i-th upper ... | ```python
def main(n,a,b,c):
import bisect
ans=0
for i in range(n):
na=bisect.bisect_left(a,b[i])
nc=n-bisect.bisect_right(c,b[i])
ans+=na*nc
print(ans)
if __name__=='__main__':
n=int(input())
a=sorted(list(map(int,input().split())))
b=sorted(list(map(int,input().split())))
c=sorted(list(map... |
p03713 AtCoder Beginner Contest 062 - Chocolate Bar | There is a bar of chocolate with a height of H blocks and a width of W blocks. Snuke is dividing this bar into exactly three pieces. He can only cut the bar along borders of blocks, and the shape of each piece must be a rectangle.
Snuke is trying to divide the bar as evenly as possible. More specifically, he is trying... | ```python
h,w = sorted(list(map(int,input().split())))
if h % 3 == 0 or w % 3 == 0:
ans = 0
else:
c1 = ((w//3+1)*h)-((w-1-w//3)*(h//2))
c2 = ((w-w//3)*(h-h//2))-(w//3*h)
c3 = h
c4 = ((h//3+1)*w)-((h-1-h//3)*(w//2))
c5 = ((h-h//3)*(w-w//2))-(h//3*w)
ans = min(c1,c2,c3,c4,c5)
print(ans)
``` |
p03874 CODE FESTIVAL 2016 Grand Final - FESTIVAL | Welcome to CODE FESTIVAL 2016! In order to celebrate this contest, find a string s that satisfies the following conditions:
* The length of s is between 1 and 5000, inclusive.
* s consists of uppercase letters.
* s contains exactly K occurrences of the string "FESTIVAL" as a subsequence. In other words, there are exac... | ```python
import math
import sys
input = sys.stdin.readline
k = int(input())
n = 512
pattern = 0
a = []
for i in range(n):
val = math.factorial(7 + i) // math.factorial(i) // math.factorial(7)
a.append(val)
a.reverse()
cnt = 600 * 7
ans = ["FESTIVA" for _ in range(n)]
for i, item in enumerate(a):
ans[i]... |
p04035 AtCoder Grand Contest 002 - Knot Puzzle | We have N pieces of ropes, numbered 1 through N. The length of piece i is a_i.
At first, for each i (1≤i≤N-1), piece i and piece i+1 are tied at the ends, forming one long rope with N-1 knots. Snuke will try to untie all of the knots by performing the following operation repeatedly:
* Choose a (connected) rope with a... | ```python
N, L = map(int, input().split())
a = [int(x) for x in input().split()]
ans = False
for i in range(N-1):
if a[i] + a[i+1] >= L:
ans = True
break
if ans:
print('Possible')
for j in range(i):
print(j+1)
for j in range(N-2, i-1, -1):
print(j+1)
else:
print('Imp... |
p00117 A reward for a Carpenter | One day, the lord ordered a carpenter to "build a sturdy and large building where the townspeople could evacuate in the event of a typhoon or earthquake." However, large thick pillars are needed to complete the sturdy and large building. There is no such big pillar in the town. So the carpenter decided to go to a dista... | ```python
import sys
n = int(input())
m = int(input())
cost = [[float("inf")] * n for _ in range(n)]
for _ in range(m):
a, b, c, d = map(int, sys.stdin.readline().split(","))
cost[a - 1][b - 1] = c
cost[b - 1][a - 1] = d
s, g, V, P = map(int, sys.stdin.readline().split(","))
for k in range(n):
for i in... |
p00250 Scone | Aika's house runs a small coffee shop. The scones baked by Aika's mother were very delicious and the shop was very prosperous.
One of the jobs of Aika, a waitress, is to deliver the scones that are baked one after another to the customer's seat. The baked scones are placed on a tray and lined up on the counter. Let Ki... | ```python
# AOJ 0254: Scone
# Python3 2018.6.25 bal4u
s = [0 for i in range(30001)]
while True:
n, m = map(int, input().split())
if n == 0: break
f = [-1 for i in range(m)]
sum, nmax, ans = 0, 0, 0
a = list(map(int, input().split()))
for i in range(n):
sum += a[i]
a[i] %= m
if a[i] > nmax: nmax = a[i]
if... |
p00431 String With Rings | Consider a string with rings on both ends. Rings have positive integers to distinguish them. Rings on both ends of the string have different numbers a and b. Describe this as [a, b]. If there are multiple strings and the number attached to the ring of one string and the other string is the same, these strings can be co... | ```python
def solve():
def dfs(ring, chain_len=1):
unchecked[ring] = False
unvisited[ring] = False
len_rec[ring] = max(len_rec[ring], chain_len)
for r in adj_list[ring]:
if unvisited[r]:
dfs(r, chain_len + 1)
unvisited[ring] = True
import ... |
p00627 Kyudo: A Japanese Art of Archery | Ito joined the Kyudo club after entering high school. At first, I had a hard time because the arrow didn't reach the target, but in the fall of my first year of high school, I managed to improve to the point where the arrow reached the target.
One day, my senior Kato suggested, "Why don't you participate in a recent K... | ```python
# AOJ 1041: Kyudo: A Japanese Art of Archery
# Python3 2018.7.6 bal4u
while True:
n = int(input())
if n == 0: break
print(sum([int(input()) for i in range(n>>2)]))
``` |
p00771 Anchored Balloon | Anchored Balloon
A balloon placed on the ground is connected to one or more anchors on the ground with ropes. Each rope is long enough to connect the balloon and the anchor. No two ropes cross each other. Figure E-1 shows such a situation.
<image>
Figure E-1: A balloon and ropes on the ground
Now the balloon takes o... | ```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 ... |
p01035 Hard Beans | Problem
Beans are popular at Otsu University. N beans are lined up in a straight line. Each is numbered from 0 to N-1, and the hardness of the i-th bean is ai.
Cyan considers the ideal bean hardness to be D. However, Cyan doesn't want to go get the beans that are too far away because he is troublesome. Therefore, Cya... | ```python
class SegmentTree(object):
def __init__(self, a:list, default: int, op):
from math import ceil, log
real_size = len(a)
self.elem_size = elem_size = 1<<ceil(log(real_size, 2))
self.tree = tree = [default] * (elem_size * 2)
tree[elem_size:elem_size + real_size] = a
... |
p01634 Register Phase | It is important to use strong passwords to make the Internet more secure. At the same time, it is very important not to reuse the same password. No matter how strong your password is, if the plaintext is leaked in one place, it will be very easy to break. Of course, if all applications hash passwords and use SALT prope... | ```python
A=0
n=str(input())
if len(n)>=6:
A=A+1
B=n.count('0')+n.count('1')+n.count('2')+n.count('3')+n.count('4')+n.count('5')+n.count('6')+n.count('7')+n.count('8')+n.count('9')
if B>0:
A=A+1
C=n.count('a')+n.count('b')+n.count('c')+n.count('d')+n.count('e')+n.count('f')+n.count('g')+n.count('h')+n.count('i'... |
p02201 Ninja E869120 | Increasing E869120 (Ninja E869120)
E869120 You are good at alter ego.
Here are $ N $ members of the PA Lab. But some of them may be E869120.
So you asked all the $ N $ members of the PA Lab for their names. As a result, the $ N $ members named themselves $ S_1, S_2, S_3, \ dots, S_N $, respectively.
E869120 How man... | ```python
import sys
input = sys.stdin.readline
N=int(input())
ANS=0
for i in range(N):
if input().strip()=="E869120":
ANS+=1
print(ANS)
``` |
p02355 The Smallest Window II | For a given array $a_1, a_2, a_3, ... , a_N$ of $N$ elements and an integer $K$, find the smallest sub-array size (smallest window length) where the elements in the sub-array contains all integers in range [$1, 2, ..., K$]. If there is no such sub-array, report 0.
Constraints
* $1 \leq N \leq 10^5$
* $1 \leq K \leq 1... | ```python
class SegmentTree():
def __init__(self, arr, func=min, ie=2**63):
self.h = (len(arr) - 1).bit_length()
self.n = 2**self.h
self.ie = ie
self.func = func
self.tree = [ie for _ in range(2 * self.n)]
for i in range(len(arr)):
self.tree[self.n + i] = ... |
1040_A. Palindrome Dance | A group of n dancers rehearses a performance for the closing ceremony. The dancers are arranged in a row, they've studied their dancing moves and can't change positions. For some of them, a white dancing suit is already bought, for some of them — a black one, and for the rest the suit will be bought in the future.
On ... | ```python
def go():
n, a, b = [int(i) for i in input().split(' ')]
x = [int(i) for i in input().split(' ')]
total = 0
for i in range(n // 2):
if (x[i] == 1 and x[n - 1 - i] == 0) or (x[i] == 0 and x[n - 1 - i] == 1):
return -1
elif x[i] == 2 and x[i] == x[n - 1 - i]:
... |
1063_A. Oh Those Palindromes | A non-empty string is called palindrome, if it reads the same from the left to the right and from the right to the left. For example, "abcba", "a", and "abba" are palindromes, while "abab" and "xy" are not.
A string is called a substring of another string, if it can be obtained from that string by dropping some (possi... | ```python
n = int(input())
s = input()
k = {}
def choose(a, b):
if b > a:
return 0
p = 1
for i in range(b):
p *= a - i
for i in range(1, b + 1):
p //= i
return p
for i in range(n):
if s[i] in k:
k[s[i]] += 1
else:
k[s[i]] = 1
#print(k)
ans = 0
a = []... |
1104_C. Grid game | You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in... | ```python
s = input()
f1 = 0; f2 = 0
for i in s:
if i=='1' and f1==0:
print(1,3); f1=1
elif i=='1' and f1==1:
print(1,1)
f1=0
elif i=='0' and f2==0:
print(3,1); f2=1
elif i=='0' and f2==1:
print(1,1); f2=0
``` |
1132_A. Regular Bracket Sequence | A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")... | ```python
a = int(input())
b = int(input())
c = int(input())
d = int(input())
if a == d:
if a > 0 or c == 0:
print(1)
else:
print(0)
else:
print(0)
``` |
1152_D. Neko and Aki's Prank | Neko is playing with his toys on the backyard of Aki's house. Aki decided to play a prank on him, by secretly putting catnip into Neko's toys. Unfortunately, he went overboard and put an entire bag of catnip into the toys...
It took Neko an entire day to turn back to normal. Neko reported to Aki that he saw a lot of w... | ```python
l=[1, 2, 6, 18, 57, 186, 622, 2120, 7338, 25724, 91144, 325878, 1174281, 4260282, 15548694, 57048048, 210295326, 778483932, 892818230, 786724318, 347919346, 355845955, 274146173, 336110626, 508416482, 521006399, 214448866, 997593411, 238896999, 849258736, 819525514, 53182350, 202970081, 945166442, 598349475, ... |
1174_B. Ehab Is an Odd Person | You're given an array a of length n. You can perform the following operation on it as many times as you want:
* Pick two integers i and j (1 ≤ i,j ≤ n) such that a_i+a_j is odd, then swap a_i and a_j.
What is lexicographically the smallest array you can obtain?
An array x is [lexicographically smaller](https://... | ```python
n = eval(input())
a = list(map(int, input().split()))
odd = False
even = False
for i in range(n):
if a[i] & 1:
odd = True
else:
even = True
if odd & even:
a.sort()
for x in a:
print(x, end=" ")
``` |
1230_D. Marcin and Training Camp | Marcin is a coach in his university. There are n students who want to attend a training camp. Marcin is a smart coach, so he wants to send only the students that can work calmly with each other.
Let's focus on the students. They are indexed with integers from 1 to n. Each of them can be described with two integers a_i... | ```python
n = int(input())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
v = []
for i in range(n):
v.append([a[i],b[i]])
v.sort()
prev = -1
big = []
flag = True
for i in v:
if prev == i[0] and (flag or big[-1]!=i[0]):
big.append(i[0])
flag = False
prev = i[0]
answer = 0
counter = 0
big.so... |
1295_A. Display The Number | You have a large electronic screen which can display up to 998244353 decimal digits. The digits are displayed in the same way as on different electronic alarm clocks: each place for a digit consists of 7 segments which can be turned on and off to compose different digits. The following picture describes how you can dis... | ```python
import sys
def solution(n):
if n % 2 == 0:
print("1" * (n // 2))
else:
print("7" + "1" * (n // 2 - 1))
for line in sys.stdin:
t = int(line)
break
for line in sys.stdin:
n = int(line)
solution(n)
``` |
1316_A. Grade Allocation | n students are taking an exam. The highest possible score at this exam is m. Let a_{i} be the score of the i-th student. You have access to the school database which stores the results of all students.
You can change each student's score as long as the following conditions are satisfied:
* All scores are integers ... | ```python
for i in range(int(input())):
print(min(list(map(int, input().split()))[1], sum(list(map(int, input().split())))))
``` |
1337_C. Linova and Kingdom | Writing light novels is the most important thing in Linova's life. Last night, Linova dreamed about a fantastic kingdom. She began to write a light novel for the kingdom as soon as she woke up, and of course, she is the queen of it.
<image>
There are n cities and n-1 two-way roads connecting pairs of cities in the ki... | ```python
from sys import *
input = stdin.readline
n,k = map(int,input().split())
graph = [set([]) for _ in range(n+1)]
for _ in range(n-1):
x,y = map(int,input().split())
graph[x].add(y)
graph[y].add(x)
dep,par,cn = [0]*(n+1),[0]*(n+1),0
q,p = [1],[]
vis = [0]*(n+1)
vis[1] = 1
while(q):
x = q.pop()... |
135_A. Replacement | Little Petya very much likes arrays consisting of n integers, where each of them is in the range from 1 to 109, inclusive. Recently he has received one such array as a gift from his mother. Petya didn't like it at once. He decided to choose exactly one element from the array and replace it with another integer that als... | ```python
n = int(input())
a = sorted(map(int, input().split()))
ans = [0]*n
ans[0] = 1
f = ans[0] != a[0]
for i in range(1, n):
ans[i] = a[i-1]
if ans[i] != a[i]:
f = True
m = 10**9
if not f:
for i in range(n-1, -1, -1):
if ans[i] < m:
ans[i] += 1
break
print(' '.... |
137_B. Permutation | "Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of n integers is calle... | ```python
n = int(input())
l = list(map(int,input().split()))
cnt=0
for i in range(1,n+1):
if i not in l:
cnt+=1
print(cnt)
``` |
13_B. Letter A | Little Petya learns how to write. The teacher gave pupils the task to write the letter A on the sheet of paper. It is required to check whether Petya really had written the letter A.
You are given three segments on the plane. They form the letter A if the following conditions hold:
* Two segments have common endpoi... | ```python
__author__ = 'Darren'
def solve():
t = int(input())
while t:
run()
t -= 1
def run():
def check_condition_1():
record = {}
common, first, second = None, -1, -1
found = False
for i in range(3):
for j in range(2):
if segm... |
1423_K. Lonely Numbers | In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b... | ```python
# This code is contributed by Siddharth
import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# setrecursionlimit(10**6)
# from sys import *
import random
from bisect import *
import math
from collections import *
import operator
from heapq import *
from itertools import *
inf=10**18
m... |
1443_D. Extreme Subtraction | You are given an array a of n positive integers.
You can use the following operation as many times as you like: select any integer 1 ≤ k ≤ n and do one of two things:
* decrement by one k of the first elements of the array.
* decrement by one k of the last elements of the array.
For example, if n=5 and a=[3... | ```python
#not done by myself
t=int(input())
fflg=0
if t==3000: fflg=1
cnt=1
while t!=0:
t-=1
n=int(input())
lst=input().split(" ")
# if fflg==1 and cnt==59: print(lst)
for i in range(0,n,1):
lst[i]=int(lst[i])
flg=0
mini=1000000000000000
psum=[0 for i in range(0,n+1,1)]
... |
1468_M. Similar Sets | You are given n sets of integers. The i-th set contains k_i integers.
Two sets are called similar if they share at least two common elements, i. e. there exist two integers x and y such that x ≠ y, and they both belong to each of the two sets.
Your task is to find two similar sets among the given ones, or report that... | ```python
def solve(n, debug=False):
global curr; global seen; global last; big = []; small = []
for i in range(1,1+n):
l = list(map(int, input().split()))
if l[0] > 600: big.append((i,l[1:]))
else: small.append((i,l[1:]))
s1 = len(big); s2 = len(... |
1494_A. ABC String | You are given a string a, consisting of n characters, n is even. For each i from 1 to n a_i is one of 'A', 'B' or 'C'.
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting charac... | ```python
from typing import Callable, Iterator, TypeVar, cast
_F = TypeVar("_F", bound=Callable[[], None])
def repeater(func: _F) -> _F:
def wrapper():
for _ in range(int(input())):
func()
return cast(_F, wrapper)
def get_num_input() -> Iterator[int]:
return map(int, input().split... |
1516_D. Cut | This time Baby Ehab will only cut and not stick. He starts with a piece of paper with an array a of length n written on it, and then he does the following:
* he picks a range (l, r) and cuts the subsegment a_l, a_{l + 1}, …, a_r out, removing the rest of the array.
* he then cuts this range into multiple subrange... | ```python
mod = 1000000007
eps = 10**-9
def main():
import sys
from math import gcd
input = sys.stdin.buffer.readline
V = 10**5
minfactor = list(range(V+1))
for d in range(2, V+1):
for x in range(2, V+1):
if d*x > V:
break
if minfactor[d*x] == d... |
171_F. ucyhf | qd ucyhf yi q fhycu dkcruh mxeiu huluhiu yi q tyvvuhudj fhycu dkcruh. oekh jqia yi je vydt jxu djx ucyhf.
Input
jxu ydfkj sediyiji ev q iydwbu ydjuwuh d (1 ≤ d ≤ 11184) — jxu edu-rqiut ydtun ev jxu ucyhf je vydt.
Output
ekjfkj q iydwbu dkcruh.
Examples
Input
1
Output
13 | ```python
#!/usr/bin/env python
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from io import BytesIO, IOBase
from itertools import *
from collections import *
# sys.setrecursionlimit(10**5)
if sys.version_info[0] < 3:
from __builtin__ i... |
215_D. Hot Days | The official capital and the cultural capital of Berland are connected by a single road running through n regions. Each region has a unique climate, so the i-th (1 ≤ i ≤ n) region has a stable temperature of ti degrees in summer.
This summer a group of m schoolchildren wants to get from the official capital to the cul... | ```python
import sys
n, m = map(int, sys.stdin.readline().split())
ans = 0
for _ in range(n):
ti, Ti, xi, ci = map(int, sys.stdin.readline().split())
cost = xi * m * (ti + m > Ti) + ci
if ti < Ti:
cost2 = ci * ((m - 1) // (Ti - ti) + 1)
cost = min(cost, cost2)
ans += cost
print... |
264_B. Good Sequences | Squirrel Liss is interested in sequences. She also has preferences of integers. She thinks n integers a1, a2, ..., an are good.
Now she is interested in good sequences. A sequence x1, x2, ..., xk is called good if it satisfies the following three conditions:
* The sequence is strictly increasing, i.e. xi < xi + 1 f... | ```python
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # ... |
288_B. Polo the Penguin and Houses | Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a hou... | ```python
import sys,math,heapq,copy
from collections import defaultdict,deque
from bisect import bisect_left,bisect_right
from functools import cmp_to_key
from itertools import permutations,combinations,combinations_with_replacement
# sys.setrecursionlimit(10**6)
# sys.stdin=open('Input.txt','r')
# sys.stdout=open('Ou... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.