name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
898_A. Rounding
Vasya has a non-negative integer n. He wants to round it to nearest integer, which ends up with 0. If n already ends up with 0, Vasya considers it already rounded. For example, if n = 4722 answer is 4720. If n = 5 Vasya can round it to 0 or to 10. Both ways are correct. For given n find out to which integer will Vasy...
```python n=int(input()) if(n%10==0): print(n) elif(n%10>5): print(n+(10-(n%10))) else: print(n-(n%10)) ```
919_B. Perfect Number
We consider a positive integer perfect, if and only if the sum of its digits is exactly 10. Given a positive integer k, your task is to find the k-th smallest perfect positive integer. Input A single line with a positive integer k (1 ≤ k ≤ 10 000). Output A single number, denoting the k-th smallest perfect integer....
```python rpta = [] def solve(pos, sum, arr): # if len(rpta) > 30: # return # # print(sum) if sum > 10 or pos >= 9: return else: if sum == 10: # print(sum, arr) rpta.append(arr) inicio = 0 if pos > 0 else 1 for i in range(inicio, min(10,1...
946_A. Partition
You are given a sequence a consisting of n integers. You may partition this sequence into two sequences b and c in such a way that every element belongs exactly to one of these sequences. Let B be the sum of elements belonging to b, and C be the sum of elements belonging to c (if some of these sequences is empty, the...
```python n = int(input()) a = list(map(int, input().split())) res = 0 for i in range(n): if a[i] > 0: res += a[i] else: res -= a[i] print(res) ```
96_D. Volleyball
Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self...
994_D. Open Communication
Two participants are each given a pair of distinct numbers from 1 to 9 such that there's exactly one number that is present in both pairs. They want to figure out the number that matches by using a communication channel you have access to without revealing it to you. Both participants communicated to each other a set ...
```python n, m = map(int, input().split()) p1 = list(map(int, input().split())) p2 = list(map(int, input().split())) cand = set() cc = [set() for i in range(n)] dd = [set() for i in range(m)] for i in range(n): for j in range(m): a, b = p1[2 * i], p1[2 * i + 1] c, d = p2[2 * j], p2[2 * j + 1] ...
p02636 AtCoder Grand Contest 046 - Secret Passage
Given is a string S consisting of `0` and `1`. Find the number of strings, modulo 998244353, that can result from applying the following operation on S zero or more times: * Remove the two characters at the beginning of S, erase one of them, and reinsert the other somewhere in S. This operation can be applied only whe...
```python def cmb(n, r, mod):#コンビネーションの高速計算  if ( r<0 or r>n ): return 0 r = min(r, n-r) return g1[n] * g2[r] * g2[n-r] % mod mod = 998244353 N = 2*10**3 g1 = [1]*(N+1) # 元テーブル g2 = [1]*(N+1) #逆元テーブル inverse = [1]*(N+1) #逆元テーブル計算用テーブル for i in range( 2, N + 1 ): g1[i]=( ( g1[i-1] * i ) % mod )...
p02767 AtCoder Beginner Contest 156 - Rally
There are N people living on a number line. The i-th person lives at coordinate X_i. You are going to hold a meeting that all N people have to attend. The meeting can be held at any integer coordinate. If you choose to hold the meeting at coordinate P, the i-th person will spend (X_i - P)^2 points of stamina to atte...
```python n=int(input()) x=tuple(map(int,input().split())) s=sum(x) ave=s//n+(1 if s/n>s//n+0.5 else 0) print(sum([pow(ave-i,2) for i in x])) ```
p02902 AtCoder Beginner Contest 142 - Pure
Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree a...
```python import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 input=lambda :sys.stdin.readline().rstrip() def resolve(): n,m=map(int,input().split()) E=[[] for _ in range(n)] for _ in range(m): a,b=map(lambda x:int(x)-1,input().split()) E[a].append(b) # bfs def...
p03037 AtCoder Beginner Contest 127 - Prison
We have N ID cards, and there are M gates. We can pass the i-th gate if we have one of the following ID cards: the L_i-th, (L_i+1)-th, ..., and R_i-th ID cards. How many of the ID cards allow us to pass all the gates alone? Constraints * All values in input are integers. * 1 \leq N \leq 10^5 * 1 \leq M \leq 10^5 * ...
```python N, M = map(int, input().split()) l, r = 1, N for m in range(M): L, R = map(int, input().split()) l = max(l,L) r = min(r,R) print(max(0,r-l+1)) ```
p03178 Educational DP Contest - Digit Sum
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7: * The sum of the digits in base ten is a multiple of D. Constraints * All values in input are integers. * 1 \leq K < 10^{10000} * 1 \leq D \leq 100 Input Input is given from Standard Input in the following ...
```python # -*- coding: utf-8 -*- import sys def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i ...
p03326 AtCoder Beginner Contest 100 - Patisserie ABC
Takahashi became a pastry chef and opened a shop La Confiserie d'ABC to celebrate AtCoder Beginner Contest 100. The shop sells N kinds of cakes. Each kind of cake has three parameters "beauty", "tastiness" and "popularity". The i-th kind of cake has the beauty of x_i, the tastiness of y_i and the popularity of z_i. Th...
```python N, M = map(int, input().split()) List = [list(map(int, input().split())) for _ in range(N)] from itertools import product ans = 0 for a, b, c in product([1, -1], repeat=3): tmp = [] for x, y, z in List: tmp.append(a*x+b*y+c*z) tmp.sort(reverse=True) ans = max(ans, sum(tmp[:M])) ...
p03480 AtCoder Beginner Contest 083 - Wide Flip
You are given a string S consisting of `0` and `1`. Find the maximum integer K not greater than |S| such that we can turn all the characters of S into `0` by repeating the following operation some number of times. * Choose a contiguous segment [l,r] in S whose length is at least K (that is, r-l+1\geq K must be satisfi...
```python s = input() tmp = [] for i in range(len(s)-1): if s[i] != s[i+1]: tmp.append(max(i+1,len(s)-(i+1))) if len(tmp) == 0: #元から全部同じ print(len(s)) else: print(min(tmp)) ```
p03647 AtCoder Regular Contest 079 - Cat Snuke and a Voyage
In Takahashi Kingdom, there is an archipelago of N islands, called Takahashi Islands. For convenience, we will call them Island 1, Island 2, ..., Island N. There are M kinds of regular boat services between these islands. Each service connects two islands. The i-th service connects Island a_i and Island b_i. Cat Snuk...
```python n,m = input().split() n = int(n) m = int(m) l = [[] for i in range(n)] for i in range(m): a,b = input().split() a = int(a) b = int(b) l[a-1].append(b-1) l[b-1].append(a-1) f = False for i in l[0]: for j in l[i]: if j == n-1: f = True break if f: pri...
p03803 AtCoder Beginner Contest 054 - One Card Poker
Alice and Bob are playing One Card Poker. One Card Poker is a two-player game using playing cards. Each card in this game shows an integer between `1` and `13`, inclusive. The strength of a card is determined by the number written on it, as follows: Weak `2` < `3` < `4` < `5` < `6` < `7` < `8` < `9` < `10` < `11` < `...
```python a,b=map(int,input().split()) a=(a-2)%13 b=(b-2)%13 if a<b:print('Bob') elif a>b:print('Alice') else:print('Draw') ```
p03971 CODE FESTIVAL 2016 qual B - Qualification simulator
There are N participants in the CODE FESTIVAL 2016 Qualification contests. The participants are either students in Japan, students from overseas, or neither of these. Only Japanese students or overseas students can pass the Qualification contests. The students pass when they satisfy the conditions listed below, from t...
```python N,A,B = map(int,input().split()) S = input() countA = 0 countB = 0 for i in range(len(S)): if S[i] == 'a' and countA + countB < A + B: countA += 1 print('Yes') elif S[i] == 'b' and countA + countB < A + B and countB < B: countB += 1 print('Yes') else: print('No') ```
p00060 Card Game
There is one card each with the numbers from "1" to "10", for a total of 10 cards. This card has numbers on the front and nothing on the back. Using this card, you and your opponent will play the game according to the following rules. 1. You and your opponent are dealt a total of two cards, one face up and one back up...
```python while 1: a=[i+1 for i in range(10)] try:b=list(map(int,input().split())) except:break for i in b:a.remove(i) print('YES' if sum([1 for i in a if i<=20-sum(b[:2])])/7>=0.5 else 'NO') ```
p00191 Baby Tree
Dr. Sato, a botanist, invented a number of special fertilizers for seedlings. When you give the fertilizer to the seedlings, the size of the seedlings changes in a blink of an eye. However, it was found that fertilizer has the following side effects. * The size of the seedlings does not change with the fertilizer give...
```python # AOJ 0191: Baby Tree # Python3 2018.6.20 bal4u while True: n, m = list(map(int, input().split())) if n == 0: break d = [[0.0 for j in range(n)] for i in range(n)] for i in range(n): d[i] = list(map(float, input().split())) dp = [[0.0 for j in range(n)] for k in range(m)] for i in range(n): dp[0][i] ...
p00346 Quiet Town
Ekiden competitions are held every year in Aizukuni. The country of Aiz is dotted with N towns, each numbered from 1 to N. Several towns are connected by roads that allow them to come and go directly to each other. You can also follow several roads between any town. The course of the tournament is decided as follows. ...
```python from heapq import heappush, heappop from collections import deque n, r = map(int, input().split()) G = [[] for i in range(n)] for i in range(r): s, t, d = map(int, input().split()) G[s-1].append((t-1, d)) G[t-1].append((s-1, d)) INF = 10**18 def dijkstra(s): dist = [INF]*n dist[s] = 0 ...
p00542 Selecting Subjects
problem JOI took six subjects: physics, chemistry, biology, earth science, history, and geography. Each test was scored on a 100-point scale. JOI chooses 3 subjects from 4 subjects of physics, chemistry, biology, and earth science, and 1 subject from 2 subjects of history and geography. When choosing a subject so th...
```python lst=[] for i in range(6): n=int(input()) lst.append(n) lst1=lst[0:4] lst2=lst[4:6] lst1.sort(reverse=True) lst3=lst1[0:3] a=sum(lst3) b=max(lst2) print(a+b) ```
p00706 Get Many Persimmon Trees
Seiji Hayashi had been a professor of the Nisshinkan Samurai School in the domain of Aizu for a long time in the 18th century. In order to reward him for his meritorious career in education, Katanobu Matsudaira, the lord of the domain of Aizu, had decided to grant him a rectangular estate within a large field in the Ai...
```python def main(): while True: N = int(input()) if N==0: exit() (W, H) = [int(x) for x in input().split()] persimmon = [[0 for j in range(100)] for i in range(100)] for _ in range(N): (x, y) = [int(x) for x in input().split()] persimmon...
p00845 How I Wonder What You Are!
One of the questions children often ask is "How many stars are there in the sky?" Under ideal conditions, even with the naked eye, nearly eight thousands are observable in the northern hemisphere. With a decent telescope, you may find many more, but, as the sight field will be limited, you may find much less at a time....
```python import math while True: n = int(input()) if not n: break stars = [list(map(float, input().split())) for i in range(n)] is_watch_star = [False for i in range(n)] scope = [list(map(float, input().split())) for j in range(int(input()))] for i in scope: a = (i[0] ** 2 + ...
p01109 Income Inequality
Income Inequality We often compute the average as the first step in processing statistical data. Yes, the average is a good tendency measure of data, but it is not always the best. In some cases, the average may hinder the understanding of the data. For example, consider the national income of a country. As the term ...
```python while True: n=int(input()) if n==0: break lst=list(map(int,input().split())) x=sum(lst)/n ans=0 for i in lst: if x>=i: ans+=1 print(ans) ```
p01724 Phutball
Ikta, who hates to lose, has recently been enthusiastic about playing games using the Go board. However, neither Go nor Gomoku can beat my friends at all, so I decided to give a special training to the lesser-known game Phutball. This game is a difficult game, so I decided to give special training so that I could win ...
```python def main(): N = 20; M = 15 MP = [[-1]*M for i in range(N)] L = 0 for i in range(N-1): s = input() for j in range(M): c = s[j] if c == 'O': sx = j; sy = i elif c == 'X': MP[i][j] = L L += 1 ...
p01997 Right triangle
problem Given the lengths of $ 2 $ sides that are not the hypotenuse of a right triangle, $ A $ and $ B $. The side of length $ A $ overlaps the $ x $ axis, and the side of length $ B $ overlaps the $ y $ axis. Do the following: 1. Rotate the triangle around the $ x $ axis. 2. Rotate the shape created by performing ...
```python import math a,b=map(int,input().split()) print(b**3*math.pi*(4/3)) ```
p02284 Binary Search Tree II
Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorde...
```python class Node(object): root = None def __init__(self, key, parent=None, left=None, right=None): self.key = key self.parent = parent self.left = left self.right = right self.height = None @classmethod def insert(cls, z): y = None x = cls.ro...
p02431 Vector
For a dynamic array $A = \\{a_0, a_1, ...\\}$ of integers, perform a sequence of the following operations: * pushBack($x$): add element $x$ at the end of $A$ * randomAccess($p$):print element $a_p$ * popBack(): delete the last element of $A$ $A$ is a 0-origin array and it is empty in the initial state. Constraints...
```python q = int(input()) A = [] ans = [] for i in range(q): q = str(input()) if q[0] == "0": #pushBack A.append(int(q[2:])) elif q[0] == "1": #randamAccess # ans.append(A[int(q[2:])]) print(A[int(q[2:])]) else: #popBack A.pop() ```
1043_B. Lost Array
Bajtek, known for his unusual gifts, recently got an integer array x_0, x_1, …, x_{k-1}. Unfortunately, after a huge array-party with his extraordinary friends, he realized that he'd lost it. After hours spent on searching for a new toy, Bajtek found on the arrays producer's website another array a of length n + 1. As...
```python arr_len = int(input()) a = [0] + [int(x) for x in input().split(" ")] x = [0] * arr_len res = [] for i in range(1, arr_len + 1): x[i-1] = a[i]-a[i-1] def ok(k, x ,a): for i in range(0, arr_len): tmp = x[i%k] + a[i] if tmp != a[i + 1]: return False return True ...
1107_E. Vasya and Binary String
Vasya has a string s of length n consisting only of digits 0 and 1. Also he has an array a of length n. Vasya performs the following operation until the string becomes empty: choose some consecutive substring of equal characters, erase it from the string and glue together the remaining parts (any of them can be empty...
```python n = int(input()) s = input() ai = [0] + list(map(int,input().split())) ar = [ai[i] for i in range(n+1)] for i in range(1,n): num = 0 for j in range(0,(i+1) // 2 + 1): ar[i] = max(ar[i],ar[j] + ar[i-j]) ar2 = [] num = 1 for i in range(1,n): if s[i] == s[i-1]: num += 1 else: ...
1155_B. Game with Telephone Numbers
A telephone number is a sequence of exactly 11 digits such that its first digit is 8. Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro...
```python n=int(input()) s=input() # for i in range(n-10) : # if s['i']!='8' # if s[:n-10].count('8')%2==0: # print(s[:n-10]) # print("YES") # else: print("NO") c=n-10-(s[:n-10].count('8')) if c<s[:n-10].count('8'): print("YES") else: print("NO") ```
1177_A. Digits Sequence (Easy Edition)
Let's write all the positive integer numbers one after another from 1 without any delimiters (i.e. as a single string). It will be the infinite sequence starting with 123456789101112131415161718192021222324252627282930313233343536... Your task is to print the k-th digit of this sequence. Input The first and only lin...
```python x = ''.join(str(i) for i in range(1, 5000)) k = int(input()) print(x[k-1]) ```
1195_E. OpenStreetMap
Seryozha conducts a course dedicated to building a map of heights of Stepanovo recreation center. He laid a rectangle grid of size n × m cells on a map (rows of grid are numbered from 1 to n from north to south, and columns are numbered from 1 to m from west to east). After that he measured the average height of each c...
```python def slide_min(tl,ql,val): res=[0]*(tl-ql+1) q=[0]*tl s=0 t=0 for i in range(0,tl): while s<t and val[q[t-1]]>=val[i]: t-=1 q[t]=i t+=1 if (i-ql+1)>=0: res[i-ql+1]=val[q[s]] if q[s]==(i-ql+1): s+=1 return res def slide_min2(tl,ql,val): res=0 q=[0]*tl...
1213_A. Chips Moving
You are given n chips on a number line. The i-th chip is placed at the integer coordinate x_i. Some chips can have equal coordinates. You can perform each of the two following types of moves any (possibly, zero) number of times on any chip: * Move the chip i by 2 to the left or 2 to the right for free (i.e. replace...
```python n = int(input()) v = list(map(int, input().split())) a = [] b = [] for x in v: a.append(x) if x & 1 else b.append(x) print(min(len(a), len(b))) ```
1236_B. Alice and the List of Presents
Alice got many presents these days. So she decided to pack them into boxes and send them to her friends. There are n kinds of presents. Presents of one kind are identical (i.e. there is no way to distinguish two gifts of the same kind). Presents of different kinds are different (i.e. that is, two gifts of different ki...
```python '''Author- Akshit Monga''' from sys import stdin, stdout input = stdin.readline mod=10**9+7 t = 1 for _ in range(t): n,m=map(int,input().split()) print(pow((pow(2,m,mod)-1),n,mod)) ```
1254_A. Feeding Chicken
Long is a huge fan of CFC (Codeforces Fried Chicken). But the price of CFC is increasing, so he decides to breed the chicken on his own farm. His farm is presented by a rectangle grid with r rows and c columns. Some of these cells contain rice, others are empty. k chickens are living on his farm. The number of chicken...
```python def distribute(n, person): q, m = divmod(n, person) if m==0: return [q] * person else: return [q]*(person-m)+[q+1]*m import sys input = sys.stdin.readline T = int(input()) CHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" for _ in range(T): R, C, K = map(...
1277_F. Beautiful Rectangle
You are given n integers. You need to choose a subset and put the chosen numbers in a beautiful rectangle (rectangular matrix). Each chosen number should occupy one of its rectangle cells, each cell must be filled with exactly one chosen number. Some of the n numbers may not be chosen. A rectangle (rectangular matrix)...
```python def play(arr): n = len(arr) number2Count = {} for p in arr: number2Count[p] = number2Count.get(p, 0) + 1 count2Numbers = {} maxCnt = 0 for num in number2Count: cnt = number2Count[num] if not cnt in count2Numbers: count2Numbers[cnt] = [] ...
1321_A. Contest for Robots
Polycarp is preparing the first programming contest for robots. There are n problems in it, and a lot of robots are going to participate in it. Each robot solving the problem i gets p_i points, and the score of each robot in the competition is calculated as the sum of p_i over all problems i solved by it. For each prob...
```python n = int(input()) r = list(map(int,input().split())) b = list(map(int,input().split())) f = 0 s = 0 for i in range(n): if r[i] > b[i]: f += 1 elif r[i] < b[i]: s += 1 if f == 0: print(-1) else: print((s + f) // f) ```
133_E. Logo Turtle
A lot of people associate Logo programming language with turtle graphics. In this case the turtle moves along the straight line and accepts commands "T" ("turn around") and "F" ("move 1 unit forward"). You are given a list of commands that will be given to the turtle. You have to change exactly n commands from the lis...
```python import sys import math INF = -100000000 memo = dict() def func(line, r): if line in memo and r in memo[line]: return memo[line][r] if len(line) == 1: which = line[0] == 'T' if r % 2 == 1: which = not which if which: return [INF, INF, 0, 0] ...
1382_B. Sequential Nim
There are n piles of stones, where the i-th pile has a_i stones. Two people play a game, where they take alternating turns removing stones. In a move, a player may remove a positive number of stones from the first non-empty pile (the pile with the minimal index, that has at least one stone). The first player who canno...
```python t=int(input()) for _ in range(t): n=int(input()) a=list(map(lambda x:int(x),input().split())) first_nonforced_index=-1 for i in range(0,len(a)): if a[i]!=1: first_nonforced_index=i break if first_nonforced_index==-1: if len(a)%2==0: print...
1425_A. Arena of Greed
Lately, Mr. Chanek frequently plays the game Arena of Greed. As the name implies, the game's goal is to find the greediest of them all, who will then be crowned king of Compfestnesia. The game is played by two people taking turns, where Mr. Chanek takes the first turn. Initially, there is a treasure chest containing N...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): pass # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode...
1497_E1. Square-free division (easy version)
This is the easy version of the problem. The only difference is that in this version k = 0. There is an array a_1, a_2, …, a_n of n positive integers. You should divide it into a minimal number of continuous segments, such that in each segment there are no two numbers (on different positions), whose product is a perfe...
```python import sys input = sys.stdin.readline def is_Prime(i): if i == 2: return True if i % 2 == 0 or i == 1: return False s = int(i ** (1 / 2)) while True: if s == 1: return True if i % s == 0: return False s -= 1 t = int(input()) sq ...
151_D. Quantity of Strings
Just in case somebody missed it: this winter is totally cold in Nvodsk! It is so cold that one gets funny thoughts. For example, let's say there are strings with the length exactly n, based on the alphabet of size m. Any its substring with length equal to k is a palindrome. How many such strings exist? Your task is to ...
```python import math def pow(a,b,p): res = 1 while(b > 0): if b%2 == 1: res = (res*a)%p a = (a*a)%p b = int(b/2) return res n,m,k = list(map(int,input().strip().split())) p = 10 ** 9 + 7 if k > n or k == 1: print(pow(m, n, p)) elif k == n: print(pow(m, ma...
1547_D. Co-growing Sequence
A sequence of non-negative integers a_1, a_2, ..., a_n is called growing if for all i from 1 to n - 1 all ones (of binary representation) in a_i are in the places of ones (of binary representation) in a_{i + 1} (in other words, a_i \:\&\: a_{i + 1} = a_i, where \& denotes [bitwise AND](http://tiny.cc/xpy9uz)). If n = 1...
```python # _ ##################################################################################################################### def minCo_growingSequenceWith(array): sequence, prevValue = [], 0 for value in array: n = prevValue&(prevValue^value) prevValue = value^n sequence.append(n...
175_A. Robot Bicorn Attack
Vasya plays Robot Bicorn Attack. The game consists of three rounds. For each one a non-negative integer amount of points is given. The result of the game is the sum of obtained points. Vasya has already played three rounds and wrote obtained points one by one (without leading zeros) into the string s. Vasya decided to...
```python def f(t, k, s): if k == 1: if t[0] == '0' and len(t) > 1: return -1 d = int(t) if d > 1000000: return -1 return s + d if t[0] == '0': return f(t[1: ], k - 1, s) p = [(t[i: ], int(t[: i])) for i in range(1, len(t) + 2 - k)] return max(f(a, k...
195_B. After Training
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has n balls and m baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to m, correspondingly. The ...
```python n,m = map(int,input().split()) l = [] if m%2 == 1: l = [(m+1)//2] for i in range((m-1)//2,0,-1): l.append(i) l.append(m-i+1) else: l = [] for i in range(m//2,0,-1): l.append(i) l.append(m-i+1) for i in range(n): print(l[i%len(l)]) ```
219_B. Special Offer! Super Price 999 Bourles!
Polycarpus is an amateur businessman. Recently he was surprised to find out that the market for paper scissors is completely free! Without further ado, Polycarpus decided to start producing and selling such scissors. Polycaprus calculated that the optimal celling price for such scissors would be p bourles. However, he...
```python p, d = input().split() p = int(p); d = int(d) ans = p = p + 1 i = 10 while i <= 1000000000000000000: if p % i <= d: ans = p - p % i i *= 10 print(ans - 1) ```
242_D. Dispute
Valera has n counters numbered from 1 to n. Some of them are connected by wires, and each of the counters has a special button. Initially, all the counters contain number 0. When you press a button on a certain counter, the value it has increases by one. Also, the values recorded in all the counters, directly connecte...
```python from queue import Queue n,m = map(int,input().split()) e = [[]for i in range(n+1)] b = [0]*n for i in range(m): u,v = map(int,input().split()) e[u-1].append(v-1) e[v-1].append(u-1) ans = 0 q = Queue() a = input().split() ai = [-1]*n c=0 mask = [False]*n for i in a: inti = int(i) ai[c] = in...
268_B. Buttons
Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you should press the buttons in a certain order to open the lock. When you push some button, it either stays pressed into the lock (that means that you've guessed correctly and pushed the button that goes next in the sequenc...
```python #mahade.......... n=int(input()) print((n**3+5*n)//6) ```
290_E. HQ
The famous joke programming language HQ9+ has only 4 commands. In this problem we will explore its subset — a language called HQ... Input The only line of the input is a string between 1 and 106 characters long. Output Output "Yes" or "No". Examples Input HHHH Output Yes Input HQHQH Output No Input H...
```python import sys s = input() qc = s.count('Q') qs = int(qc ** 0.5) hc = s.count('H') if qs == 0: print('Yes') sys.exit(0) if not qc == qs ** 2: print('No') sys.exit(0) if not hc % (qs + 1) == 0: print('No') sys.exit(0) t = s.split('Q') pre = len(t[0]) // 2 suf = 0 if len(t) == 1 else len(t...
339_B. Xenia and Ringroad
Xenia lives in a city that has n houses built along the main ringroad. The ringroad houses are numbered 1 through n in the clockwise order. The ringroad traffic is one way and also is clockwise. Xenia has recently moved into the ringroad house number 1. As a result, she's got m things to do. In order to complete the i...
```python def main(n, m, lst): count = 0 lst = [1] + lst for i in range(1, len(lst)): if lst[i] >= lst[i-1]: count += lst[i] - lst[i-1] else: count += n - lst[i-1] + lst[i] return count n, m = [int(x) for x in input().split()] lst = list(map(int, input().split())...
385_B. Bear and Strings
The bear has a string s = s1s2... s|s| (record |s| is the string's length), consisting of lowercase English letters. The bear wants to count the number of such pairs of indices i, j (1 ≤ i ≤ j ≤ |s|), that string x(i, j) = sisi + 1... sj contains at least one string "bear" as a substring. String x(i, j) contains strin...
```python a=input() ans=0 for i in range(0,len(a)-3): b=a.find("bear",i) if b>=0: ans+=len(a)-3-b print(ans) ```
406_A. Unusual Product
Little Chris is a huge fan of linear algebra. This time he has been given a homework about the unusual square of a square matrix. The dot product of two integer number vectors x and y of size n is the sum of the products of the corresponding components of the vectors. The unusual square of an n × n square matrix A is ...
```python from sys import stdin n = int(stdin.readline()) dot = 0 j = 0 for i in range(n): line = stdin.readline() if line[j] == '1': dot ^= 1 j += 2 out = [] stdin.readline() for query in stdin: if len(query) < 3: out.append('1' if dot else '0') else: dot ^= 1 print(''.jo...
433_B. Kuriyama Mirai's Stones
Kuriyama Mirai has killed many monsters and got many (namely n) stones. She numbers the stones from 1 to n. The cost of the i-th stone is vi. Kuriyama Mirai wants to know something about these stones so she will ask you two kinds of questions: 1. She will tell you two numbers, l and r (1 ≤ l ≤ r ≤ n), and you should...
```python t = int(input()) lst = list(map(int,input().split())) x = lst[:] x.sort() l_st = [0] lst1 = [0] k = 0 k1 = 0 for i in range(t): k += lst[i] l_st.append(k) k1 += x[i] lst1.append(k1) n = int(input()) for i in range(n): t_pe , l , r = map(int,input().split()) if(t_pe == 1): print...
478_B. Random Teams
n participants of the competition were split into m teams in some manner so that each team has at least one participant. After the competition each pair of participants from the same team became friends. Your task is to write a program that will find the minimum and the maximum number of pairs of friends that could ha...
```python #code n,m = map(int,input().split()) k = n//m z = n - m print(m*k*(k-1)//2+k*(n%m),(z+1)*z//2) ```
500_D. New Year Santa Network
New Year is coming in Tree World! In this world, as the name implies, there are n cities connected by n - 1 roads, and for any two distinct cities there always exists a path between them. The cities are numbered by integers from 1 to n, and the roads are numbered by integers from 1 to n - 1. Let's define d(u, v) as tot...
```python from queue import Queue import sys cost = [] def readarray(): return map(int, input().split(' ')) n = int(input()) graph = [[] for i in range(n)] for i in range(n - 1): u, v, c = readarray() u, v = u - 1, v - 1 cost.append(c) graph[u].append((v, i)) graph[v].append((u, i)) order = [] used = [0] *...
526_B. Om Nom and Dark Park
Om Nom is the main character of a game "Cut the Rope". He is a bright little monster who likes visiting friends living at the other side of the park. However the dark old parks can scare even somebody as fearless as Om Nom, so he asks you to help him. <image> The park consists of 2n + 1 - 1 squares connected by roads...
```python # print ("Enter n") n = int(input()) alen = 2**(n+1) a = [0 for i in range(alen)] # print ("Enter all values on the same line") inp = input().split() for i in range(len(inp)): a[i+2] = int(inp[i]) answer = 0 while (n > 0): index = 2**n for i in range(index, index*2, 2): left = a[i] ...
551_C. GukiZ hates Boxes
Professor GukiZ is concerned about making his way to school, because massive piles of boxes are blocking his way. In total there are n piles of boxes, arranged in a line, from left to right, i-th pile (1 ≤ i ≤ n) containing ai boxes. Luckily, m students are willing to help GukiZ by removing all the boxes from his way...
```python # -*- coding: utf-8 -*- # @Time : 2021/1/15 5:25 下午 # @Author : qu # @Email : quzhenqing@zju.edu.cn # @File : C. GukiZ hates Boxes.py from sys import stdin # n, m = map(int, stdin.buffer.readline().split()) a = list(map(int, stdin.buffer.readline().split())) max_not_zero = 0 for index, value in enu...
578_D. LCS Again
You are given a string S of length n with each character being one of the first m lowercase English letters. Calculate how many different strings T of length n composed from the first m lowercase English letters exist such that the length of LCS (longest common subsequence) between S and T is n - 1. Recall that LCS ...
```python n, m = map(int, input().split()) s = input() p = c = 0 for i in range(1, n): if s[i] == s[i - 1]: c += n * (m - 1) p = i elif s[i] != s[i - 2]: p = i - 1 c += i - p ans = n * n * (m - 1) - c print(ans) ```
5_B. Center Alignment
Almost every text editor has a built-in function of center text alignment. The developers of the popular in Berland text editor «Textpad» decided to introduce this functionality into the fourth release of the product. You are to implement the alignment in the shortest possible time. Good luck! Input The input file c...
```python import sys; lines = []; m = 0; for s in sys.stdin: lines.append(s.rstrip()); for s in lines: m = max(m, len(s)); turn_is_left = 1; sys.stdout.write('*' * (m + 2) + '\n'); for s in lines: l = len(s); p = q = (m - l) // 2; if ((m - l) % 2): if turn_is_left: q += 1; else: p += ...
621_E. Wet Shark and Blocks
There are b blocks of digits. Each one consisting of the same n digits, which are given to you in the input. Wet Shark must choose exactly one digit from each block and concatenate all of those digits together to form one large integer. For example, if he chooses digit 1 from the first block and digit 2 from the second...
```python import os from io import BytesIO #input = BytesIO(os.read(0, os.fstat(0).st_size)).readline def main(): mod = 10**9 + 7 n,b,k,x = map(int,input().split()) x2 = x + 1 ai = list(map(int,input().split())) ai2 = [0]*x2 for i in range(n): ai2[ai[i] % x] += 1 ai2[-1] = 1 de...
670_C. Cinema
Moscow is hosting a major international conference, which is attended by n scientists from different countries. Each of the scientists knows exactly one language. For convenience, we enumerate all languages of the world with integers from 1 to 109. In the evening after the conference, all n scientists decided to go to...
```python n = int(input()) d = {} for i in list(map(int, input().split())): if i in d: d[i] += 1 else: d[i] = 1 m = int(input()) res = [(0, 0)] * m b = list(map(int, input().split())) c = list(map(int, input().split())) for i in range(m): if b[i] not in d: d[b[i]] = 0 if c[i] not in d: d[c[i]] = 0 r...
737_B. Sea Battle
Galya is playing one-dimensional Sea Battle on a 1 × n grid. In this game a ships are placed on the grid. Each of the ships consists of b consecutive cells. No cell can be part of two ships, however, the ships can touch each other. Galya doesn't know the ships location. She can shoot to some cells and after each shot ...
```python n,a,b,k=map(int,input().split()) A=input() B=A.split('1') C=[] l=1 for i in B: if len(i)>=b: for j in range(b-1,len(i),b): C.append(j+l) l+=len(i)+1 C=C[:len(C)-a+1] print(len(C)) print(' '.join(list(map(str,C)))) # Made By Mostafa_Khaled ```
761_A. Dasha and Stairs
On her way to programming school tiger Dasha faced her first test — a huge staircase! <image> The steps were numbered from one to infinity. As we know, tigers are very fond of all striped things, it is possible that it has something to do with their color. So on some interval of her way she calculated two values — th...
```python string=input() a,b=map(int,string.split(' ')) if a==0 and b==0: print('NO') elif a-b==1 or b-a==1: print('YES') elif a==b: print('YES') else: print('NO') ```
784_C. INTERCALC
DO YOU EXPECT ME TO FIND THIS OUT? WHAT BASE AND/XOR LANGUAGE INCLUDES string? DON'T BYTE OF MORE THAN YOU CAN CHEW YOU CAN ONLY DISTORT THE LARGEST OF MATHEMATICS SO FAR SAYING "ABRACADABRA" WITHOUT A MAGIC AND WON'T DO YOU ANY GOOD THE LAST STACK RUPTURES. ALL DIE. OH, THE EMBARRASSMENT! I HAVE NO ARRAY AND I M...
```python input() a = list(map(int, input().split())) print(max(a) ^ a[-1]) ```
805_B. 3-palindrome
In the beginning of the new year Keivan decided to reverse his name. He doesn't like palindromes, so he changed Naviek to Navick. He is too selfish, so for a given n he wants to obtain a string of n characters, each of which is either 'a', 'b' or 'c', with no palindromes of length 3 appearing in the string as a substr...
```python def check(s): for i in range(len(s)//2): if s[i] != s[-(i+1)]: return(True) return(False) n = int(input()) sub = "aabb" ans = "" mod = n //4 ans += sub*mod for i in range(n%4): ans += sub[i] print(ans) # print(check(ans)) ```
830_B. Cards Sorting
Vasily has a deck of cards consisting of n cards. There is an integer on each of the cards, this integer is between 1 and 100 000, inclusive. It is possible that some cards have the same integers on them. Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on...
```python # -*- coding: utf-8 -*- import sys # fout = open("output.txt", "w") fin = sys.stdin # fin = open("input.txt", "r") fout = sys.stdout n = int(fin.readline()) a = list(map(int, fin.readline().split())) def solution(n, a): sorted_arr = [(i, elem) for i, elem in enumerate(a)] sorted_arr.sort(key=lamb...
851_C. Five Dimensional Points
You are given set of n points in 5-dimensional space. The points are labeled from 1 to n. No two points coincide. We will call point a bad if there are different points b and c, not equal to a, from the given set such that angle between vectors <image> and <image> is acute (i.e. strictly less than <image>). Otherwise,...
```python d = lambda i, j, k: sum((a - c) * (b - c) for a, b, c in zip(p[i], p[j], p[k])) * (i != j) n = int(input()) r = range(n) p = [list(map(int, input().split())) for i in r] t = [k + 1 for k in r if all(d(i, j, k) <= 0 for i in r for j in r)] if n < 12 else [] for q in [len(t)] + t: print(q) ```
89_D. Space mines
Once upon a time in the galaxy of far, far away... Darth Wader found out the location of a rebels' base. Now he is going to destroy the base (and the whole planet that the base is located at), using the Death Star. When the rebels learnt that the Death Star was coming, they decided to use their new secret weapon — sp...
```python import sys, math def dist(a,b): return pow((a[0] - b[0])**2 + (a[1] - b[1])**2 + (a[2] - b[2])**2,0.5) def vxv(v1,v2): x = -v1[2] * v2[1] + v1[1] * v2[2] y = -v1[0] * v2[2] + v1[2] * v2[0] z = -v1[1] * v2[0] + v1[0] * v2[1] return (x,y,z) readline = sys.stdin.readline s1,s2,s3,v1,v2,v3,R ...
949_D. Curfew
Instructors of Some Informatics School make students go to bed. The house contains n rooms, in each room exactly b students were supposed to sleep. However, at the time of curfew it happened that many students are not located in their assigned rooms. The rooms are arranged in a row and numbered from 1 to n. Initially,...
```python read = lambda: map(int, input().split()) n, d, b = read() d += 1 t, a = 0, [0] * (n + 1) for i, x in enumerate(read()): t += x a[i + 1] = t print(max(i - min(a[min(n, i * d)], (a[n] - a[max(0, n - i * d)])) // b for i in range(n + 3 >> 1))) ```
977_C. Less or Equal
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≤ x ≤ 10^9) such that exactly k elements of given sequence are less than or equal to x. Note that the sequence can contain equal elements. If there is no such x, print "-1" (w...
```python # import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') t = 1 # t = int(input()) while t: t -= 1 n, k = list(map(int, input().split())) a = list(map(int, input().split())) # s = input() a.sort() if k == 0: ans = a[0]-1 else: ...
997_A. Convert to Ones
You've got a string a_1, a_2, ..., a_n, consisting of zeros and ones. Let's call a sequence of consecutive elements a_i, a_{i + 1}, …, a_j (1≤ i≤ j≤ n) a substring of string a. You can apply the following operations any number of times: * Choose some substring of string a (for example, you can choose entire strin...
```python n, x, y = [int(s) for s in input().split(' ')] a = input() z = len([t for t in a.split('1') if t]) ans = max(min(z * y, y + (z - 1) * x), 0) print(ans) ```
p02653 AtCoder Grand Contest 045 - Range Set
Snuke has a string x of length N. Initially, every character in x is `0`. Snuke can do the following two operations any number of times in any order: * Choose A consecutive characters in x and replace each of them with `0`. * Choose B consecutive characters in x and replace each of them with `1`. Find the number o...
```python MOD = 10 ** 9 + 7 n, a, b = map(int, input().split()) if a > b: a, b = b, a dp_1s = [0] * b for l in range(a + 2, b): dp = [[0, 0] for _ in range(l + 1)] # at i, 0/1 precedes dp[1][1] = 1 for i in range(1, l): dp[i + 1][0] = (dp[i + 1][0] + dp[i][0]) % MOD dp[i + 1][1] = (dp[...
p02782 AtCoder Beginner Contest 154 - Many Many Paths
Snuke is standing on a two-dimensional plane. In one operation, he can move by 1 in the positive x-direction, or move by 1 in the positive y-direction. Let us define a function f(r, c) as follows: * f(r,c) := (The number of paths from the point (0, 0) to the point (r, c) that Snuke can trace by repeating the operati...
```python r1, c1, r2, c2 = map(int, input().split()) mod = int(1e+9) + 7 def inved(x): a, b, c, d, k, l = 1, 0, 0, 1, x, mod while l != 0: a, b, c, d = c, d, a - c * (k // l), b - d * (k // l) k, l = l, k % l return a % mod frac = [1] for i in range(r2 + c2 + 2): frac.append(((i+1) * frac[i]) % mod) fra...
p02917 AtCoder Beginner Contest 140 - Maximal Value
There is an integer sequence A of length N whose values are unknown. Given is an integer sequence B of length N-1 which is known to satisfy the following: B_i \geq \max(A_i, A_{i+1}) Find the maximum possible sum of the elements of A. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 0 \leq B_i...
```python n = int(input()) b = list(map(int,input().split())) sum = b[0]+b[n-2] for i in range(n-2): sum += min(b[i],b[i+1]) print(sum) ```
p03053 AtCoder Grand Contest 033 - Darker and Darker
You are given a grid of squares with H horizontal rows and W vertical columns, where each square is painted white or black. HW characters from A_{11} to A_{HW} represent the colors of the squares. A_{ij} is `#` if the square at the i-th row from the top and the j-th column from the left is black, and A_{ij} is `.` if t...
```python from collections import deque from itertools import chain H, W = map(int, input().split()) G = chain.from_iterable([[s == '#' for s in input()] for _ in range(H)]) dist = [0]*(H*W) B = deque([i for i, g in enumerate(G) if g]) visited = set(B) while B: vij = B.pop() for dij in (W, -W, 1, -1): n...
p03197 CADDi 2018 - Harlequin
There is an apple tree that bears apples of N colors. The N colors of these apples are numbered 1 to N, and there are a_i apples of Color i. You and Lunlun the dachshund alternately perform the following operation (starting from you): * Choose one or more apples from the tree and eat them. Here, the apples chosen at ...
```python N = int(input()) A = [int(input()) for i in range(N)] for a in A: if a%2: print('first') exit() print('second') ```
p03344 AtCoder Regular Contest 098 - Donation
There is a simple undirected graph with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects Vertex U_i and V_i. Also, Vertex i has two predetermined integers A_i and B_i. You will play the following game on this graph. First, choose one vertex and stan...
```python class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: ...
p03504 AtCoder Beginner Contest 080 - Recording
Joisino is planning to record N TV programs with recorders. The TV can receive C channels numbered 1 through C. The i-th program that she wants to record will be broadcast from time s_i to time t_i (including time s_i but not t_i) on Channel c_i. Here, there will never be more than one program that are broadcast on ...
```python import sys def MI(): return map(int,sys.stdin.readline().rstrip().split()) N,C = MI() A = [[0]*(10**5+2) for i in range(C+1)] for i in range(N): s,t,c = MI() A[c][s] += 1 A[c][t+1] -= 1 from itertools import accumulate for i in range(1,C+1): A[i] = list(accumulate(A[i])) # A[i][j] が正 ⇔ チャン...
p03665 AtCoder Grand Contest 017 - Biscuits
There are N bags of biscuits. The i-th bag contains A_i biscuits. Takaki will select some of these bags and eat all of the biscuits inside. Here, it is also possible to select all or none of the bags. He would like to select bags so that the total number of biscuits inside is congruent to P modulo 2. How many such wa...
```python N, P = map(int, input().split()) O = sum([int(a) % 2 for a in input().split()]) E = N - O fa = [1] for i in range(1, 51): fa.append(fa[-1] * i) ans = 0 for i in range(P, O+1, 2): ans += fa[O] // (fa[i] * fa[O-i]) print(ans * 2**E) ```
p03820 AtCoder Regular Contest 068 - Solitaire
Snuke has decided to play with N cards and a deque (that is, a double-ended queue). Each card shows an integer from 1 through N, and the deque is initially empty. Snuke will insert the cards at the beginning or the end of the deque one at a time, in order from 1 to N. Then, he will perform the following action N times...
```python def cmb(n, r, mod):#コンビネーションの高速計算  if ( r<0 or r>n ): return 0 r = min(r, n-r) return g1[n] * g2[r] * g2[n-r] % mod mod = 10**9+7 #出力の制限 N = 5000 g1 = [1, 1] # 元テーブル g2 = [1, 1] #逆元テーブル inverse = [0, 1] #逆元テーブル計算用テーブル for i in range( 2, N + 1 ): g1.append( ( g1[-1] * i ) % mod ) ...
p03987 AtCoder Grand Contest 005 - Minimum Sum
One day, Snuke was given a permutation of length N, a_1, a_2, ..., a_N, from his friend. Find the following: <image> Constraints * 1 ≦ N ≦ 200,000 * (a_1, a_2, ..., a_N) is a permutation of (1, 2, ..., N). Input The input is given from Standard Input in the following format: N a_1 a_2 ... a_N Output Print th...
```python import sys input = sys.stdin.readline import bisect n = int(input()) A = list(map(int,input().split())) 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 &...
p00075 BMI
Obesity is cited as the cause of many adult diseases. In the past, with a few exceptions, it was unrelated to high school students. However, it is no longer unrealistic to suffer from lack of exercise due to excessive studying for entrance exams, or to become bulimia nervosa due to stress. It may be a problem that high...
```python try: while True: id,w,h = map(float,input().split(",")) bmi = w / (h*h) if bmi >= 25.0: print(int(id)) except: pass ```
p00207 Block
Relative B came to Mr. A's house. He is 3 years old and loves blocks. The block he has is shaped like Figure 1. <image> Figure 1 Mr. B is laying blocks on the board. When I asked him, "What are you making?", He replied cheerfully, "Maze !!". The maze he says is the arrangement of blocks that are in contact with each...
```python import sys BLOCK_WIDTH = 4 BLOCK_HEIGHT = 2 field = [] dx = [-1, 0, 1, 0] dy = [0, 1, 0, -1] w = 0 h = 0 xg = 0 yg = 0 start_color = 0 def main(): global field, w, h, c, xg, yg, start_color while True: w, h = map(int, input().split()) if w == 0 and h == 0: break x...
p00366 Electronic Metronome
A boy PCK is playing with N electric metronomes. The i-th metronome is set to tick every t_i seconds. He started all of them simultaneously. He noticed that, even though each metronome has its own ticking interval, all of them tick simultaneously from time to time in certain intervals. To explore this interesting phen...
```python n = int(input()) max_t = 0 timing = [] for i in range(n): timing.append(int(input())) if timing[i] > max_t : max_t = timing[i] divisor = [] for i in range(1,(max_t>>1)+1): if max_t%i == 0 : divisor.append(i) divisor.append(max_t) adj = 0 for t in timing : for d in divisor : if d...
p00721 Cleaning Robot
Here, we want to solve path planning for a mobile robot cleaning a rectangular room floor with furniture. Consider the room floor paved with square tiles whose size fits the cleaning robot (1 × 1). There are 'clean tiles' and 'dirty tiles', and the robot can change a 'dirty tile' to a 'clean tile' by visiting the tile...
```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 ...
p00861 Bug Hunt
In this problem, we consider a simple programming language that has only declarations of one- dimensional integer arrays and assignment statements. The problem is to find a bug in the given program. The syntax of this language is given in BNF as follows: <image> where <new line> denotes a new line character (LF). C...
```python import re def deref(d, expr): expr = expr.replace(']', '') symb = expr.split('[') symb[-1] = symb[-1] while len(symb) > 1: name, index = symb[-2:] if index not in d[name]: return None symb.pop() symb.pop() symb.append(d[name][index]) return symb[0] def check(s): d = ...
p00992 War
Two countries, Country A and Country B, are at war. As a soldier in Country A, you will lead n soldiers to occupy the territory of Country B. The territory of Country B is represented by a two-dimensional grid. The first place you occupy is a square on the 2D grid. Each of the soldiers you lead has h_i health. Each so...
```python a=sorted([int(input()) for _ in [0]*int(input())]) c=b=0 for i in range(len(a)-1,-1,-1): if a[i]<c//4:continue else:b+=a[i]-c//4 c+=1 print(b+1) ```
p01423 Rabbit Party
A rabbit Taro decided to hold a party and invite some friends as guests. He has n rabbit friends, and m pairs of rabbits are also friends with each other. Friendliness of each pair is expressed with a positive integer. If two rabbits are not friends, their friendliness is assumed to be 0. When a rabbit is invited to t...
```python #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop import sys import math import bisect import random def LI(): return [int(x) for x in sys.stdin.readline().split()] def I(): return int(sys.stdin.readline()) def LS():return [list(x) for x in sys.stdin.readline(...
p02016 Twins
B: Twins One twin was angry that it was not well known which of them was the older brother and which was the younger brother. Create a program that outputs "square1001" when "ani" is entered and "e869120" when "otouto" is entered. input You will be given either the string "ani" or "otouto" as input. output Please...
```python if input()=="ani": print("square1001") else: print("e869120") ```
p02299 Polygon-Point Containment
For a given polygon g and target points t, print "2" if g contains t, "1" if t is on a segment of g, "0" otherwise. g is represented by a sequence of points p1, p2,..., pn where line segments connecting pi and pi+1 (1 ≤ i ≤ n-1) are sides of the polygon. The line segment connecting pn and p1 is also a side of the poly...
```python 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 def string_to_complex(s): x, y = map(int, s.split()) return x + y * 1j def contains(polygon, point): flag = False for v1, v2 in zip(polygon[0:], polygon[1:])...
p02446 Unique
For a sequence of integers $A = \\{a_0, a_1, ..., a_{n-1}\\}$ which is sorted by ascending order, eliminate all equivalent elements. Constraints * $1 \leq n \leq 100,000$ * $-1000,000,000 \leq a_i \leq 1,000,000,000$ * $a_0 \leq a_1 \leq ... \leq a_{n-1}$ Input A sequence is given in the following format. $n$ $a_...
```python n = int(input()) s = { int(x) for x in input().split()} l = list(s) l.sort() print(*l) ```
1041_D. Glider
A plane is flying at a constant height of h meters above the ground surface. Let's consider that it is flying from the point (-10^9, h) to the point (10^9, h) parallel with Ox axis. A glider is inside the plane, ready to start his flight at any moment (for the sake of simplicity let's consider that he may start only w...
```python R = lambda: map(int, input().split()) n, h = R() ps = [] for _ in range(n): l, r = R() ps.append([l, r]) l, c, res = 0, 0, 0 for r in range(n): c += (ps[r][0] - ps[r - 1][1]) if r > 0 else 0 while c >= h: c -= (ps[l + 1][0] - ps[l][1]) l += 1 res = max(res, ps[r][1] - ps[l]...
1064_C. 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 input() print("".join(sorted(input()))) ```
1086_A. Connect Three
The Squareland national forest is divided into equal 1 × 1 square plots aligned with north-south and east-west directions. Each plot can be uniquely described by integer Cartesian coordinates (x, y) of its south-west corner. Three friends, Alice, Bob, and Charlie are going to buy three distinct plots of land A, B, C i...
```python s = [[int(i)for i in input().split()]for j in range(3)] s.sort() a = s[0] b = s[1] c = s[2] print(c[0] - a[0] + max(a[1], b[1], c[1]) - min(a[1], b[1], c[1]) + 1) for i in range(a[0], b[0]): print('{} {}'.format(i, a[1])) for i in range(min(a[1], b[1], c[1]), max(a[1], b[1], c[1]) + 1): print('{} {}...
1106_A. Lunar New Year and Cross Counting
Lunar New Year is approaching, and you bought a matrix with lots of "crosses". This matrix M of size n × n contains only 'X' and '.' (without quotes). The element in the i-th row and the j-th column (i, j) is defined as M(i, j), where 1 ≤ i, j ≤ n. We define a cross appearing in the i-th row and the j-th column (1 < i...
```python n=int(input()) a=[] for i in range(n): s=input() a.append(s) ans=0 for i in range(1,n-1): for j in range(1,n-1): if(a[i][j]=='X' and a[i-1][j-1]=='X' and a[i-1][j+1]=='X' and a[i+1][j-1]=='X' and a[i+1][j+1]=='X'): ans+=1 print(ans) ```
1133_B. Preparation for International Women's Day
International Women's Day is coming soon! Polycarp is preparing for the holiday. There are n candy boxes in the shop for sale. The i-th box contains d_i candies. Polycarp wants to prepare the maximum number of gifts for k girls. Each gift will consist of exactly two boxes. The girls should be able to share each gift ...
```python l=list(map(int,input().split())) n=l[0] k=l[1] l=[] b=[] for i in range (k): b.append(int(0)) l=list(map(int,input().split())) for i in l: b[i%k]+=1 sum=b[0]-b[0]%2 for i in range (1,(k+1)//2): sum+=(min(b[i],b[k-i])*2) if(k%2==0): sum+=b[k//2]-b[k//2]%2 print (sum) ```
1153_E. Serval and Snake
This is an interactive problem. Now Serval is a senior high school student in Japari Middle School. However, on the way to the school, he must go across a pond, in which there is a dangerous snake. The pond can be represented as a n × n grid. The snake has a head and a tail in different cells, and its body is a series...
```python # AC import sys class Main: def __init__(self): self.buff = None self.index = 0 def next(self): if self.buff is None or self.index == len(self.buff): self.buff = sys.stdin.readline().split() self.index = 0 val = self.buff[self.index] s...
1175_D. Array Splitting
You are given an array a_1, a_2, ..., a_n and an integer k. You are asked to divide this array into k non-empty consecutive subarrays. Every element in the array should be included in exactly one subarray. Let f(i) be the index of subarray the i-th element belongs to. Subarrays are numbered from left to right and from...
```python # AC import sys class Main: def __init__(self): self.buff = None self.index = 0 def next(self): if self.buff is None or self.index == len(self.buff): self.buff = self.next_line() self.index = 0 val = self.buff[self.index] self.index +=...
1194_C. From S To T
You are given three strings s, t and p consisting of lowercase Latin letters. You may perform any number (possibly, zero) operations on these strings. During each operation you choose any character from p, erase it from p and insert it into string s (you may insert this character anywhere you want: in the beginning of...
```python #import sys #input=sys.stdin.readline t=int(input()) for you in range(t): a=input() b=input() c=input() freqa=[0 for i in range(26)] freqb=[0 for i in range(26)] freqc=[0 for i in range(26)] for i in a: freqa[ord(i)-ord('a')]+=1 for i in b: freqb[ord(i)-ord('a')...
1276_B. Two Fairs
There are n cities in Berland and some pairs of them are connected by two-way roads. It is guaranteed that you can pass from any city to any other, moving along the roads. Cities are numerated from 1 to n. Two fairs are currently taking place in Berland — they are held in two different cities a and b (1 ≤ a, b ≤ n; a ...
```python def main(): t=int(input()) allans=[] for _ in range(t): n,m,a,b=readIntArr() adj=[[] for __ in range(n+1)] for __ in range(m): u,v=readIntArr() adj[u].append(v) adj[v].append(u) def reachableFromAWOPassingB(a,b): ...
1296_C. Yet Another Walking Robot
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'. Each of these characters corresponds to some move: * 'L' (left): means that the robot moves from the point (x, y) to the point (x...
```python t = int(input()) for _ in range(t): n = int(input()) arr = list(input()) curr = [0, 0] visited = {tuple(curr):0} dist = float('inf') le = -1; re = -1 for i in range(n): x, y = curr if arr[i] == 'L': x -= 1 elif arr[i] == 'R': x += 1 ...