name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
977_F. Consecutive Subsequence
You are given an integer array of length n. You have to choose some subsequence of this array of maximum length such that this subsequence forms a increasing sequence of consecutive integers. In other words the required sequence should be equal to [x, x + 1, ..., x + k - 1] for some value x and length k. Subsequence ...
```python n=int(input()) l=list(map(int,input().split())) d={} dp=[0 for i in range(n)] ind=dp[:] dp[0]=1 d[l[0]]=0 for i in range(1,len(l)): if l[i]-1 in d: dp[i]=1+dp[d[l[i]-1]] ind[i]=d[l[i]-1] else: dp[i]=1 d[l[i]]=i print(max(dp)) i=dp.index(max(dp)) mx=max(dp) ans=[] while mx: ...
p02785 AtCoder Beginner Contest 153 - Fennec vs Monster
Fennec is fighting with N monsters. The health of the i-th monster is H_i. Fennec can do the following two actions: * Attack: Fennec chooses one monster. That monster's health will decrease by 1. * Special Move: Fennec chooses one monster. That monster's health will become 0. There is no way other than Attack and...
```python R = lambda: map(int, input().split()) n, k = R() print(sum(sorted(R())[:n - k]) if k < n else 0) ```
p02921 AtCoder Beginner Contest 139 - Tenki
You will be given a string S of length 3 representing the weather forecast for three days in the past. The i-th character (1 \leq i \leq 3) of S represents the forecast for the i-th day. `S`, `C`, and `R` stand for sunny, cloudy, and rainy, respectively. You will also be given a string T of length 3 representing the ...
```python S = input() T = input() print(sum([1 for s,t in zip(S,T) if s == t])) ```
p03056 AtCoder Grand Contest 033 - Complexity
Note the unusual memory limit. For a rectangular grid where each square is painted white or black, we define its complexity as follows: * If all the squares are black or all the squares are white, the complexity is 0. * Otherwise, divide the grid into two subgrids by a line parallel to one of the sides of the grid, a...
```python H, W = map(int, input().split()) A = [[1 if a == "#" else 0 for a in input()] for _ in range(H)] X = [[[-2] * (H + 2) for _ in range(W + 2)] for _ in range(H + 2)] Y = [[[-2] * (W + 2) for _ in range(W + 2)] for _ in range(H + 2)] for i in range(H): Xi = X[i] Yi = Y[i] for j in range(W): ...
p03200 AtCoder Grand Contest 029 - Irreversible operation
There are N Reversi pieces arranged in a row. (A Reversi piece is a disc with a black side and a white side.) The state of each piece is represented by a string S of length N. If S_i=`B`, the i-th piece from the left is showing black; If S_i=`W`, the i-th piece from the left is showing white. Consider performing the f...
```python s = input() num = 0 st = 0 for i,x in enumerate(s): if x=='W': num += (i-st) st += 1 print(num) ```
p03347 AtCoder Grand Contest 024 - Sequence Growing Easy
There is a sequence X of length N, where every element is initially 0. Let X_i denote the i-th element of X. You are given a sequence A of length N. The i-th element of A is A_i. Determine if we can make X equal to A by repeating the operation below. If we can, find the minimum number of operations required. * Choose...
```python N = int(input()) A = [0] + [int(input()) for i in range(N)] if A[1] != 0: print(-1) quit() ans = 0 for i, a in enumerate(A[1:], 1): pre_a = A[i-1] if a - pre_a >= 2: print(-1) quit() elif a > pre_a: ans += 1 else: ans += a print(ans) ```
p03507 Code Festival Team Relay (Parallel) - Garden
In your garden, there is a long and narrow flowerbed that stretches infinitely to the east. You have decided to plant N kinds of flowers in this empty flowerbed. For convenience, we will call these N kinds of flowers Flower 1, 2, …, N. Also, we will call the position that is p centimeters from the west end of the flowe...
```python def main(): import sys input = sys.stdin.buffer.readline N, K = (int(i) for i in input().split()) WD = [[int(i) for i in input().split()] for j in range(N)] ma_w = 0 ma_d = 0 for w, d in WD: if ma_w < w: ma_w = w if ma_d < d: ma_d = d de...
p03668 AtCoder Grand Contest 017 - Game on Tree
There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two se...
```python import sys sys.setrecursionlimit(10 ** 7) n = int(input()) edges = [[] for i in range(n)] for i in range(n - 1): x, y = map(int, input().split()) edges[x - 1].append(y - 1) edges[y - 1].append(x - 1) def grundy_dfs(cur, prev): res = 0 for next_ in edges[cur]: if next_ == prev: ...
p03823 AtCoder Grand Contest 009 - Division into Two
There is a set consisting of N distinct integers. The i-th smallest element in this set is S_i. We want to divide this set into two sets, X and Y, such that: * The absolute difference of any two distinct elements in X is A or greater. * The absolute difference of any two distinct elements in Y is B or greater. How ...
```python import sys input = sys.stdin.readline from bisect import bisect_left, bisect_right INF = 10**18 + 100 N,A,B = map(int,input().split()) S = [-INF] + [int(x) for x in sys.stdin.read().split()] MOD = 10**9 + 7 dpX = [0] * (N+1) # 最後にYを選んだとして、直前に選んだXがどこにあるか dpY = [0] * (N+1) # 最後にXを選んだとして、直前に選んだYがどこにあるか dpX[0...
p03990 AtCoder Grand Contest 005 - Sugigma: The Showdown
Sigma and Sugim are playing a game. The game is played on a graph with N vertices numbered 1 through N. The graph has N-1 red edges and N-1 blue edges, and the N-1 edges in each color forms a tree. The red edges are represented by pairs of integers (a_i, b_i), and the blue edges are represented by pairs of integers (c...
```python import sys sys.setrecursionlimit(2147483647) INF=float("inf") MOD=10**9+7 # 998244353 input=lambda:sys.stdin.readline().rstrip() def resolve(): n,x,y=map(int,input().split()) x-=1; y-=1 E1=[[] for _ in range(n)] E2=[[] for _ in range(n)] for _ in range(n-1): u,v=map(int,input().spl...
p00078 Magic Square
The numbers 1 to n x n are contained in the n x n square squares one by one, and the sum of the squares in any vertical column and the sum of the squares in any horizontal column are diagonal squares. Those with the same sum of eyes are called magic squares. There are the following methods to create a magic square wit...
```python while 1: n = int(input()) if n == 0: break l = [[ 0 for i in range(n)] for j in range(n)] i = n//2 + 1 j = n//2 l[i][j] = ' 1' c = 2 d = '{: >4}'.format(c) for x in range(n**2 - 1): i = (i + 1) % n j = (j + 1) % n while l[i][j] != 0: ...
p00210 The Squares
The huge maze The Squares has been newly completed in the famous theme park. Evacuation drills must be conducted under the guidance of the fire department, but the time required for the drills cannot be predicted due to the huge maze. Therefore, you decided to develop an evacuation drill simulator based on the followin...
```python from sys import stdin # from line_profiler import LineProfiler def main(): head = [[8,1,2,4],[1,2,4,8],[2,4,8,1],[4,8,1,2]] while(True): W,H = map(int, stdin.readline().split()) m = [[0]*W for _ in range(H)] ps = [] if not (W or H): break for h in range(H): ...
p00587 Binary Tree Intersection And Union
Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same dept...
```python import re class bintree(): def __init__(self, str1): self.str1 = str1 if self.str1[1] != ",": c = 0 counter = 0 for s in str1[1:]: counter += 1 if s == "(": c += 1 elif s == ")": ...
p00864 Grey Area
Dr. Grey is a data analyst, who visualizes various aspects of data received from all over the world everyday. He is extremely good at sophisticated visualization tools, but yet his favorite is a simple self-made histogram generator. Figure 1 is an example of histogram automatically produced by his histogram. <image> ...
```python # coding: utf-8 while 1: n,w=map(int,input().split()) if n==0: break dic={} mx=-1 max_section=-1 for i in range(1+100//w): dic[i]=0 for i in range(n): x=int(input()) dic[x//w]+=1 mx=max(mx,dic[x//w]) max_section=max(max_section,x//w) ...
p01127 X-Ray Screening System
This is the story of 20XX. The number of air passengers increased as a result of the stable energy supply by the renewable power network and the invention of liquefied synthetic fuel. However, the threat of terrorism by aircraft still exists, and the importance of fast and highly reliable automatic baggage inspection s...
```python n = int(input()) for _ in range(n): h, w = map(int, input().split()) mp = [list(input()) for _ in range(h)] range_dic = {} keys = [] for y in range(h): for x in range(w): c = mp[y][x] if c in range_dic: x1, x2, y1, y2 = range_dic[c] range_dic[c] = (min(x, x1), max(x, ...
p01426 Vector Compression
You are recording a result of a secret experiment, which consists of a large set of N-dimensional vectors. Since the result may become very large, you are thinking of compressing it. Fortunately you already have a good compression method for vectors with small absolute values, all you have to do is to preprocess the ve...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def calc(V, es, r): mins = [(10**18, -1)]*V for s, t, w in es: mins[t] = min(mins[t], (w, s)) mins[r] = (-1, -1) group = [0]*V comp = [0]*V cnt = 0 used = [0]*V for v in range(V): if not used[v...
p01742 Dictionary
Sunuke-kun's dictionary contains the words s1, ..., sn, which consist of n lowercase letters. This satisfies s1 <... <sn when compared in lexicographical order. Unfortunately, some characters are faint and unreadable. Unreadable characters are represented by?. Find out how many ways to restore the dictionary by replaci...
```python # seishin.py import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): MOD = 10**9 + 7 N = int(readline()) M = 20 L = 26 ca = ord('a') cq = ord('?') S = [[ca-1]*M for i in range(N)] for i in range(N): s = readline().strip() S[i][:len(s)] = ...
p01882 We don't wanna work!
Example Input 4 Durett 7 Gayles 3 Facenda 6 Daughtery 0 1 + Mccourtney 2 Output Mccourtney is not working now. Durett is working hard now.
```python from heapq import heappush, heappop, heapify import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N = int(readline()) P = []; Q = [] E = []; R = {} L = N + 20000 for i in range(N): s, a = readline().split(); a = int(a) * L + i E.append(s) ...
p02019 Training
E-training Nene is writing a program to look up $ N $ integers $ V_1, V_2, V_3, \ cdots, V_N $ for programming training. As told by his instructor, Umiko, Nene wrote a program to look up multiples of 2, 3, and 6. Multiples of 2 were $ A $, multiples of 3 were $ B $, and multiples of 6 were $ C $. Umiko told me to l...
```python n,a,b,c = map(int,input().split()) print(n - (a+b-c)) ```
p02302 Convex Cut
<image> As shown in the figure above, cut a convex polygon g by a line p1p2 and print the area of the cut polygon which is on the left-hand side of the line. 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 convex polygon. The line segm...
```python def cross(a: complex, b: complex) -> float: return a.real * b.imag - a.imag * b.real def cross_point(c: complex, d: complex) -> complex: global lt, lv vec = d - c v1 = cross(lv, vec) v2 = cross(lv, lt - c) return c + v2 / v1 * vec if __name__ == "__main__": n = int(input()) ...
p02449 Permutation
For given a sequence $A = \\{a_0, a_1, ..., a_{n-1}\\}$, print the previous permutation and the next permutation in lexicographic order. Constraints * $1 \leq n \leq 9$ * $a_i$ consist of $1, 2, ..., n$ Input A sequence is given in the following format. $n$ $a_0 \; a_1 \; ... \; a_{n-1}$ Output Print the previ...
```python import operator def permutations(li): """Returns a list of previous, current, and next permutations of li. >>> permutations([1, 2]) [[1, 2], [2, 1]] >>> permutations([1, 3, 2]) [[1, 2, 3], [1, 3, 2], [2, 1, 3]] """ def perm(op): def func(xs): i = len(xs)...
1015_E2. Stars Drawing (Hard Edition)
A star is a figure of the following type: an asterisk character '*' in the center of the figure and four rays (to the left, right, top, bottom) of the same positive length. The size of a star is the length of its rays. The size of a star must be a positive number (i.e. rays of length 0 are not allowed). Let's consider...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys mod = 10 ** 9 + 7 mod1 = 998244353 #sys.setrecursionlimit(300000) # --------------------...
1103_A. Grid game
You are given a 4x4 grid. You play a game — there is a sequence of tiles, each of them is either 2x1 or 1x2. Your task is to consequently place all tiles from the given sequence in the grid. When tile is placed, each cell which is located in fully occupied row or column is deleted (cells are deleted at the same time in...
```python b= [['3 4','1 4'],['1 1','1 3']];o = [0,0] for i in map(int,input()):print(b[i][o[i]%2]);o[i] +=1 ```
1131_A. Sea Battle
In order to make the "Sea Battle" game more interesting, Boris decided to add a new ship type to it. The ship consists of two rectangles. The first rectangle has a width of w_1 and a height of h_1, while the second rectangle has a width of w_2 and a height of h_2, where w_1 ≥ w_2. In this game, exactly one ship is used...
```python w1, h1, w2, h2 = map(int, input().split()) if w2 > w1: res = w1 + 1 + h1 + h2 + 1 + w2 + 1 + h2 + (w1 - w2) + h1 + 1 else: res = (w1 + h1 + h2) * 2 + 4 print(res) ```
1151_C. Problem for Nazar
Nazar, a student of the scientific lyceum of the Kingdom of Kremland, is known for his outstanding mathematical abilities. Today a math teacher gave him a very difficult task. Consider two infinite sets of numbers. The first set consists of odd positive numbers (1, 3, 5, 7, …), and the second set consists of even posi...
```python import math def Solve(x): if x == 0: return 0 stage = int(math.floor(math.log(x,2))) odd = math.ceil(stage/2) even = math.floor(stage/2) even_terms = 2*(pow(4,even)-1)//3 odd_terms = (pow(4,odd)-1)//3 total = even_terms+odd_terms if (stage+1)%2 == 0: even_...
1173_B. Nauuo and Chess
Nauuo is a girl who loves playing chess. One day she invented a game by herself which needs n chess pieces to play on a m× m chessboard. The rows and columns are numbered from 1 to m. We denote a cell on the intersection of the r-th row and c-th column as (r,c). The game's goal is to place n chess pieces numbered fro...
```python import sys import math from functools import reduce n = int(input()) m = 1 while True: if m * 2 <= n: m += 1 else: break print(m) for x in range(m): print(1, x+1) t = n - m for _ in range(n - m): print(m, m - t + 1) t -= 1 ```
122_B. Lucky Substring
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. One day Petya was delivered a string s, containing only digits. He needs to find a string that * ...
```python s=input() s=s.strip('0') four=s.count('4') seven=s.count('7') if '4' not in s and '7' not in s: print(-1) else: if four>=seven: print('4') else: print('7') ```
1251_A. Broken Keyboard
Recently Polycarp noticed that some of the buttons of his keyboard are malfunctioning. For simplicity, we assume that Polycarp's keyboard contains 26 buttons (one for each letter of the Latin alphabet). Each button is either working fine or malfunctioning. To check which buttons need replacement, Polycarp pressed som...
```python ''' @judge CodeForces @id 1251A @name Broken Keyboard @tag Simulation ''' from sys import stdin from itertools import groupby def solve(s): return ''.join(sorted(set(map(lambda p: str(p[0]), filter(lambda p: len(list(p[1])) & 1, groupby(s)))))) input() for line in stdin: print(solve(line.strip())) ``...
1313_E. Concatenation with intersection
Vasya had three strings a, b and s, which consist of lowercase English letters. The lengths of strings a and b are equal to n, the length of the string s is equal to m. Vasya decided to choose a substring of the string a, then choose a substring of the string b and concatenate them. Formally, he chooses a segment [l_...
```python import sys, logging logging.basicConfig(level=logging.INFO) logging.disable(logging.INFO) def build(S, n): Z = [0 for i in range(3 * n + 3)] #logging.info(S) n = len(S) L = 0 R = 0 Z[0] = n for i in range(1, n): if(i > R): L = R = i while(R < n and ...
1336_C. Kaavi and Magic Spell
Kaavi, the mysterious fortune teller, deeply believes that one's fate is inevitable and unavoidable. Of course, she makes her living by predicting others' future. While doing divination, Kaavi believes that magic spells can provide great power for her to see the future. <image> Kaavi has a string T of length m and a...
```python mod = 998244353 eps = 10**-9 def main(): import sys input = sys.stdin.readline S = input().rstrip('\n') S = S[::-1] T = input().rstrip('\n') NS = len(S) NT = len(T) dp = [[0] * (NT+1) for _ in range(NS+1)] dp[0][0] = 1 for i in range(NS): s = S[i] fo...
1358_F. Tasty Cookie
Oh, no! The coronavirus has caught you, and now you're sitting in a dark cellar, with tied legs (but not hands). You have a delicious cookie, a laptop in front of you, and your ideal development environment is open. The coronavirus convinces you to solve the following problem. You are given two arrays A and B of size...
```python import sys int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI():...
1379_B. Dubious Cyrpto
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c. Unfortunately, an adversa...
```python #!/usr/local/bin/python3 """ Given l, r, m, you know that m = n*a + b - c for some l <= a,b,c <= r, and n is an integer. Can you find a,b,c? (any value is fine) Examples l,r,m = 10,20,90 Choose 10 <= a,b,c <= 20 s.t. 90 = n*a + b - c a=10,b=10,c=10,n=9 l,r,m = 8,9,95 Choose 8 <= a,b,c <= 9 ...
1399_F. Yet Another Segments Subset
You are given n segments on a coordinate axis OX. The i-th segment has borders [l_i; r_i]. All points x, for which l_i ≤ x ≤ r_i holds, belong to the i-th segment. Your task is to choose the maximum by size (the number of segments) subset of the given set of segments such that each pair of segments in this subset eith...
```python def f(sl): sl.sort(key=lambda s:(s[1],-s[0])) tl = sorted(list(set([s[0] for s in sl] + [s[1] for s in sl]))) cd = {tl[i]:i for i in range(len(tl))} csl = [[] for i in range(len(tl))] for s0,s1 in sl: csl[cd[s1]].append(cd[s0]) # start dp! n = len(tl) dp = [[len(cs...
1442_C. Graph Transpositions
You are given a directed graph of n vertices and m edges. Vertices are numbered from 1 to n. There is a token in vertex 1. The following actions are allowed: * Token movement. To move the token from vertex u to vertex v if there is an edge u → v in the graph. This action takes 1 second. * Graph transposition. T...
```python # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.BytesIO() self.writable = "x" in file.mode or "r" not ...
1468_E. Four Segments
Monocarp wants to draw four line segments on a sheet of paper. He wants the i-th segment to have its length equal to a_i (1 ≤ i ≤ 4). These segments can intersect with each other, and each segment should be either horizontal or vertical. Monocarp wants to draw the segments in such a way that they enclose a rectangular...
```python t = int(input()) while (t): a = list(map(int,input().split())) a.sort() print(a[0]*a[2]) t -= 1 ```
1492_D. Genius's Gambit
You are given three integers a, b, k. Find two binary integers x and y (x ≥ y) such that 1. both x and y consist of a zeroes and b ones; 2. x - y (also written in binary form) has exactly k ones. You are not allowed to use leading zeros for x and y. Input The only line contains three integers a, b, and k (...
```python #tests = int(input()) #for t in range(tests): #n = int(input()) a, b, k = list(map(int, input().split())) if a == 0 and k!=0: print('No') elif k ==0: print('Yes') print('1'*b + '0'*a) print('1'*b + '0'*a) elif b==1 or k > (a+b-2): print('No') else: shift = a+b-2-k print('Yes') ...
1515_E. Phoenix and Computers
There are n computers in a row, all originally off, and Phoenix wants to turn all of them on. He will manually turn on computers one at a time. At any point, if computer i-1 and computer i+1 are both on, computer i (2 ≤ i ≤ n-1) will turn on automatically if it is not already on. Note that Phoenix cannot manually turn ...
```python #!/usr/bin/env python import os import sys from io import BytesIO, IOBase def main(): n, MOD = map(int, input().split()) factorial = [1] for i in range(2, n + 1): factorial.append(factorial[-1] * i % MOD) for i in range(len(factorial)): factorial[i] = pow(factorial[i], MOD - ...
1542_D. Priority Queue
You are given a sequence A, where its elements are either in the form + x or -, where x is an integer. For such a sequence S where its elements are either in the form + x or -, define f(S) as follows: * iterate through S's elements from the first one to the last one, and maintain a multiset T as you iterate through...
```python MOD = 998244353 def solve(): n = int(input()) ans = 0 arr = [] for i in range(n): a = list(input().split()) if len(a) == 2: arr.append(int(a[1])) else: arr.append(0) for cur in range(n): if arr[cur]: dp = [0] * (n+1) ...
16_D. Logging
The main server of Gomble company received a log of one top-secret process, the name of which can't be revealed. The log was written in the following format: «[date:time]: message», where for each «[date:time]» value existed not more than 10 lines. All the files were encoded in a very complicated manner, and only one p...
```python from sys import stdin lines = int(stdin.readline()) days = 1 count = 0 h1 = 0 m1 = 0 for x in range(lines): log = stdin.readline().strip() hour = int(log[1:3]) if hour == 12: hour = 0 if log[7] =='p': hour += 12 minute = int(log[4:6]) #print(hour,minute) #print(h1,m1) if hour < h1...
190_B. Surrounded
So, the Berland is at war with its eternal enemy Flatland again, and Vasya, an accountant, was assigned to fulfil his duty to the nation. Right now the situation in Berland is dismal — their both cities are surrounded! The armies of flatlanders stand on the borders of circles, the circles' centers are in the surround...
```python import sys import math a,b,c=map(int,sys.stdin.readline().split()) d,e,f=map(int,sys.stdin.readline().split()) ds=math.sqrt((a-d)**2+(b-e)**2) if ds>=c+f: print((ds-c-f)/2) elif ds<=abs(c-f): print((abs(c-f)-ds)/2) else: print(0) ```
214_B. Hometask
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you? You are given a set of digits, your task is to find the maximum integer that you can mak...
```python def hometask(arr): n="0" if arr.count(0)==0: return -1 arr.remove(0) ans=[] arr=sorted(arr,reverse=True) while arr : c=sum(arr)%3 if c==0: break flag=True for i in range(len(arr)-1,-1,-1): if arr[i]%3==c: a...
238_B. Boring Partition
This problem is the most boring one you've ever seen. Given a sequence of integers a1, a2, ..., an and a non-negative integer h, our goal is to partition the sequence into two subsequences (not necessarily consist of continuous elements). Each element of the original sequence should be contained in exactly one of the...
```python #https://codeforces.com/problemset/problem/238/B n, h = map(int, input().split()) a = list(map(int, input().split())) b = [[x, i] for i, x in enumerate(a)] b = sorted(b, key=lambda x:x[0]) def solve(a, n, h): if n == 2: return 0, [1, 1] min_ = (a[-1][0] + a[-2][0]) - (a[0][0] +...
262_E. Maxim and Matrix
Maxim loves to fill in a matrix in a special manner. Here is a pseudocode of filling in a matrix of size (m + 1) × (m + 1): <image> Maxim asks you to count, how many numbers m (1 ≤ m ≤ n) are there, such that the sum of values in the cells in the row number m + 1 of the resulting matrix equals t. Expression (x xor y...
```python def comb(n, r): if r > n or r < 0: return 0 r = min(r, n-r) result = 1 for i in range(1, r+1): result = result*(n+1-i)//i return result def F(n, t): if t == 0: return 1 elif n == 0: return 0 elif n == 1: return int(t == 1) m = len(bi...
334_C. Secrets
Gerald has been selling state secrets at leisure. All the secrets cost the same: n marks. The state which secrets Gerald is selling, has no paper money, only coins. But there are coins of all positive integer denominations that are powers of three: 1 mark, 3 marks, 9 marks, 27 marks and so on. There are no coins of oth...
```python n = int(input()) res = 1 x = 1 while x <= n: if n%x != 0: res = max(res, (n+x-1)//x) x *= 3 print(res) ```
357_C. Knight Tournament
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event. As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tourname...
```python n, m = map(int, input().split()) p, d = [0] * (n + 2), list(range(1, n + 3)) for i in range(m): l, r, x = map(int, input().split()) while l < x: if p[l]: k = d[l] d[l] = x l = k else: d[l], p[l] = x, x l += 1 ...
401_A. Vanya and Cards
Vanya loves playing. He even has a special set of cards to play with. Each card has a single integer. The number on the card can be positive, negative and can even be equal to zero. The only limit is, the number on each card doesn't exceed x in the absolute value. Natasha doesn't like when Vanya spends a long time pla...
```python inp = input().split(' ') n = int(inp[0]) x = int(inp[1]) su = 0 inp = input().split(' ') for i in inp: su += int(i) count = 0 while su!=0: count += 1 if su > 0: su += max(-x, -su) else: su += min(x, -su) print(count) ```
429_B. Working out
Summer is coming! It's time for Iahub and Iahubina to work out, as they both want to look hot at the beach. The gym where they go is a matrix a with n lines and m columns. Let number a[i][j] represents the calories burned by performing workout at the cell of gym in the i-th line and the j-th column. Iahub starts with ...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 1/7/20 """ import collections import time import os import sys import bisect import heapq from typing import List def solve(N, M, A): dpa = [[0 for _ in range(M+2)] for _ in range(N+2)] dpb = [[0 for _ in range(M+2)] for _ in range(N+2)] ...
450_E. Jzzhu and Apples
Jzzhu has picked n apples from his big apple tree. All the apples are numbered from 1 to n. Now he wants to sell them to an apple store. Jzzhu will pack his apples into groups and then sell them. Each group must contain two apples, and the greatest common divisor of numbers of the apples in each group must be greater...
```python import math apples=int(input()) if apples<=3: print(0) else: halfpr=int(apples/2) def primes(n): primeslistsa=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, ...
497_B. Tennis Game
Petya and Gena love playing table tennis. A single match is played according to the following rules: a match consists of multiple sets, each set consists of multiple serves. Each serve is won by one of the players, this player scores one point. As soon as one of the players scores t points, he wins the set; then the ne...
```python n = int(input()) line = input().split() lst = [] for num in line: lst.append(int(num)) cnt1 = [0] cnt2 = [0] c1 = 0 c2 = 0 for num in lst: if num == 1: c1 += 1 cnt1.append(c2) else: c2 += 1 cnt2.append(c1) w = lst[n - 1] ans = [] c1 = len(cnt1) c2 = len(cnt2) fo...
548_A. Mike and Fax
While Mike was walking in the subway, all the stuff in his back-bag dropped on the ground. There were several fax messages among them. He concatenated these strings in some order and now he has string s. <image> He is not sure if this is his own back-bag or someone else's. He remembered that there were exactly k mess...
```python def isPalindrome(t): for i in range(len(t)//2): if t[i] != t[len(t)-i-1]: return False return True s = input() k = int(input()) if len(s) % k: print('NO') else: t = len(s)//k for i in range(k): if not isPalindrome(s[i*t: i*t+t]): print('NO') ...
574_C. Bear and Poker
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are n players (including Limak himself) and right now all of them have bids on the table. i-th of them has bid with size ai dollars. Each player can double his bid any number of times and triple his bid any number of ...
```python n = int(input()) arr = [int(x) for x in input().split()] for i in range(n): while arr[i]%2==0: arr[i]/=2 while arr[i]%3==0: arr[i]/=3 print("Yes" if all(arr[0]==arr[i] for i in range(n))else "No") ```
596_A. Wilbur and Swimming Pool
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned...
```python def judgeTwoPoints( pa , pb ): if pa[0] != pb[0] and pa[1] != pb[1]: #print( "ok!" , pa , pb , abs( pa[0] - pb[0] ) * abs( pa[1] - pb[1] ) ) return abs( pa[0] - pb[0] ) * abs( pa[1] - pb[1] ) else: return -1 def solve( pts , n ): if n == 1: return -1 pts.sort(...
617_C. Watering Flowers
A flowerbed has many flowers and two fountains. You can adjust the water pressure and set any values r1(r1 ≥ 0) and r2(r2 ≥ 0), giving the distances at which the water is spread from the first and second fountain respectively. You have to set such r1 and r2 that all the flowers are watered, that is, for each flower, t...
```python f = lambda: map(int, input().split()) n, a, b, c, d = f() t = [] for i in range(n): x, y = f() t.append(((x - a) ** 2 + (y - b) ** 2, (x - c) ** 2 + (y - d) ** 2)) t.sort() s = 8e14 q = 0 for u, v in reversed(t): s = min(s, u + q) q = max(q, v) print(min(s, q)) ```
637_D. Running with Obstacles
A sportsman starts from point xstart = 0 and runs to point with coordinate xfinish = m (on a straight line). Also, the sportsman can jump — to jump, he should first take a run of length of not less than s meters (in this case for these s meters his path should have no obstacles), and after that he can jump over a lengt...
```python n,m,s,d=map(int,input().split()) x=list(map(int,input().split()))+[m+s+1] x.sort() cur=l=0 ans=[] while l<m: r=min(x[cur]-1,m) ans.append(("RUN",r-l)) if r==m: break if r-l<s: print("IMPOSSIBLE") exit() t=x[cur]+1 while x[cur+1]-1-t<s: cur+=1 t=x[cur]+1 if t-r>d: print("I...
665_D. Simple Subset
A tuple of positive integers {x1, x2, ..., xk} is called simple if for all pairs of positive integers (i, j) (1 ≤ i < j ≤ k), xi + xj is a prime. You are given an array a with n positive integers a1, a2, ..., an (not necessary distinct). You want to find a simple subset of the array a with the maximum size. A prime n...
```python n = int(input()) L = list(map(int, input().split())) P = [-1 for _ in range(2000001)] def premier(n): if P[n] >= 0: return P[n] for i in range(2,int(n**0.5)+1): if n%i==0: P[n] = False return False P[n] = True return True e = L.count(1) if n == 1: ...
68_B. Energy exchange
It is well known that the planet suffers from the energy crisis. Little Petya doesn't like that and wants to save the world. For this purpose he needs every accumulator to contain the same amount of energy. Initially every accumulator has some amount of energy: the i-th accumulator has ai units of energy. Energy can be...
```python def check(a, k, cur): need = 0 have = 0 for x in a: if x < cur: need += cur - x else: have += (x - cur) * (1 - k / 100) return need <= have n, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] l = 0 r = 1000 for i in range(100): cur = (l + r) / 2 if check(a, k, cur):...
711_E. ZS and The Birthday Paradox
ZS the Coder has recently found an interesting concept called the Birthday Paradox. It states that given a random set of 23 people, there is around 50% chance that some two of them share the same birthday. ZS the Coder finds this very interesting, and decides to test this with the inhabitants of Udayland. In Udayland,...
```python #copied import math n, k = [int(x) for x in input().split()] if n<70 and k>2**n: print(1,1) exit(0) mod = int(1e6)+3 def fastpow(a,b): t, ans = a, 1 while b: if(b&1): ans = ans*t%mod t = t*t %mod b>>=1 return ans t=k-1 cnt=0 while t: # gets highest pos...
778_B. Bitwise Formula
Bob recently read about bitwise operations used in computers: AND, OR and XOR. He have studied their properties and invented a new game. Initially, Bob chooses integer m, bit depth of the game, which means that all numbers in the game will consist of m bits. Then he asks Peter to choose some m-bit number. After that, ...
```python #from math import * from sys import * from decimal import * def main(): n,k=(int(z) for z in stdin.readline().split()) d=[] nm=[0]*n bt1=[False]*(n+1) bt2=[False]*(n+1) bt2[-1]=True nam=dict() nam["?"]=-1 for i in range(n): fl=0 s=stdin.readline()[:-1].spli...
802_E. Marmots (medium)
Good job! Now that Heidi is able to distinguish between Poisson and uniform distributions, she is in a good position to actually estimate the populations. Can you help Heidi estimate each village's population? Input Same as the easy version. Output Output one line per village, in the same order as provided in the ...
```python def sampleVariance(V): X = sum(V) / len(V) S = 0.0 for x in V: S += (X-x)**2 S /= (len(V)-1) return (X, S) #That awkward moment when you realized that variance is sigma^2 but you just took the stat course this semester for i in range(int(input())): V = list(map(int, input().s...
825_A. Binary Protocol
Polycarp has just invented a new binary protocol for data transmission. He is encoding positive integer decimal number to binary string using following algorithm: * Each digit is represented with number of '1' characters equal to the value of that digit (for 0 it is zero ones). * Digits are written one by one in ...
```python x = int(input()) a = input() l = 0 c = [] v = '' b = a.split("0") for i in b: g = len(i) c.append(g) for p in c: v += str(p) print(v) ```
847_L. Berland SU Computer Network
In the computer network of the Berland State University there are n routers numbered from 1 to n. Some pairs of routers are connected by patch cords. Information can be transmitted over patch cords in both direction. The network is arranged in such a way that communication between any two routers (directly or through o...
```python import math import sys read = sys.stdin.readline n = int(read()) sub = [[] for _ in range(n)] for i in range(n): data = read().strip() for j in data.split('-'): tree = list(map(int, j.split(':')[1].split(','))) for k in range(len(tree)): tree[k] -= 1 sub[i].append(s...
896_A. Nephren gives a riddle
What are you doing at the end of the world? Are you busy? Will you save us? <image> Nephren is playing a game with little leprechauns. She gives them an infinite array of strings, f0... ∞. f0 is "What are you doing at the end of the world? Are you busy? Will you save us?". She wants to let more people know about i...
```python f0 = 'What are you doing at the end of the world? Are you busy? Will you save us?' ft1, ft2, ft3 = 'What are you doing while sending "', '"? Are you busy? Will you send "', '"?' flen = [2 * 10 ** 18] * (10 ** 5 + 1) flen[0] = len(f0) for i in range(1, 56): flen[i] = len(ft1) + len(ft2) + len(ft3) + 2 * f...
917_B. MADMAX
As we all know, Max is the best video game player among her friends. Her friends were so jealous of hers, that they created an actual game just to prove that she's not the best at games. The game is played on a directed acyclic graph (a DAG) with n vertices and m edges. There's a character written on each edge, a lower...
```python def mat(shape, inital_val=None): if len(shape) > 1: return [mat(shape[1:], inital_val) for _ in range(shape[0])] else: return [inital_val] * shape[0] def main(): n, m = [int(x) for x in input().split()] graph = [{} for _ in range(n)] for _ in range(m): ...
93_B. End of Exams
Students love to celebrate their holidays. Especially if the holiday is the day of the end of exams! Despite the fact that Igor K., unlike his groupmates, failed to pass a programming test, he decided to invite them to go to a cafe so that each of them could drink a bottle of... fresh cow milk. Having entered the cafe...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, w, m = map(int, input().split()) w = float(w) eps = 1e-9 req = n * w / m cup = [req] * m ans = [[] for _ in range(m)] j = 0 for i in range(n): milk = w cnt = 0 while j < m a...
p02626 AtCoder Beginner Contest 172 - Unfair Nim
There are N piles of stones. The i-th pile has A_i stones. Aoki and Takahashi are about to use them to play the following game: * Starting with Aoki, the two players alternately do the following operation: * Operation: Choose one pile of stones, and remove one or more stones from it. * When a player is unable to do t...
```python import sys from functools import lru_cache read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines N, *A = map(int, read().split()) a, b = A[:2] xor = 0 for x in A[2:]: xor ^= x INF = 10**13 @lru_cache(None) def F(a, b, xor): if (a & 1) ^ (b & 1) !...
p02757 AtCoder Beginner Contest 158 - Divisible Substring
Takahashi has a string S of length N consisting of digits from `0` through `9`. He loves the prime number P. He wants to know how many non-empty (contiguous) substrings of S - there are N \times (N + 1) / 2 of them - are divisible by P when regarded as integers written in base ten. Here substrings starting with a `0`...
```python n,m=map(int,input().split());s=input();l=[0]*m;a,t,p=0,0,1 if 10%m: for i in s[::-1]:l[t%m]+=1;t+=int(i)*p;a+=l[t%m];p=p*10%m else:a=sum(i+1 for i in range(n) if int(s[i])%m<1) print(a) ```
p02892 AtCoder Grand Contest 039 - Graph Partition
Given is a connected undirected graph with N vertices and M edges. The vertices are numbered 1 to N, and the edges are described by a grid of characters S. If S_{i,j} is `1`, there is an edge connecting Vertex i and j; otherwise, there is no such edge. Determine whether it is possible to divide the vertices into non-e...
```python from collections import deque import sys sys.setrecursionlimit(10**6) input = sys.stdin.readline n = int(input()) edge = [[] for _ in range(n)] mat = [[1000] * n for _ in range(n)] for i in range(n): s = input().rstrip() for j, ch in enumerate(s): if ch == "1": mat[i][j] = 1 ...
p03027 M-SOLUTIONS Programming Contest - Product of Arithmetic Progression
Consider the following arithmetic progression with n terms: * x, x + d, x + 2d, \ldots, x + (n-1)d What is the product of all terms in this sequence? Compute the answer modulo 1\ 000\ 003. You are given Q queries of this form. In the i-th query, compute the answer in case x = x_i, d = d_i, n = n_i. Constraints *...
```python p,M,f=pow,1000003,[1] for i in range(1,M):f.append(f[i-1]*i%M) for _ in'_'*int(input()):x,d,n=map(int,input().split());t=x*p(d,M-2,M)%M;print([p(x,n,M),(M-n>=t>0)*1and f[t+n-1]*p(f[t-1],M-2,M)*p(d,n,M)%M][d>0]) ```
p03168 Educational DP Contest - Coins
Let N be a positive odd number. There are N coins, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), when Coin i is tossed, it comes up heads with probability p_i and tails with probability 1 - p_i. Taro has tossed all the N coins. Find the probability of having more heads than tails. Constraints * N is an od...
```python n=int(input()) p=list(map(float,input().split())) dp=[[0 for _ in range(n+1)]for _ in range(n)] dp[0][0]=1-p[0] dp[0][1]=p[0] for i in range(1,n): for j in range(i+2): dp[i][j]=dp[i-1][j-1]*p[i]+dp[i-1][j]*(1-p[i]) print(sum(dp[-1][(n+1)//2:])) ```
p03313 AtCoder Regular Contest 100 - Or Plus Max
There is an integer sequence of length 2^N: A_0, A_1, ..., A_{2^N-1}. (Note that the sequence is 0-indexed.) For every integer K satisfying 1 \leq K \leq 2^N-1, solve the following problem: * Let i and j be integers. Find the maximum value of A_i + A_j where 0 \leq i < j \leq 2^N-1 and (i or j) \leq K. Here, or denot...
```python n = int(input()) aaa = list(map(int, input().split())) n2 = 1 << n dp = [[a, 0] for a in aaa] for j in range(n): b = 1 << j for i in range(n2): if not i & b: dpi, dpk = dp[i], dp[i | b] if dpk[0] < dpi[0]: dpk[1] = max(dpk[0], dpi[1]) dp...
p03470 AtCoder Beginner Contest 085 - Kagami Mochi
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have...
```python n,*d=map(int,open(0).read().split());print(len(set(d))) ```
p03632 AtCoder Beginner Contest 070 - Two Switches
Alice and Bob are controlling a robot. They each have one switch that controls the robot. Alice started holding down her button A second after the start-up of the robot, and released her button B second after the start-up. Bob started holding down his button C second after the start-up, and released his button D second...
```python a,b,c,d=map(int,input().split()) print(max(0,min(d,b)-max(a,c))) ```
p03790 AtCoder Grand Contest 011 - Train Service Planning
There is a railroad in Takahashi Kingdom. The railroad consists of N sections, numbered 1, 2, ..., N, and N+1 stations, numbered 0, 1, ..., N. Section i directly connects the stations i-1 and i. A train takes exactly A_i minutes to run through section i, regardless of direction. Each of the N sections is either single-...
```python import sys def merge_delay_pattern(k, half1, half2): len1 = len(half1) len2 = len(half2) start, delay1_next = half1[0] start2 = half2[0][0] time1 = start - start2 mid_start = start + time1 + delay1_next offset2_num_period = (mid_start - start2) // k offset2_phase = mid_start ...
p03958 CODE FESTIVAL 2016 qual C - K Cakes
There are K pieces of cakes. Mr. Takahashi would like to eat one cake per day, taking K days to eat them all. There are T types of cake, and the number of the cakes of type i (1 ≤ i ≤ T) is a_i. Eating the same type of cake two days in a row would be no fun, so Mr. Takahashi would like to decide the order for eating ...
```python #!/usr/bin/env python3 k,t = map(int,input().split()) a = list(map(int,input().split())) print(max(0,2*(max(a)-(k+1)//2)-1)) ```
p00050 Apple and Peach
Fukushima Prefecture is also famous for producing fruits, and among them, peaches and apples boast one of the highest production volumes in Japan. By the way, when I made a print manuscript of an English pamphlet for sale, I mistakenly wrote the description about apples and the description about peaches in reverse. Yo...
```python a,p,t='apple','peach','_' print(input().replace(a,t).replace(p,a).replace(t,p)) ```
p00180 Demolition of Bridges
Water Country Water Deven has n cities. Each city is surrounded by water and looks like an island country. Water Deven has m bridges, and transportation between cities is carried out by these bridges, which allows you to travel to and from all cities. Recently, it was decided to reduce the maintenance cost of the brid...
```python class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * (n+1) def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y...
p00336 Repeated Spell
We, the researchers who discovered and investigated the ancient nation Iwashiro, finally discovered the temple in the center of Iwashiro. A lithograph dedicated to the god of Iwashiro was stored in the temple. On the lithograph, two strings were written, one for each sentence and one for the spell. In Iwashiro, how ma...
```python t = input() b = input() MOD = 10**9 + 7 cnts = [0]*(len(b)+1) cnts[0] = 1 for c in t: for i in range(len(b)-1, -1, -1): if c == b[i]: cnts[i+1] = (cnts[i+1] + cnts[i]) % MOD print(cnts[-1]) ```
p00527 Take the 'IOI' train
Take the'IOI'train A new railway has been laid in IOI. Trains running on railways in IOI are a combination of several vehicles, and there are two types of vehicles, I and O. Vehicles can only be connected to different types of vehicles. Also, because the train has a driver's seat, the cars at both ends of the train mu...
```python def main(): M, N = map(int, input().split()) S = input() T = input() INF = 10**18 dp0 = [[0]*(N+1) for i in range(M+1)] dp1 = [[-INF]*(N+1) for i in range(M+1)] for p in range(M+1): for q in range(N+1): v0 = dp0[p][q] v1 = dp1[p][q] if...
p00694 Strange Key
Professor Tsukuba invented a mysterious jewelry box that can be opened with a special gold key whose shape is very strange. It is composed of gold bars joined at their ends. Each gold bar has the same length and is placed parallel to one of the three orthogonal axes in a three dimensional space, i.e., x-axis, y-axis an...
```python def solve(sentence): now = [0, 0, 0] # x,y,z num_p = {} positions = [] for s in sentence: if s.isdecimal(): if s in num_p: now = num_p[s] else: num_p[s] = now else: sign = 1 if s[0] == "+" else -1 ...
p01398 Swap Cipher
Problem A: Swap crypto A 2D enthusiast at R University, he often writes embarrassing sentences that blush when seen by people. Therefore, in order for a third party to not be able to see the text he is writing, he encrypts the text using a method called swap encryption that he devised independently. In swap encryption...
```python while True: n = int(input()) if n == 0:break mes = list(input()) mes = [ord(c) - ord("a") for c in mes] ablst = [tuple(map(int, input().split())) for _ in range(n)] ablst.reverse() for a, b in ablst: a -= 1 b -= 1 mes[b], mes[a] = (mes[a] + (b - a)) % 26, (mes[b] + (b - a)) % 26 me...
p01551 DNA
A gene is a string consisting of `A`,` T`, `G`,` C`. The genes in this world are strangely known to obey certain syntactic rules. Syntax rules are given in the following form: Non-terminal symbol 1: Symbol 1_1 Symbol 1_2 ... Symbol 1_n1 Non-terminal symbol 2: Symbol 2_1 Symbol 2_2 ... Symbol 2_n2 ... Non-terminal sy...
```python from collections import defaultdict import sys def solve(): readline = sys.stdin.readline write = sys.stdout.write MOD = 10**9 + 7 Na, Nt, Ng, Nc = map(int, readline().split()) L = Na + Nt + Ng + Nc M = int(readline()) MP = {} S = [] for i in range(M): s = readline(...
p01852 Finger Counting
Problem statement Meatishi can increase or decrease the number of fingers. There are n buns in front of Nikunishi-kun. Meatishi is trying to count the number of steamed buns by breaking his finger. There are only two shapes that Nishikun's fingers can take, whether they are broken or not. Nikunishi understands binary ...
```python n = int(input()) print(0 * (n == 0) + len(str(bin(n))[2:]) * (n != 0)) ```
p02274 The Number of Inversions
For a given sequence $A = \\{a_0, a_1, ... a_{n-1}\\}$, the number of pairs $(i, j)$ where $a_i > a_j$ and $i < j$, is called the number of inversions. The number of inversions is equal to the number of swaps of Bubble Sort defined in the following program: bubbleSort(A) cnt = 0 // the number of inversions for i = 0 ...
```python import bisect #int bit[n+1],n def sum(i):#[1,i]のsumを求める s = 0 while(i > 0): s += bit[i] i = i&(i-1) return s def add(i,x):#i番目にxを加算 i & (-i):iの最後の1のbit while(i <= n): bit[i] += x i += i & (-i) n = int(input()) a = list(map(int,input().split())) aa = sorted(a)...
p02421 Card Game
Taro and Hanako are playing card games. They have n cards each, and they compete n turns. At each turn Taro and Hanako respectively puts out a card. The name of the animal consisting of alphabetical letters is written on each card, and the bigger one in lexicographical order becomes the winner of that turn. The winner ...
```python n = int(input()) t = 0 h = 0 for _ in range(n): tc, hc = input().split() if tc > hc: t += 3 elif tc < hc: h += 3 else: t += 1 h += 1 print(t, h) ```
1003_A. Polycarp's Pockets
Polycarp has n coins, the value of the i-th coin is a_i. Polycarp wants to distribute all the coins between his pockets, but he cannot put two coins with the same value into the same pocket. For example, if Polycarp has got six coins represented as an array a = [1, 2, 4, 3, 3, 2], he can distribute the coins into two ...
```python n = int(input()) mn = list(map(int, input().split())) k = 1 for i in range(1, 101): s = mn.count(i) if s > k: k = s print(k) ```
1027_B. Numbers on the Chessboard
You are given a chessboard of size n × n. It is filled with numbers from 1 to n^2 in the following way: the first ⌈ (n^2)/(2) ⌉ numbers from 1 to ⌈ (n^2)/(2) ⌉ are written in the cells with even sum of coordinates from left to right from top to bottom. The rest n^2 - ⌈ (n^2)/(2) ⌉ numbers from ⌈ (n^2)/(2) ⌉ + 1 to n^2 ...
```python import sys n,q=map(int,sys.stdin.readline().strip().split()) nc=n # print(n,q) if(n%2==0): n2=int((n*n)/2) else: n2=int((n*n)/2)+1 n1=int(n/2) if(1==1): for i in range(q): x,y=map(int,sys.stdin.readline().strip().split()) # print(n,q,x,y) x1=int(x/2) y1=int(...
1091_D. New Year and the Permutation Concatenation
Let n be an integer. Consider all permutations on integers 1 to n in lexicographic order, and concatenate them into one big sequence p. For example, if n = 3, then p = [1, 2, 3, 1, 3, 2, 2, 1, 3, 2, 3, 1, 3, 1, 2, 3, 2, 1]. The length of this sequence will be n ⋅ n!. Let 1 ≤ i ≤ j ≤ n ⋅ n! be a pair of indices. We cal...
```python n = int(input()) f_n = n cnt = 0 for k in range(n-1, 0, -1): cnt += f_n f_n *= k if f_n >= 998244353: f_n %= 998244353 print((n*f_n-cnt)%998244353) ```
1110_B. Tape
You have a long stick, consisting of m segments enumerated from 1 to m. Each segment is 1 centimeter long. Sadly, some segments are broken and need to be repaired. You have an infinitely long repair tape. You want to cut some pieces from the tape and use them to cover all of the broken segments. To be precise, a piece...
```python n, m, k = (int(x) for x in input().split()) b = [int(x) for x in input().split()] deltaB = sorted([b[i + 1] - b[i] for i in range(n - 1)]) print(sum(deltaB[:n - k]) + k) ```
1158_C. Permutation recovery
Vasya has written some permutation p_1, p_2, …, p_n of integers from 1 to n, so for all 1 ≤ i ≤ n it is true that 1 ≤ p_i ≤ n and all p_1, p_2, …, p_n are different. After that he wrote n numbers next_1, next_2, …, next_n. The number next_i is equal to the minimal index i < j ≤ n, such that p_j > p_i. If there is no su...
```python import sys input = sys.stdin.readline T = int(input()) for _ in range(T): n = int(input()) l = list(map(int, input().split())) stack = [] out = [-1] * n curr = 0 works = True for i in range(n): while stack and stack[-1][0] == i: _, j = stack.pop() ...
1180_B. Nick and Array
Nick had received an awesome array of integers a=[a_1, a_2, ..., a_n] as a gift for his 5 birthday from his mother. He was already going to explore its various properties but after unpacking he was disappointed a lot because the product a_1 ⋅ a_2 ⋅ ... a_n of its elements seemed to him not large enough. He was ready t...
```python n=int(input()) list1=[*map(int,input().split())] list2=[] if n%2==0: for element in list1: if element>=0: print(-element-1) else: print(element) else: for element in list1: if element>=0: list2.append(-element-1) else: lis...
1199_B. Water Lily
While sailing on a boat, Inessa noticed a beautiful water lily flower above the lake's surface. She came closer and it turned out that the lily was exactly H centimeters above the water surface. Inessa grabbed the flower and sailed the distance of L centimeters. Exactly at this point the flower touched the water surfac...
```python import math h, l = input().split() h = int(h) l = int(l) a = float((pow(l,2)-pow(h,2))/(2*h)) print(a) ```
1216_A. Prefixes
Nikolay got a string s of even length n, which consists only of lowercase Latin letters 'a' and 'b'. Its positions are numbered from 1 to n. He wants to modify his string so that every its prefix of even length has an equal amount of letters 'a' and 'b'. To achieve that, Nikolay can perform the following operation arb...
```python l = int(input()) s = list(input().strip()) ct = 0 for i in range(0,l-1,2): if s[i] == s[i+1]: ct += 1 if s[i] == 'a': s[i] = 'b' else: s[i] = 'a' print(ct) print(''.join(s)) ```
1239_B. The World Is Just a Programming Task (Hard Version)
This is a harder version of the problem. In this version, n ≤ 300 000. Vasya is an experienced developer of programming competitions' problems. As all great minds at some time, Vasya faced a creative crisis. To improve the situation, Petya gifted him a string consisting of opening and closing brackets only. Petya beli...
```python def get_bal(): bal = [0] * n bal[0] = u[0] for i in range(1, n): bal[i] = bal[i - 1] + u[i] min_b = min(bal) ans = 0 for i in range(n): if bal[i] == min_b: ans += 1 return ans n = int(input()) u = list(input()) for i in range(n): if u[i] == '(': ...
1257_D. Yet Another Monster Killing Problem
You play a computer game. In this game, you lead a party of m heroes, and you have to clear a dungeon with n monsters. Each monster is characterized by its power a_i. Each hero is characterized by his power p_i and endurance s_i. The heroes clear the dungeon day by day. In the beginning of each day, you choose a hero ...
```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...
1300_D. Aerodynamic
Guy-Manuel and Thomas are going to build a polygon spaceship. You're given a strictly convex (i. e. no three points are collinear) polygon P which is defined by coordinates of its vertices. Define P(x,y) as a polygon obtained by translating P by vector \overrightarrow {(x,y)}. The picture below depicts an example of t...
```python import sys import math from collections import defaultdict from collections import deque from itertools import combinations from itertools import permutations input = lambda : sys.stdin.readline().rstrip() read = lambda : list(map(int, input().split())) go = lambda : 1/0 def write(*args, sep="\n"): for i in...
1324_E. Sleeping Schedule
Vova had a pretty weird sleeping schedule. There are h hours in a day. Vova will sleep exactly n times. The i-th time he will sleep exactly after a_i hours from the time he woke up. You can assume that Vova woke up exactly at the beginning of this story (the initial time is 0). Each time Vova sleeps exactly one day (in...
```python def indices(arr): ind = [] for i, val in enumerate(arr): if val >= 0: ind.append(i) return ind def e(hours, mem, lo, hi, hour_day): for i in range(len(hours)): # for each day non_zero = indices(mem[i]) for v in non_zero: next_hour = (v + hour...
1343_D. Constant Palindrome Sum
You are given an array a consisting of n integers (it is guaranteed that n is even, i.e. divisible by 2). All a_i does not exceed some integer k. Your task is to replace the minimum number of elements (replacement is the following operation: choose some index i from 1 to n and replace a_i with some integer in range [1...
```python from bisect import bisect_left from collections import Counter def solve(n, k, a): s = [a[i] + a[n-i-1] for i in range(n//2)] amin = sorted([min(a[i], a[n-i-1]) for i in range(n//2)]) amax = sorted([max(a[i], a[n-i-1]) for i in range(n//2)]) ans = float('inf') counter = Counter...
1365_E. Maximum Subsequence Value
Ridhiman challenged Ashish to find the maximum valued subsequence of an array a of size n consisting of positive integers. The value of a non-empty subsequence of k elements of a is defined as ∑ 2^i over all integers i ≥ 0 such that at least max(1, k - 2) elements of the subsequence have the i-th bit set in their bin...
```python n = int(input()) l = list(map(int,input().split())) ans = 0 for i in range(n): for j in range(i,n): for k in range(j,n):ans = max(ans,l[i] | l[j] | l[k]) print(ans) ```
1385_E. Directing Edges
You are given a graph consisting of n vertices and m edges. It is not guaranteed that the given graph is connected. Some edges are already directed and you can't change their direction. Other edges are undirected and you have to choose some direction for all these edges. You have to direct undirected edges in such a w...
```python from sys import stdin, gettrace from collections import deque if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n,m = map(int, inputi().split()) dadjs = [[] for _ in range(n)] dadjd = ...
1407_C. Chocolate Bunny
This is an interactive problem. We hid from you a permutation p of length n, consisting of the elements from 1 to n. You want to guess it. To do that, you can give us 2 different indices i and j, and we will reply with p_{i} mod p_{j} (remainder of division p_{i} by p_{j}). We have enough patience to answer at most 2...
```python import sys DEBUG = False def debug(*args): if not DEBUG: return print("\033[0;31m", end="", file=sys.stderr) print(*args, file=sys.stderr) print("\033[0m", end="", file=sys.stderr) sys.stderr.flush() def readInt(): line = input() while line == "": line = input(...