name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
452_F. Permutation
You are given a permutation of numbers from 1 to n. Determine whether there's a pair of integers a, b (1 ≤ a, b ≤ n; a ≠ b) such that the element <image> (note, that it is usual division, not integer one) is between a and b in this permutation. Input First line consists of a single integer n (1 ≤ n ≤ 300000) — the si...
```python n = int(input()) v = list(map(int, input().split())) ans = "NO" p = [] for i in range(n + 1): p.append(-1) for i in range(n): p[v[i]] = i for i in range(n - 1): for j in range(i + 1, min(n, i + 6)): if v[i] * 2 - v[j] >= 1 and v[i] * 2 - v[j] <= n and p[v[i] * 2 - v[j]] < i: an...
475_D. CGCDSSQ
Given a sequence of integers a1, ..., an and q queries x1, ..., xq on it. For each query xi you have to count the number of pairs (l, r) such that 1 ≤ l ≤ r ≤ n and gcd(al, al + 1, ..., ar) = xi. <image> is a greatest common divisor of v1, v2, ..., vn, that is equal to a largest positive integer that divides all vi. ...
```python from sys import stdin import math from collections import defaultdict input = stdin.readline n = int(input()) arr = list(map(int, input().rstrip().split(" "))) q = int(input()) d = defaultdict(lambda : 0) current = defaultdict(lambda : 0) # totalCount1 = 0 # count1 = 0 for i in range(n): newCurrent = ...
523_A. Rotate, Flip and Zoom
Polycarp is writing the prototype of a graphic editor. He has already made up his mind that the basic image transformations in his editor will be: rotate the image 90 degrees clockwise, flip the image horizontally (symmetry relative to the vertical line, that is, the right part of the image moves to the left, and vice ...
```python I=input R=range w,h=map(int,I().split()) t=[I()for _ in R(h)] for r in[[t[i][j]*2for i in R(h)]for j in R(w)]:s=''.join(r);print(s+'\n'+s) ```
549_G. Happy Line
Do you like summer? Residents of Berland do. They especially love eating ice cream in the hot summer. So this summer day a large queue of n Berland residents lined up in front of the ice cream stall. We know that each of them has a certain amount of berland dollars with them. The residents of Berland are nice people, s...
```python R = lambda: list(map(int, input().split())) n = R()[0] a = R() for i in range(n): a[i] += i a = sorted(list(set(a))) if len(a) != n: print(':(') else: for i in range(n): print(a[i] - i, end=' ') ```
598_D. Igor In the Museum
Igor is in the museum and he wants to see as many pictures as possible. Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassa...
```python import sys from queue import deque # sys.stdin = open('ivo.in') move = [(0, 1), (1, 0), (0, -1), (-1, 0)] n, m, k = map(int, sys.stdin.readline().split()) a = [] for i in range(n): a.append(sys.stdin.readline().rstrip()) visited = [] values = [] for x in range(n): visited.append([]) values.ap...
61_B. Hard Work
After the contest in comparing numbers, Shapur's teacher found out that he is a real genius and that no one could possibly do the calculations faster than him even using a super computer! Some days before the contest, the teacher took a very simple-looking exam and all his n students took part in the exam. The teacher...
```python import itertools def remove_signs(s: str, signs: list) -> str: for i in range(len(signs)): s = s.replace(signs[i], '') return s def get_permulation_of_strings(s1, s2, s3): return list(map("".join, itertools.permutations([s1, s2, s3]))) def main(): signs = [';', '_', '-'] str1 =...
63_A. Sinking Ship
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All n crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to n) and await further instructions. However, one should evacuate the crew properly, in a strict o...
```python a=[] for _ in range(int(input())): x,y=map(str,input().split()) if y=="rat": y=0 else: if y=="man": y=2 else: if y=="captain": y=3 else: y=1 a.append([x,y]) a.sort(key=lambda x:x[1]) a=[i[0] for i in a] print(*a,sep="\n") ```
690_C2. Brain Network (medium)
Further research on zombie thought processes yielded interesting results. As we know from the previous problem, the nervous system of a zombie consists of n brains and m brain connectors joining some pairs of brains together. It was observed that the intellectual abilities of a zombie depend mainly on the topology of i...
```python import copy import sys import threading threading.stack_size(64 * 1024 * 1024) sys.setrecursionlimit(10 ** 6) n, m = map(int, input().split()) ans = 0 sz = [0] * (n + 1) graph = [] for _ in range(n + 1): graph.append([]) for _ in range(m): u, v = map(int, input().split()) graph[u].append(v) ...
714_A. Meeting of Old Friends
Today an outstanding event is going to happen in the forest — hedgehog Filya will come to his old fried Sonya! Sonya is an owl and she sleeps during the day and stay awake from minute l1 to minute r1 inclusive. Also, during the minute k she prinks and is unavailable for Filya. Filya works a lot and he plans to visit ...
```python l1,r1,l2,r2,k=map(int,input().split()) ma=max(l1,l2) mi=min(r1,r2) if k<=mi and k>=ma: print(max(0,mi-ma)) else: print(max(0,mi-ma+1)) ```
734_D. Anton and Chess
Anton likes to play chess. Also, he likes to do programming. That is why he decided to write the program that plays chess. However, he finds the game on 8 to 8 board to too simple, he uses an infinite one instead. The first task he faced is to check whether the king is in check. Anton doesn't know how to implement thi...
```python MAX_NUM = 10**9 n = int(input()) king_x, king_y = [int(x) for x in input().split()] nomakers = {'Rook': {'right-down':[], 'right-up':[], 'left-down':[], 'left-up':[]}, 'Bishop': {'left':[], 'right':[], 'up':[], 'down':[]}} yes = {'Queen':{'right-down':[], 'right-up':[], 'left-down':[], 'left-up':[],'left':[],...
758_D. Ability To Convert
Alexander is learning how to convert numbers from the decimal system to any other, however, he doesn't know English letters, so he writes any number only as a decimal number, it means that instead of the letter A he will write the number 10. Thus, by converting the number 475 from decimal to hexadecimal system, he gets...
```python n = input() k = input() digit = len(n) lst = [] def recul(k): if len(k)== 0: return if k[-digit:] < n: lst.append(k[-digit:]) if k[-digit:][0:1] == '0' and len(k[-digit:]) != 1: recul(k[:-digit]+'0') else: recul(k[:-digit]) else: temp = -digit+1 while k[temp:temp+1]== '0' and temp<0:...
77_B. Falling Anvils
For some reason in many American cartoons anvils fall from time to time onto heroes' heads. Of course, safes, wardrobes, cruisers, planes fall sometimes too... But anvils do so most of all. Anvils come in different sizes and shapes. Quite often they get the hero stuck deep in the ground. But have you ever thought who ...
```python t = int(input()) for _ in range(t): a, b = map(int, input().split()) if a == 0 and b == 0: print(1) elif a == 0: print(0.5) elif b == 0: print(1) elif a > 4 * b: print('%.10f' % ((a - b) / a)) else: print('%.10f' % (a / 16 / b + 0.5)) ```
803_A. Maximal Binary Matrix
You are given matrix with n rows and n columns filled with zeroes. You should put k ones in it in such a way that the resulting matrix is symmetrical with respect to the main diagonal (the diagonal that goes from the top left to the bottom right corner) and is lexicographically maximal. One matrix is lexicographically...
```python import sys import bisect from bisect import bisect_left as lb input_=lambda: sys.stdin.readline().strip("\r\n") from math import log from math import gcd from math import atan2,acos from random import randint sa=lambda :input_() sb=lambda:int(input_()) sc=lambda:input_().split() sd=lambda:list(map(int,input_(...
898_B. Proper Nutrition
Vasya has n burles. One bottle of Ber-Cola costs a burles and one Bars bar costs b burles. He can buy any non-negative integer number of bottles of Ber-Cola and any non-negative integer number of Bars bars. Find out if it's possible to buy some amount of bottles of Ber-Cola and Bars bars and spend exactly n burles. I...
```python n = int(input()) a = int(input()) b = int(input()) for i in range(n//a+1): if (n - i * a) % b == 0: print("YES") print(i, (n - i * a) // b) break else: print("NO") ```
919_C. Seat Arrangements
Suppose that you are in a campus and have to go for classes day by day. As you may see, when you hurry to a classroom, you surprisingly find that many seats there are already occupied. Today you and your friends went for class, and found out that some of the seats were occupied. The classroom contains n rows of seats ...
```python n, m, k = map(int, input().split()) def count(M): nr = len(M) nc = len(M[0]) res = 0 for i in range(nr): j = 0 while j < nc: while j < nc and M[i][j] == '*': j += 1 j2 = j while j2 < nc and M[i][j2] == '.': j2...
946_B. Weird Subtraction Process
You have two variables a and b. Consider the following sequence of actions performed with these variables: 1. If a = 0 or b = 0, end the process. Otherwise, go to step 2; 2. If a ≥ 2·b, then set the value of a to a - 2·b, and repeat step 1. Otherwise, go to step 3; 3. If b ≥ 2·a, then set the value of b to b - 2...
```python a, b = map(int, input().split()) while a != 0 and b != 0: if a >= 2 * b: a = a % (2 * b) elif b >= 2 * a: b = b % (2 * a) else: print(a, b) exit(0) print(a, b) ```
994_E. Careful Maneuvering
There are two small spaceship, surrounded by two groups of enemy larger spaceships. The space is a two-dimensional plane, and one group of the enemy spaceships is positioned in such a way that they all have integer y-coordinates, and their x-coordinate is equal to -100, while the second group is positioned in such a wa...
```python from collections import defaultdict import itertools as it def main(): n, m = map(int, input().split()) l = tuple(map(int, input().split())) r = tuple(map(int, input().split())) p2d = defaultdict(lambda :set()) for i, ll in enumerate(l): for j, rr in enumerate(r, len(l)): pd = p2d[(ll+rr)/2] ...
p02637 AtCoder Grand Contest 046 - Permutation Cover
Given are an integer K and integers a_1,\dots, a_K. Determine whether a sequence P satisfying below exists. If it exists, find the lexicographically smallest such sequence. * Every term in P is an integer between 1 and K (inclusive). * For each i=1,\dots, K, P contains a_i occurrences of i. * For each term in P, there...
```python import sys def find_permutation(aaa, use): """ iの残り使用数がaaa[i-1]の状態で 集合useにある文字群(1~k)を後ろに繋げる方法で それよりさらに後が破綻しないような繋げ方のうち 辞書順最小のものを求める。 ただし(この関数からは見えないが)現在確定済み配列の 末尾 (k - |use|) 個は、useに含まれない要素が1回ずつ登場することを前提とする。 (つまり、この関数の結果を繋げると、末尾 k 個が順列になる) どうやっても破綻する場合はNoneを返す。 :pa...
p02768 AtCoder Beginner Contest 156 - Bouquet
Akari has n kinds of flowers, one of each kind. She is going to choose one or more of these flowers to make a bouquet. However, she hates two numbers a and b, so the number of flowers in the bouquet cannot be a or b. How many different bouquets are there that Akari can make? Find the count modulo (10^9 + 7). Here,...
```python n,a,b = map(int,input().split()) mod = 10 ** 9 + 7 k = max(a,b) com = [1] for i in range(1,k+1): com.append((com[i-1]*(n-i+1)*pow(i,mod-2,mod))%mod) print((pow(2,n,mod)-1-com[a]-com[b])%mod) ```
p02903 AtCoder Grand Contest 038 - 01 Matrix
We have a square grid with H rows and W columns. Snuke wants to write 0 or 1 in each of the squares. Here, all of the following conditions have to be satisfied: * For every row, the smaller of the following is A: the number of 0s contained in the row, and the number of 1s contained in the row. (If these two numbers ar...
```python H,W,A,B = map(int,input().split()) for i in range(B): print("0"*A+"1"*(W-A)) for j in range(H-B): print("1"*A+"0"*(W-A)) ```
p03038 AtCoder Beginner Contest 127 - Integer Cards
You have N cards. On the i-th card, an integer A_i is written. For each j = 1, 2, ..., M in this order, you will perform the following operation once: Operation: Choose at most B_j cards (possibly zero). Replace the integer written on each chosen card with C_j. Find the maximum possible sum of the integers written o...
```python N,M=map(int,input().split()) L=[(1,a) for a in map(int,input().split())] for _ in range(M): L.append(tuple(map(int,input().split()))) L=sorted(L,key=lambda x: x[1],reverse=True) ans,k=0,0 for n,a in L: if n+k>=N: ans+=a*(N-k) break else: ans+=a*n k+=n print(ans) ```
p03179 Educational DP Contest - Permutation
Let N be a positive integer. You are given a string s of length N - 1, consisting of `<` and `>`. Find the number of permutations (p_1, p_2, \ldots, p_N) of (1, 2, \ldots, N) that satisfy the following condition, modulo 10^9 + 7: * For each i (1 \leq i \leq N - 1), p_i < p_{i + 1} if the i-th character in s is `<`, a...
```python M=10**9+7;n=int(input());s=input();d=[1]*n for k in range(n-1,0,-1): N=[0]*n for i in range(k+1): if'<'<s[n-1-k]:N[0]+=d[i];N[i]-=d[i] else:N[i]+=d[i];N[k]-=d[i] for i in range(k):N[i+1]=(N[i+1]+N[i])%M d=N print(d[0]%M) ```
p03327 AtCoder Beginner Contest 099 - ABD
Decades have passed since the beginning of AtCoder Beginner Contest. The contests are labeled as `ABC001`, `ABC002`, ... from the first round, but after the 999-th round `ABC999`, a problem occurred: how the future rounds should be labeled? In the end, the labels for the rounds from the 1000-th to the 1998-th are dec...
```python print(["ABD","ABC"][len(input())<4]) ```
p03483 AtCoder Regular Contest 088 - Papple Sort
You are given a string S consisting of lowercase English letters. Determine whether we can turn S into a palindrome by repeating the operation of swapping two adjacent characters. If it is possible, find the minimum required number of operations. Constraints * 1 \leq |S| \leq 2 × 10^5 * S consists of lowercase Englis...
```python from string import ascii_lowercase class Bit: def __init__(self, n): self.size = n self.tree = [0] * (n + 1) def sum(self, i): s = 0 while i > 0: s += self.tree[i] i -= i & -i return s def add(self, i, x): while i <= self....
p03648 AtCoder Regular Contest 079 - Decrease (Contestant ver.)
We have a sequence of length N consisting of non-negative integers. Consider performing the following operation on this sequence until the largest element in this sequence becomes N-1 or smaller. * Determine the largest element in the sequence (if there is more than one, choose one). Decrease the value of this element...
```python k = int(input()) d, m = divmod(k, 50) b = 49 + d print(50) print(*map(str, [b + 1] * m + [b - m] * (50 - m))) ```
p03804 AtCoder Beginner Contest 054 - Template Matching
You are given an image A composed of N rows and N columns of pixels, and a template image B composed of M rows and M columns of pixels. A pixel is the smallest element of an image, and in this problem it is a square of size 1×1. Also, the given images are binary images, and the color of each pixel is either white or bl...
```python m,n = [int(x) for x in input().split()] a = [] b = [] for _ in range(m): a.append(input()) m = 0 for i in range(n): b.append(input()) if b[i] in a[i]: m += 1 print('Yes') if m == n else print('No') ```
p03972 CODE FESTIVAL 2016 qual B - Gr-idian MST
On an xy plane, in an area satisfying 0 ≤ x ≤ W, 0 ≤ y ≤ H, there is one house at each and every point where both x and y are integers. There are unpaved roads between every pair of points for which either the x coordinates are equal and the difference between the y coordinates is 1, or the y coordinates are equal and...
```python #!/usr/bin/env python3 import sys try: from typing import Any, Union, List, Tuple, Dict except ImportError: pass sys.setrecursionlimit(10**6) def debug(*args): print(*args, file=sys.stderr) def exit(): sys.exit(0) W, H = map(int, input().split()) p = [] for i in range(W): p.append(int(input())) q = [] f...
p00061 Rank Checker
The time is 2020. There is data that saves the qualifying results of PC Koshien 2020. This data stores the reference number and the number of correct answers assigned to each team. Here, the ranking is determined by the number of correct answers, and the ranking is given in descending order of the number of correct ans...
```python def get_input(): while True: try: yield ''.join(input()) except EOFError: break teams = [0 for i in range(101)] points = [False for i in range(31)] while True: a,b = [int(i) for i in input().split(",")] if a == 0 and b == 0: break teams[a] = b ...
p00192 Multistory Parking Lot
There are various parking lots such as three-dimensional type and tower type in the city to improve the utilization efficiency of the parking lot. In some parking lots, a "two-stage parking device" as shown in the figure is installed in one parking space to secure a parking space for two cars. This two-stage parking de...
```python from collections import deque def out(time, parking): x = len(parking) outs = [] for i in range(x): for j in range(2): if parking[i][j] != None: parking[i][j][0] -= time for i in range(x): c1 = parking[i][0] c2 = parking[i][1] if c1 != None and c2 != None: if c1...
p00347 Forecast of Forces
Nobuo-kun and Shizuo-kun are playing a game of competing for territories on a rectangular island. As shown in Fig. 1 below, the entire island is made up of square compartments divided in a grid pattern, and the profits and losses resulting from these are indicated by integers. <image> In this game, move one piece t...
```python import sys sys.setrecursionlimit(10**7) w, h = map(int, input().split()) S = [list(map(int, input().split())) for i in range(h)] SW = [[0]*w for i in range(h)] SH = [[0]*w for i in range(h)] for i in range(h): cnt = 0 for j in range(w-1, -1, -1): cnt += S[i][j] SW[i][j] = cnt for j in ...
p00543 Swapping Bibs
problem N students from JOI High School are lined up in a row from east to west. The i-th student from the western end of the column is student i. Each student has a bib with one integer. Initially, the integer Ai is written on the number of student i. There are M batons, and the batons are numbered from 1 to M. For ...
```python n,m=map(int,input().split()) a=[int(input()) for _ in range(n)] for i in range(1,m+1): for j in range(n-1): if a[j]%i>a[j+1]%i:a[j],a[j+1]=a[j+1],a[j] for i in a:print(i) ```
p00707 The Secret Number
Your job is to find out the secret number hidden in a matrix, each of whose element is a digit ('0'-'9') or a letter ('A'-'Z'). You can see an example matrix in Figure 1. <image> Figure 1: A Matrix The secret number and other non-secret ones are coded in a matrix as sequences of digits in a decimal format. You shoul...
```python from collections import defaultdict def main(w, h): field = [list(input()) for i in range(h)] d = defaultdict(str) for y in range(h - 1, -1, -1): for x in range(w - 1, -1, -1): if "0" <= field[y][x] <= "9": d[(x, y)] = field[y][x] for y in range(h - 1, -1, -...
p01110 Origami
Origami, or the art of folding paper Master Grus is a famous origami (paper folding) artist, who is enthusiastic about exploring the possibility of origami art. For future creation, he is now planning fundamental experiments to establish the general theory of origami. One rectangular piece of paper is used in each of...
```python while(True): n,m,t,p=map(int,input().split()) if (n,m,t,p)==(0,0,0,0): break d=[0 for i in range(t)] c=[0 for i in range(t)] x=[0 for i in range(p)] y=[0 for i in range(p)] nnow,mnow=n,m for i in range(t): d[i],c[i]=map(int,input().split()) for i in rang...
p01563 Connect
You are playing a solitaire puzzle called "Connect", which uses several letter tiles. There are R × C empty cells. For each i (1 ≤ i ≤ R), you must put a string si (1 ≤ |si| ≤ C) in the i-th row of the table, without changing the letter order. In other words, you choose an integer sequence {aj} such that 1 ≤ a1 < a2 <...
```python # seishin.py import sys readline = sys.stdin.readline write = sys.stdout.write def gen(N, K): if K == 0: yield 0 return v = (1 << K) - 1 N2 = (1 << N) while v < N2: yield v x = v & -v; y = v + x v = ((v & ~y) // x >> 1) | y def solve(): R, C = map(...
p01725 Unordered Operators
One day, Ikta, an elementary school student, received a piece of paper with mathematical formulas from his grandfather. Apparently, the grandfather will give you as much money as the answer to the formula. Ikta has only learned addition, subtraction, and multiplication, so only addition, subtraction, and multiplication...
```python from sys import setrecursionlimit setrecursionlimit(10 ** 8) O = {'+': lambda l, r: l + r, '-': lambda l, r: l - r, '*': lambda l, r: l * r} P = {'+': 0, '-': 0, '*': 0} class Source(): def __init__(self, S, i=0): self.S = S self.pos = i def peek(S): return S.S[...
p01863 Miko Mi String
F: Miko Mi String- story Mikko Mikkomi ~! Everyone's idol, Miko Miko Tazawa! Today ~, with Mikoto ~, practice the string algorithm, let's do it ☆ Miko's special ~~ character making ~~ The slogan "MikoMikomi" becomes "MikoMikoMi" in Roman letters! In other words, if A = “Mi” and B = “Ko”, you can write in the form of...
```python s = input() length = len(s) BASE = 100 MOD1 = 1000000007 MOD2 = 2147483647 acc1 = 0 acc2 = 0 hlst1 = [0] hlst2 = [0] for c in s: i = ord(c) acc1 = (acc1 * BASE + i) % MOD1 acc2 = (acc2 * BASE + i) % MOD2 hlst1.append(acc1) hlst2.append(acc2) def calc_hash(left, right, xlen): return ((hlst1[right]...
p01998 Prime Number
problem One day, Sosusa, who loves prime numbers, was playing with the pair $ (p, q) $, where $ p + q $ is a prime number. Suddenly, Sosusa wondered how many of these pairs were prime numbers with $ p $ and $ q $ both less than or equal to $ N $. Find the number on your behalf. output Output the number of pairs. A...
```python import math N = int(input()) P = [True for x in range(N + 3)] P[0] = False P[1] = False for i in range(2, int(math.sqrt(N + 3)) + 1): if P[i]: for j in range(i * 2, N + 3, i): P[j] = False count = 0 for q in range(3, N + 1): if P[q] and P[2 + q]: count += 2 print(coun...
p02285 Binary Search Tree III
Write a program which performs the following operations to a binary search tree $T$ by adding delete operation to B: Binary Search Tree II. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * delete $k$: Delete a node containing $k$. * print: Print t...
```python class Node: def __init__(self,key,left=None,right=None,parent=None): self.key = key self.left = left self.right = right self.parent = parent root=None #前序排序 def PreorderTreeWalk(u): if u == None: return print(" %d"%u.key,end='') PreorderTreeWalk(u.left...
p02432 Deque
For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations: * push($d$, $x$): Add element $x$ at the begining of $A$, if $d = 0$. Add element $x$ at the end of $A$, if $d = 1$. * randomAccess($p$): Print element $a_p$. * pop($d$): Delete the first element of $A$, if $d = ...
```python from collections import deque class shinajina(): def push(A,que): if que[1]==0: A.appendleft(que[2]) elif que[1]==1: A.append(que[2]) def randomaccess(A,que): print(A[que[1]]) def pop(A,que): if que[1]==0: A.popleft() elif...
1003_F. Abbreviation
You are given a text consisting of n space-separated words. There is exactly one space character between any pair of adjacent words. There are no spaces before the first word and no spaces after the last word. The length of text is the number of letters and spaces in it. w_i is the i-th word of text. All words consist ...
```python # import time N = 303 eq = [] dp = [] for i in range(N): eq.append([False] * N) for i in range(N): dp.append([0] * N) n = int(input()) s = input() # t = time.time() allsum = len(s) s = s.split() for i in range(n): eq[i][i] = True for j in range(i): eq[i][j] = eq[j][i] = s[i] == s[j] fo...
1027_G. X-mouse in the Campus
The campus has m rooms numbered from 0 to m - 1. Also the x-mouse lives in the campus. The x-mouse is not just a mouse: each second x-mouse moves from room i to the room i ⋅ x mod{m} (in fact, it teleports from one room to another since it doesn't visit any intermediate room). Starting position of the x-mouse is unknow...
```python from math import gcd def powmod(a,b,m): a%=m r=1 while b: if b&1:r=r*a%m a=a*a%m b>>=1 return r def f(n): r=[] if (n&1)==0: e=0 while (n&1)==0:n>>=1;e+=1 yield (2,e) p=3 while n>1: if p*p>n:p=n if n%p: p+=2 continue e=1;n//=p while n%p==0:n//=p;e+=1 yield (p,e) p+=2 ret...
1046_F. Splitting money
After finding and moving to the new planet that supports human life, discussions started on which currency should be used. After long negotiations, Bitcoin was ultimately chosen as the universal currency. These were the great news for Alice, whose grandfather got into Bitcoin mining in 2013, and accumulated a lot of t...
```python n = int(input()) a = list(map(int, input().split())) max, fee = map(int, input().split()) total = 0 a.sort(reverse=True) for i in range(n): if a[i]> max: num = -(-(a[i]-max)//(max+fee)) total = total + fee*num else: break print(total) ```
1070_E. Getting Deals Done
Polycarp has a lot of work to do. Recently he has learned a new time management rule: "if a task takes five minutes or less, do it immediately". Polycarp likes the new rule, however he is not sure that five minutes is the optimal value. He supposes that this value d should be chosen based on existing task list. Polyca...
```python import io, os input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline ii = lambda: int(input()) mi = lambda: map(int, input().split()) li = lambda: list(mi()) out = [] for _ in range(ii()): n, m, t = mi() p = li() def check(d): cur = tim = tot = totim = 0 for i in...
1092_A. Uniform String
You are given two integers n and k. Your task is to construct such a string s of length n that for each i from 1 to k there is at least one i-th letter of the Latin alphabet in this string (the first letter is 'a', the second is 'b' and so on) and there are no other letters except these. You have to maximize the minim...
```python t=int(input()) for _ in range(t): n,k=map(int,input().split()) s='' for i in range(97,97+k): s+=chr(i) s=s*(n//k)+s[:n%k] print(s) ```
1140_D. Minimum Triangulation
You are given a regular polygon with n vertices labeled from 1 to n in counter-clockwise order. The triangulation of a given polygon is a set of triangles such that each vertex of each triangle is a vertex of the initial polygon, there is no pair of triangles such that their intersection has non-zero area, and the tota...
```python n=int(input()) print((n*(n+1)*(n+2))//3-2-n*(n+1)) ```
1159_B. Expansion coefficient of the array
Let's call an array of non-negative integers a_1, a_2, …, a_n a k-extension for some non-negative integer k if for all possible pairs of indices 1 ≤ i, j ≤ n the inequality k ⋅ |i - j| ≤ min(a_i, a_j) is satisfied. The expansion coefficient of the array a is the maximal integer k such that the array a is a k-extension....
```python from sys import stdin,stdout a=int(stdin.readline()) z=list(map(int,stdin.readline().split())) k=min(z);r=int(1e9);i=0;j=a-1 while i<=j:r=min(r,z[i]//max(i,a-i-1),z[j]//max(j,a-j-1));i+=1;j-=1 stdout.write(str(r)) ```
1181_B. Split a Number
Dima worked all day and wrote down on a long paper strip his favorite number n consisting of l digits. Unfortunately, the strip turned out to be so long that it didn't fit in the Dima's bookshelf. To solve the issue, Dima decided to split the strip into two non-empty parts so that each of them contains a positive inte...
```python n = int(input()) s = input() mid = n//2; ans = int(s) for i in range(mid, 0, -1): if s[i] != '0': val = int(s[:i]) + int(s[i:]) ans = min(ans, val) break for i in range(mid+1, n): if s[i] != '0': val = int(s[:i]) + int(s[i:]) ans = min(ans, val) break ...
119_A. Epic Game
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number a and Antisimon receives number b. They also have a heap of n stones. The players take turns to make a move and Simon starts. During a move a player should take from ...
```python def gcd(a, b): if a == 0: return b return gcd(b % a, a) a, b,n = map(int,input().split(" ")) while True: n -= gcd(a, n) if n < 0: print("1") break n -= gcd(b,n) if n < 0: print("0") break ```
1216_E2. Numerical Sequence (hard version)
The only difference between the easy and the hard versions is the maximum value of k. You are given an infinite sequence of form "112123123412345..." which consist of blocks of all consecutive positive integers written one after another. The first block consists of all numbers from 1 to 1, the second one — from 1 to 2...
```python q = int(input()) def f(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += (n - take) * (n - take + 1) // 2 take = take * 10 + 9 return ret def g(n): take = 0 ret = 0 while True: if n - take <= 0: break ret += n - take take = take * 10 + 9 return ret ...
123_A. Prime Permutation
You are given a string s, consisting of small Latin letters. Let's denote the length of the string as |s|. The characters in the string are numbered starting from 1. Your task is to find out if it is possible to rearrange characters in string s so that for any prime number p ≤ |s| and for any integer i ranging from 1...
```python import math ch='abcdefghijklmnopqrstuvwxyz' def sieve(n): p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * 2, n + 1, p): prime[i] = False p += 1 prime[0]= False prime[1]= False s = ['#']+list(input()) lis=[0]*26 n = len(s)-1 pr...
125_B. Simple XML
Let's define a string <x> as an opening tag, where x is any small letter of the Latin alphabet. Each opening tag matches a closing tag of the type </x>, where x is the same letter. Tegs can be nested into each other: in this case one opening and closing tag pair is located inside another pair. Let's define the notion...
```python # vars s = input() h = 0 # end_vars # main.sys l = s.split('>') for _ in range(len(l)): l[_] += '>' l = l[:-1] for i in range(len(l)): if '/' in l[i]: h -= 2 print(h * ' ' + l[i]) if '/' not in l[i]: h += 2 # end_main.sys ```
1281_D. Beingawesomeism
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r × c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomei...
```python # ------------------- fast io -------------------- import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in...
1301_D. Time to Run
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he sh...
```python import sys import math from collections import defaultdict,Counter # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # m=pow(10,9)+7 n,m,k=map(int,input().split()) if k>(4*m*n-2*n-2*m): print("NO"...
1325_D. Ehab the Xorcist
Given 2 integers u and v, find the shortest array such that [bitwise-xor](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of its elements is u, and the sum of its elements is v. Input The only line contains 2 integers u and v (0 ≤ u,v ≤ 10^{18}). Output If there's no array that satisfies the condition, print "...
```python u, v = list(map(int, input().split())) if u > v: print(-1) elif u == 0 and v == 0: print(0) elif u == v: print(1) print(u) else: a, b, c = u, (v - u) // 2, (v - u) // 2 d, e = (v - u) // 2 + u, (v - u) // 2 if d + e == v and d ^ e == u: print(2) print(d, e) elif...
1344_C. Quantifier Question
Logical quantifiers are very useful tools for expressing claims about a set. For this problem, let's focus on the set of real numbers specifically. The set of real numbers includes zero and negatives. There are two kinds of quantifiers: universal (∀) and existential (∃). You can read more about them here. The universa...
```python import sys from collections import deque input=sys.stdin.readline n,m=map(int,input().split()) edge=[[] for i in range(n)] revedge=[[] for i in range(n)] for i in range(m): j,k=map(int,input().split()) edge[j-1].append(k-1) revedge[k-1].append(j-1) deg=[len(revedge[i]) for i in range(n)] ans =...
1366_C. Palindromic Paths
You are given a matrix with n rows (numbered from 1 to n) and m columns (numbered from 1 to m). A number a_{i, j} is written in the cell belonging to the i-th row and the j-th column, each number is either 0 or 1. A chip is initially in the cell (1, 1), and it will be moved to the cell (n, m). During each move, it eit...
```python cases = int(input()) for t in range(cases): n,m = list(map(int,input().split())) a = [list(map(int,input().split())) for i in range(n)] b = [[] for i in range(n+m-1)] for i in range(n): for j in range(m): d = i+j b[d].append(a[i][j]) centre = (n+m-1)//2 ...
1408_C. Discrete Acceleration
There is a road with length l meters. The start of the road has coordinate 0, the end of the road has coordinate l. There are two cars, the first standing at the start of the road and the second standing at the end of the road. They will start driving simultaneously. The first car will drive from the start to the end ...
```python from sys import stdin, stdout from bisect import * def calc(T,arr): M={} # arr.insert(0,0) D,S,T=[0],[1],[0] M[0]=(0,1) c=0 t=0 for i in range(1,len(arr)): d=arr[i]-arr[i-1] c+=1 t+=d/c M[t]=(d,c) D.append(arr[i]) T.append(t) ...
1428_F. Fruit Sequences
Zookeeper is buying a carton of fruit to feed his pet wabbit. The fruits are a sequence of apples and oranges, which is represented by a binary string s_1s_2… s_n of length n. 1 represents an apple and 0 represents an orange. Since wabbit is allergic to eating oranges, Zookeeper would like to find the longest contiguo...
```python hist = [0]*1000005 def solve(n,s): cnt = 0 tot = 0 i = 0 while i < n: if s[i] == '0': tot += cnt else: l = i r = i while r+1 < n and s[r+1] == '1': r+=1 #print(r) for x in range(r-l...
1452_A. Robot Program
There is an infinite 2-dimensional grid. The robot stands in cell (0, 0) and wants to reach cell (x, y). Here is a list of possible commands the robot can execute: * move north from cell (i, j) to (i, j + 1); * move east from cell (i, j) to (i + 1, j); * move south from cell (i, j) to (i, j - 1); * move wes...
```python for _ in range(int(input())): n,m=[int(x) for x in input().split()] print(n+m+max(0,abs(m-n)-1)) ```
1475_F. Unusual Matrix
You are given two binary square matrices a and b of size n × n. A matrix is called binary if each of its elements is equal to 0 or 1. You can do the following operations on the matrix a arbitrary number of times (0 or more): * vertical xor. You choose the number j (1 ≤ j ≤ n) and for all i (1 ≤ i ≤ n) do the follow...
```python def solve(): for _ in range(int(input())): n=int(input()) a=[] b=[] aux=[] for i in range(n): s=input() t=[] for j in s: t.append(int(j)) a.append(t) aux.append(t) s=input() ...
157_C. Message
Dr. Moriarty is about to send a message to Sherlock Holmes. He has a string s. String p is called a substring of string s if you can read it starting from some position in the string s. For example, string "aba" has six substrings: "a", "b", "a", "ab", "ba", "aba". Dr. Moriarty plans to take string s and cut out som...
```python aa = input() bb = input() if len(aa) >= len(bb): p = aa q = bb else: p = aa q = bb maxc = 0 for i in range(1,len(p)+len(q)): k1 = max(0,i-len(q)) k2 = min(i,len(p)) a = p[k1:k2] if i < len(q): b = q[-i:] elif i > len(p): b = q[:-(i-len(p))] else: ...
178_A3. Educational Game
The Smart Beaver from ABBYY began to develop a new educational game for children. The rules of the game are fairly simple and are described below. The playing field is a sequence of n non-negative integers ai numbered from 1 to n. The goal of the game is to make numbers a1, a2, ..., ak (i.e. some prefix of the sequenc...
```python import sys import math #to read string get_string = lambda: sys.stdin.readline().strip() #to read list of integers get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) ) #to read integers get_int = lambda: int(sys.stdin.readline()) #--------------------------------WhiteHat010----------...
248_C. Robo-Footballer
It's a beautiful April day and Wallace is playing football with his friends. But his friends do not know that Wallace actually stayed home with Gromit and sent them his robotic self instead. Robo-Wallace has several advantages over the other guys. For example, he can hit the ball directly to the specified point. And ye...
```python from math import hypot y1, y2, yw, xb, yb, r = map(int, input().split()) yw -= r y1, y2 = yw * 2 - y2, yw * 2 - y1 def xww(y): return (y - yw) * xb / (y - yb) def dd(y): xw = xww(y) return (y - y1) / hypot(1, (yw - y) / xw) def binary_search(): a, b = y1 + r, 1e10 for i in range(200): m = ...
272_D. Dima and Two Sequences
Little Dima has two sequences of points with integer coordinates: sequence (a1, 1), (a2, 2), ..., (an, n) and sequence (b1, 1), (b2, 2), ..., (bn, n). Now Dima wants to count the number of distinct sequences of points of length 2·n that can be assembled from these sequences, such that the x-coordinates of points in th...
```python from math import sqrt,ceil,gcd from collections import defaultdict def modInverse(b,m): g = gcd(b, m) if (g != 1): # print("Inverse doesn't exist") return -1 else: # If b and m are relatively prime, # then modulo inverse is b^(m-2) mode m return pow(b, m...
296_A. Yaroslav and Permutations
Yaroslav has an array that consists of n integers. In one second Yaroslav can swap two neighboring array elements. Now Yaroslav is wondering if he can obtain an array where any two neighboring elements would be distinct in a finite time. Help Yaroslav. Input The first line contains integer n (1 ≤ n ≤ 100) — the numb...
```python import math nums=eval(input()) list=input().split() max1=0 for i in list: if max1<list.count(i): max1=list.count(i) if max1>math.ceil((len(list)/2)): print("NO") else :print("YES") ```
367_A. Sereja and Algorithm
Sereja loves all sorts of algorithms. He has recently come up with a new algorithm, which receives a string as an input. Let's represent the input string of the algorithm as q = q1q2... qk. The algorithm consists of two steps: 1. Find any continuous subsequence (substring) of three characters of string q, which does...
```python import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') input = sys.stdin.readline s = input().strip() x_c, y_c, z_c = [0], [0], [0] for el in s: x_c.append(x_c[-1]+int(el=="x")) y_c.append(y_c[-1]+int(el=="y")) z_c.append(z_c[-1]+int(el=="z")) for _ in range(...
38_E. Let's Go Rolling!
On a number axis directed from the left rightwards, n marbles with coordinates x1, x2, ..., xn are situated. Let's assume that the sizes of the marbles are infinitely small, that is in this task each of them is assumed to be a material point. You can stick pins in some of them and the cost of sticking in the marble num...
```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...
40_D. Interesting Sequence
Berland scientists noticed long ago that the world around them depends on Berland population. Due to persistent research in this area the scientists managed to find out that the Berland chronology starts from the moment when the first two people came to that land (it is considered to have happened in the first year). A...
```python from fractions import Fraction import sys sys.setrecursionlimit(1000*100) A=int(input()) p=[] c=1 for _ in range(600): p.append(c) c*=12 r=[] for i in range(600): for j in range(i+1): if p[j]+p[i-j]==A: r.append(i+1) break s=set() for i in r: for j in range(i...
45_J. Planting Trees
Vasya is a Greencode wildlife preservation society proponent. One day he found an empty field nobody owned, divided it into n × m squares and decided to plant a forest there. Vasya will plant nm trees of all different heights from 1 to nm. For his forest to look more natural he wants any two trees growing in the side n...
```python # by the authority of GOD author: manhar singh sachdev # def some_random_function(): """due to the fast IO template, my code gets caught in plag check for no reason. That is why, I am making random functions""" x = 10 x *= 100 i_dont_know = x why_am_i_writing_this = x*x ...
483_D. Interesting Array
We'll call an array of n non-negative integers a[1], a[2], ..., a[n] interesting, if it meets m constraints. The i-th of the m constraints consists of three integers li, ri, qi (1 ≤ li ≤ ri ≤ n) meaning that value <image> should be equal to qi. Your task is to find any interesting array of n elements or state that su...
```python # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase def main(): n,m = map(int,input().split()) dp = [[0]*30 for _ in range(n+2)] op = [] for _ in range(m): op.append(tuple(map(int,input().split()))) l,r,q = op[-1] ...
507_D. The Maths Lecture
Amr doesn't like Maths as he finds it really boring, so he usually sleeps in Maths lectures. But one day the teacher suspected that Amr is sleeping and asked him a question to make sure he wasn't. First he gave Amr two positive integers n and k. Then he asked Amr, how many integer numbers x > 0 exist such that: * D...
```python def get_input(): hahaha=input() (n,k,m)=hahaha.split(sep=None, maxsplit=1000) return (int(n),int(k),int(m)) (n,k,m)=get_input() f=[0 for i in range(k)] s=0 for v in range(n): tens = 10**v%k f=[ (sum( [f[(j+k-(x+1)*tens)%k] for x in range(9)] )+f[j])%m for j in range(k)] for...
604_C. Alternative Thinking
Kevin has just recevied his disappointing results on the USA Identification of Cows Olympiad (USAICO) in the form of a binary string of length n. Each character of Kevin's string represents Kevin's score on one of the n questions of the olympiad—'1' for a correctly identified cow and '0' otherwise. However, all is not...
```python if __name__ == "__main__": n = int( input().strip() ) s = input().strip() segs = [] start = 0 i = 1 while i <= n: if i == n or s[i] != s[start]: segs.append( i - start ) start = i i = start + 1 else: i += 1 res = l...
676_B. Pyramid of Glasses
Mary has just graduated from one well-known University and is now attending celebration party. Students like to dream of a beautiful life, so they used champagne glasses to construct a small pyramid. The height of the pyramid is n. The top level consists of only 1 glass, that stands on 2 glasses on the second level (co...
```python n, t = map(int, input().split()) g = [0] * n for i in range(n): g[i] = [0]*(i+1) for i in range(t): g[0][0] += 1 for j in range(n): for k in range(j+1): if g[j][k] > 1 and j < n - 1: u = g[j][k] - 1 g[j][k] = 1 g[j+1][k] += u/2 ...
69_B. Bets
In Chelyabinsk lives a much respected businessman Nikita with a strange nickname "Boss". Once Nikita decided to go with his friend Alex to the Summer Biathlon World Cup. Nikita, as a very important person, received a token which allows to place bets on each section no more than on one competitor. To begin with friends...
```python import os import sys from io import BytesIO, IOBase from types import GeneratorType from bisect import * from collections import defaultdict, deque, Counter import math import string from heapq import * from operator import add from itertools import accumulate BUFSIZE = 8192 sys.setrecursionlimit(10 ** 5) ...
742_B. Arpa’s obvious problem and Mehrdad’s terrible solution
There are some beautiful girls in Arpa’s land as mentioned before. Once Arpa came up with an obvious problem: Given an array and a number x, count the number of pairs of indices i, j (1 ≤ i < j ≤ n) such that <image>, where <image> is bitwise xor operation (see notes for explanation). <image> Immediately, Mehrdad d...
```python n,x = map(int, input().split(' ')) a = list(map(int, input().split(' '))) cs = {} for v in a: cs[v] = cs.get(v, 0) + 1 t = 0 if x == 0: for c in cs.values(): t += c * (c - 1) // 2 print (t) else: for v in a: t += cs.get(x ^ v, 0) print(t // 2) ```
789_C. Functions again
Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as...
```python n = int(input()) arr = list(map(int,input().split(' '))) arr.insert(0,0) diff_arr = [] end_so_far = 0 max_so_far = 0 l = 1 for i in range(2,len(arr)-1): temp = abs(arr[i]-arr[i+1]) diff_arr.append(temp*(pow((-1),i))) end_so_far = end_so_far + diff_arr[-1] if end_so_far < 0: if i%2 == 0...
80_E. Beavermuncher-0xFF
"Eat a beaver, save a tree!" — That will be the motto of ecologists' urgent meeting in Beaverley Hills. And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with t...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n = int(input()) beaver = list(map(int, input().split())) adj = [[] for _ in range(n)] deg = [0] * n for u, v in (map(int, input().split()) for _ in range(n - 1)): adj[u - 1].append(v ...
835_C. Star sky
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 ≤ si ≤ c). Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. ...
```python import sys from bisect import bisect_left, bisect_right n, q, c = list(map(int, input().split())) values = [[[0 for _ in range(11)] for _ in range(0, 101)] for _ in range(0, 101)] # print(dp) for i in range(n): x, y, s = list(map(int, sys.stdin.readline().split())) values[x][y][s] += 1 dp = [[[-1...
903_F. Clear The Matrix
You are given a matrix f with 4 rows and n columns. Each element of the matrix is either an asterisk (*) or a dot (.). You may perform the following operation arbitrary number of times: choose a square submatrix of f with size k × k (where 1 ≤ k ≤ 4) and replace each element of the chosen submatrix with a dot. Choosin...
```python import sys n = int(sys.stdin.buffer.readline().decode('utf-8')) cost = [0] + \ list(map(int, sys.stdin.buffer.readline().decode('utf-8').split())) a = [line.decode('utf-8').rstrip() for line in sys.stdin.buffer] mask = [0, 1, 51, 1911] inf, bs_size, full_bit = 10**9, 1 << 12, (1 << 12) - 1 dp = [[inf]*b...
926_A. 2-3-numbers
A positive integer is called a 2-3-integer, if it is equal to 2x·3y for some non-negative integers x and y. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 — are 2-3 integers, while 5, 10, 21 and 120 are not. Print the number...
```python import sys from math import * from fractions import gcd readints=lambda:map(int, input().strip('\n').split()) l,r=readints() maxn=2*(10**9) twos=set() i=2 while i<=maxn: twos.add(i) i*=2 threes=set() i=3 while i<=maxn: threes.add(i) i*=3 nums=set() nums.add(1) for x in twos: for y in t...
981_A. Antipalindrome
A string is a palindrome if it reads the same from the left to the right and from the right to the left. For example, the strings "kek", "abacaba", "r" and "papicipap" are palindromes, while the strings "abb" and "iq" are not. A substring s[l … r] (1 ≤ l ≤ r ≤ |s|) of a string s = s_{1}s_{2} … s_{|s|} is the string s_...
```python a=input() b=a[::-1] c=0 if a!=b: print(len(a)) while a==b: a=a[:0]+a[(0+1):] b=a[::-1] if a!=b: print(len(a)) else: print(c) break ```
p02550 AtCoder Beginner Contest 179 - Sequence Sum
Let us denote by f(x, m) the remainder of the Euclidean division of x by m. Let A be the sequence that is defined by the initial value A_1=X and the recurrence relation A_{n+1} = f(A_n^2, M). Find \displaystyle{\sum_{i=1}^N A_i}. Constraints * 1 \leq N \leq 10^{10} * 0 \leq X < M \leq 10^5 * All values in input are ...
```python n,x,m=map(int,input().split()) yj=[x] lps=0 for i in range(n): an=(yj[i]**2)%m if an in yj: lps=yj.index(an) break yj.append(an) blp=yj[:lps] lp=yj[lps:] ans=sum(blp)+sum(lp)*((n-len(blp))//len(lp))+sum(lp[:(n-len(blp))%len(lp)]) print(ans) ```
p02681 AtCoder Beginner Contest 167 - Registration
Takahashi wants to be a member of some web service. He tried to register himself with the ID S, which turned out to be already used by another user. Thus, he decides to register using a string obtained by appending one character at the end of S as his ID. He is now trying to register with the ID T. Determine whether...
```python s = input() t = input() print('Yes') if t[:-1] == s else print('No') ```
p02809 Dwango Programming Contest 6th - Arrangement
Niwango has N cards, numbered 1,2,\ldots,N. He will now arrange these cards in a row. Niwango wants to know if there is a way to arrange the cards while satisfying all the N conditions below. To help him, determine whether such a way exists. If the answer is yes, also find the lexicographically smallest such arrangeme...
```python """ Writer: SPD_9X2 https://atcoder.jp/contests/dwacon6th-prelims/tasks/dwacon6th_prelims_d 左からおいていくことを考える 残ったカード全てから嫌われている場合、もう置くしかない 貪欲に置いていき、残りカード全てから嫌われてしまったら置く? そうなるとただの実装難問題だが… for i in range(N) if 残りのカード全てから嫌われてしまっているカードがあったら置く。 elif 辞書順最小のカードが置けたら置く elif 辞書順2番目のカードが存在したら置く。 else -1?...
p02946 AtCoder Beginner Contest 137 - One Clue
There are 2000001 stones placed on a number line. The coordinates of these stones are -1000000, -999999, -999998, \ldots, 999999, 1000000. Among them, some K consecutive stones are painted black, and the others are painted white. Additionally, we know that the stone at coordinate X is painted black. Print all coordi...
```python K, X = map(int, input().split()) ans = list(range(X-K+1,X+K,1)) print(*ans) ```
p03082 ExaWizards 2019 - Modulo Operations
Snuke has a blackboard and a set S consisting of N integers. The i-th element in S is S_i. He wrote an integer X on the blackboard, then performed the following operation N times: * Choose one element from S and remove it. * Let x be the number written on the blackboard now, and y be the integer removed from S. Repla...
```python N , X = list(map(int, input().split())) S = list(map(int, input().split())) MOD = 10**9+7 memo = [{} for i in range(N)] S.sort(reverse=True) def ddp(cur_N, cur_x): if cur_N == N: return cur_x if cur_x in memo[cur_N]: return memo[cur_N][cur_x] ret = ddp(cur_N+1, cur_x % S[cur_N]) ...
p03227 Tenka1 Programmer Beginner Contest - Measure
You are given a string S of length 2 or 3 consisting of lowercase English letters. If the length of the string is 2, print it as is; if the length is 3, print the string after reversing it. Constraints * The length of S is 2 or 3. * S consists of lowercase English letters. Input Input is given from Standard Input i...
```python S = input() if len(S) == 2: print(S) if len(S) == 3: print(S[2]+S[1]+S[0]) ```
p03375 AtCoder Regular Contest 096 - Everything on It
In "Takahashi-ya", a ramen restaurant, basically they have one menu: "ramen", but N kinds of toppings are also offered. When a customer orders a bowl of ramen, for each kind of topping, he/she can choose whether to put it on top of his/her ramen or not. There is no limit on the number of toppings, and it is allowed to ...
```python # coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline #文字列入力のときは注意 n,MOD = [int(i) for i in readline().split()] SIZE=3001; #MOD=10**9+7 #998244353 #ここを変更する SIZE += 1 inv = [0]*SIZE # inv[j] = j^{-1} mod MOD fac = [0]*SIZE # fac[j] = j! mod MOD finv = [0]*S...
p03537 CODE FESTIVAL 2017 Final (Parallel) - Combination Lock
Ringo has a string S. He can perform the following N kinds of operations any number of times in any order. * Operation i: For each of the characters from the L_i-th through the R_i-th characters in S, replace it with its succeeding letter in the English alphabet. (That is, replace `a` with `b`, replace `b` with `c` a...
```python import sys from operator import sub sys.setrecursionlimit(100000) def dfs(s, visited): visited.add(s) for v in links[s]: if v not in visited: dfs(v, visited) def solve(): checked = set() for i in range(ls // 2 + 1): if i in checked: continue ...
p03696 AtCoder Beginner Contest 064 - Insertion
You are given a string S of length N consisting of `(` and `)`. Your task is to insert some number of `(` and `)` into S to obtain a correct bracket sequence. Here, a correct bracket sequence is defined as follows: * `()` is a correct bracket sequence. * If X is a correct bracket sequence, the concatenation of `(`, X ...
```python n = int(input()) s = input() l, r = 0, 0 for i in s: if i == "(": r += 1 elif r > 0 and i == ")": r -= 1 else: l += 1 print("(" * l + s + ")" * r) ```
p04018 AtCoder Regular Contest 060 - Best Representation
Let x be a string of length at least 1. We will call x a good string, if for any string y and any integer k (k \geq 2), the string obtained by concatenating k copies of y is different from x. For example, `a`, `bbc` and `cdcdc` are good strings, while `aa`, `bbbb` and `cdcdcd` are not. Let w be a string of length at l...
```python from collections import Counter *W, = map(ord, input()) N = len(W) C = Counter(W) if len(C) == 1: print(N) print(1) exit(0) def z_algo(S): A = [0]*N i = 1; j = 0 A[0] = l = len(S) while i < l: while i+j < l and S[j] == S[i+j]: j += 1 A[i] = j i...
p00102 Matrix-like Computation
Your task is to develop a tiny little part of spreadsheet software. Write a program which adds up columns and rows of given table as shown in the following figure: <image> Input The input consists of several datasets. Each dataset consists of: n (the size of row and column of the given table) 1st row of the tab...
```python while True: n = int(input()) if not n: break mat = [] for _ in range(n): lst = list(map(int, input().split())) lst.append(sum(lst)) mat.append(lst) sum_lst = [] for i in range(len(mat[0])): s = 0 for j in range(n): s += mat[j][i] sum_lst.append(s) mat.append...
p00235 Sergeant Rian
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an ope...
```python while 1: N = int(input()) if N == 0:break R = [[0 for i in range(N+1)] for i in range(N+1)] def dfs_max(cur, pre): _max = -R[cur][pre] for i in range(N+1): if R[cur][i] > 0 and i != pre: _max = max(_max, dfs_max(i, cur) + R[cur][i]) # print('...
p00612 Hedro's Hexahedron
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory. The sludge is produced in a rectangular solid shaped tank whose size is N × N × 2. Let coordinate of two corner points of tank be (-N/2, -N/...
```python while 1: n=int(input()) if n==0:break a=0;i=1;b=n//2 while i*i<b:a+=((b-1)//i+1)-i-1;i+=1 a=(a+b-1)*2+i print(8*(a+n)) ```
p00750 The Most Powerful Spell
Long long ago, there lived a wizard who invented a lot of "magical patterns." In a room where one of his magical patterns is drawn on the floor, anyone can use magic by casting magic spells! The set of spells usable in the room depends on the drawn magical pattern. Your task is to compute, for each given magical patter...
```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 ...
p00888 The Two Men of the Japanese Alps
Two experienced climbers are planning a first-ever attempt: they start at two points of the equal altitudes on a mountain range, move back and forth on a single route keeping their altitudes equal, and finally meet with each other at a point on the route. A wise man told them that if a route has no point lower than the...
```python from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) if N == 0: return False P = [tuple(map(int, readline().split())) for i in range(N)] YS = set(y for x, y in P) Q = P[:] for i in range(N-1): ...
p01019 Cheat Case
Hint * One grid may be filled more than once * Even if it can be represented by one line segment such as '1', it may be represented by two or more line segments. Sample Input 1 Formula for Sample Input 1. Sample Input 2 Sample Input 2 formula. Another character may get inside the smallest rectangle that covers one...
```python dic = {((0, 0), (0, 1), (0, 2), (0, 3), (0, 4), (1, 0), (1, 4), (2, 0), (2, 1), (2, 2), (2, 3), (2, 4)):"0", ((0, 0), (0, 1), (0, 2), (0, 3), (0, 4)):"1", ((0, 0), (0, 2), (0, 3), (0, 4), (1, 0), (1, 2), (1, 4), (2, 0), (2, 1), (2, 2), (2, 4)):"2", ((0, ...
p01291 Wind Passages
Wind Corridor is a covered passageway where strong wind is always blowing. It is a long corridor of width W, and there are several pillars in it. Each pillar is a right prism and its face is a polygon (not necessarily convex). In this problem, we consider two-dimensional space where the positive x-axis points the east...
```python def solve(): from itertools import combinations from heapq import heappush, heappop def dot(c1, c2): return c1.real * c2.real + c1.imag * c2.imag def cross(c1, c2): return c1.real * c2.imag - c1.imag * c2.real # get distance between segment and point def ...
p01460 Matrix Operation
You are a student looking for a job. Today you had an employment examination for an IT company. They asked you to write an efficient program to perform several operations. First, they showed you an N \times N square matrix and a list of operations. All operations but one modify the matrix, and the last operation output...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, Q, A, B, C, D, E, F, G = map(int, readline().split()) d = 0; rx = 0; ry = 0 *X, = range(N) *Y, = range(N) def fc(d, x, y): if d == 0: return x, y if d == 1: return y, N...
p01772 A-Z Cat
A: A-Z Cat / A-Z Cat story Aizunyan is a second-year student who belongs to the programming contest club of Wakagamatsu High School, commonly known as the Prokon club. It's so cute. Aizu Nyan was asked by her friend Joy to take care of her cat. It is a rare cat called A-Z cat. Aizunyan named the A-Z cat he had entrus...
```python s,a,c=input(),1,0 for x in s: if x=='A':a=0 elif x=='Z' and not a:a,c=1,c+1 print('AZ'*c if c else -1) ```