name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
158_D. Ice Sculptures
The Berland University is preparing to celebrate the 256-th anniversary of its founding! A specially appointed Vice Rector for the celebration prepares to decorate the campus. In the center of the campus n ice sculptures were erected. The sculptures are arranged in a circle at equal distances from each other, so they f...
```python n=int(input()) s=list(map(int,input().split())) max=0 for i in range(n): max+=s[i] for i in range(2,n): if n%i==0 and n//i>=3: for j in range(i): sum=0 x=j while(x<n): sum+=s[x] x+=i if sum>max:max=sum print(max)...
200_B. Drinks
Little Vasya loves orange juice very much. That's why any food and drink in his kitchen necessarily contains orange juice. There are n drinks in his fridge, the volume fraction of orange juice in the i-th drink equals pi percent. One day Vasya decided to make himself an orange cocktail. He took equal proportions of ea...
```python napitki = int(input()) apelsina_v_soke = [int(x) for x in input().split()] kokteil = sum(apelsina_v_soke) / napitki kokteil = format(kokteil, '.12f') print(kokteil) ```
225_A. Dice Tower
A dice is a cube, its faces contain distinct integers from 1 to 6 as black points. The sum of numbers at the opposite dice faces always equals 7. Please note that there are only two dice (these dices are mirror of each other) that satisfy the given constraints (both of them are shown on the picture on the left). <imag...
```python q=int(input()) w=int(input()) k=0 for i in range(q): e=list(map(int,input().split())) if (w in e) or ((7-w) in e): print('NO') k=1 break if k==0: print('YES') ```
249_D. Donkey and Stars
In the evenings Donkey would join Shrek to look at the stars. They would sit on a log, sipping tea and they would watch the starry sky. The sky hung above the roof, right behind the chimney. Shrek's stars were to the right of the chimney and the Donkey's stars were to the left. Most days the Donkey would just count the...
```python import bisect def INPUT(): global n, a, b, c, d n = int(input()) a, b, c, d = [int(j) for i in input().split() for j in i.split("/")] global y_alpha y_alpha = [] for _ in range(n): x, y = [int(x) for x in input().split()] y_alpha.append((b * y - a * x, c * x - d * y)) if __name__ == '__main__': ...
297_B. Fish Weight
It is known that there are k fish species in the polar ocean, numbered from 1 to k. They are sorted by non-decreasing order of their weight, which is a positive number. Let the weight of the i-th type of fish be wi, then 0 < w1 ≤ w2 ≤ ... ≤ wk holds. Polar bears Alice and Bob each have caught some fish, and they are g...
```python n,m,k=list(map(int,input().split())) a=sorted(list(map(int,input().split()))) b=sorted(list(map(int,input().split()))) for i in range(n): if a[-i-1]>int(b[-i-1] if i<m else 0): print('YES') break else: print('NO') ```
31_E. TV Game
There is a new TV game on BerTV. In this game two players get a number A consisting of 2n digits. Before each turn players determine who will make the next move. Each player should make exactly n moves. On it's turn i-th player takes the leftmost digit of A and appends it to his or her number Si. After that this leftmo...
```python n = int(input()) s = input() mat = [[[int(0),int(0),""] for _i in range(n+1)] for _j in range(n+1)] for i in range(2*n): digit = int(s[i]) toIter = min(i,n) minh = max(i-n,0) maxh = min(n,i) for m in range(minh,maxh+1): h = i - m v = mat[h][m] if h < n: #add current symbol to homer v...
368_B. Sereja and Suffixes
Sereja has an array a, consisting of n integers a1, a2, ..., an. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out m integers l1, l2, ..., lm (1 ≤ li ≤ n). For each number li he wants to know how many distinct numbers are staying on the positions li, li + 1, ......
```python n, m = map(int, input().split()) l = list(map(int, input().split())) els = [] for i in range(m): els.append(int(input())) b = set() aux = [0]*n cont = 0 for i in range(n-1, -1, -1): if l[i] not in b: b.add(l[i]) cont += 1 aux[i] = cont for i in els: print(aux[i-1]) ```
412_B. Network Configuration
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessar...
```python n,k=[int(i)for i in input().split()] l1=list(map(int,input().strip().split())) l1.sort() print(l1[n-k]) ```
439_D. Devu and his Brother
Devu and his brother love each other a lot. As they are super geeks, they only like to play with arrays. They are given two arrays a and b by their father. The array a is given to Devu and b to his brother. As Devu is really a naughty kid, he wants the minimum value of his array a should be at least as much as the ma...
```python def costo(a, b, t): resultado = 0 for elem in a: resultado += max(t - elem, 0) for elem in b: resultado += max(elem - t, 0) return resultado m, n = tuple(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) inf, sup = min(a), max...
461_A. Appleman and Toastman
Appleman and Toastman play a game. Initially Appleman gives one group of n numbers to the Toastman, then they start to complete the following tasks: * Each time Toastman gets a group of numbers, he sums up all the numbers and adds this sum to the score. Then he gives the group to the Appleman. * Each time Applema...
```python n=int(input()) a=sorted([int(i) for i in input().split()]) l=len(a) out=0 for i in range(l): out+=(i+2)*a[i] out-=a[l-1] print(out) ```
508_E. Arthur and Brackets
Notice that the memory limit is non-standard. Recently Arthur and Sasha have studied correct bracket sequences. Arthur understood this topic perfectly and become so amazed about correct bracket sequences, so he even got himself a favorite correct bracket sequence of length 2n. Unlike Arthur, Sasha understood the topic...
```python n = int(input()) L = [tuple(map(int, input().split(' '))) for i in range(n)] ans = [] try : for l,r in reversed(L) : d,a=1,"(" while d < l : d += len(ans[-1]) a += ans.pop() if d > r : raise IndexError a += ")" ans.append(a) except IndexError...
533_B. Work Group
One Big Software Company has n employees numbered from 1 to n. The director is assigned number 1. Every employee of the company except the director has exactly one immediate superior. The director, of course, doesn't have a superior. We will call person a a subordinates of another person b, if either b is an immediate...
```python n = int(input()) t = [list(map(int, input().split())) for q in range(n)] t[0][0] = 0 n += 1 u = [-1e7] * n v = [0] * n for i, (j, a) in list(enumerate(t, 1))[::-1]: u[i] = max(u[i], v[i] + a) v[j], u[j] = max(v[j] + v[i], u[j] + u[i]), max(v[j] + u[i], u[j] + v[i]) print(u[1]) ```
558_A. Lala Land and Apple Trees
Amr lives in Lala Land. Lala Land is a very beautiful country that is located on a coordinate line. Lala Land is famous with its apple trees growing everywhere. Lala Land has exactly n apple trees. Tree number i is located in a position xi and has ai apples growing on it. Amr wants to collect apples from the apple tre...
```python a = [list(map(int, input().split(" "))) for x in range(int(input()))] pl = []; ol = [] for i in range(len(a)): if a[i][0] < 0: ol.append(a[i]) else: pl.append(a[i]) pl.sort(); ol.sort(); ol.reverse() del a; dl = abs(len(ol)-len(pl)); sum = int(0); j = 0 m = min(len(ol), len(pl)) if (le...
583_D. Once Again...
You are given an array of positive integers a1, a2, ..., an × T of length n × T. We know that for any i > n it is true that ai = ai - n. Find the length of the longest non-decreasing sequence of the given array. Input The first line contains two space-separated integers: n, T (1 ≤ n ≤ 100, 1 ≤ T ≤ 107). The second li...
```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 if se...
677_C. Vanya and Label
While walking down the street Vanya saw a label "Hide&Seek". Because he is a programmer, he used & as a bitwise AND for these two words represented as a integers in base 64 and got new word. Now Vanya thinks of some string s and wants to know the number of pairs of words of length |s| (length of s), such that their bit...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
6_C. Alice, Bob and Chocolate
Alice and Bob like games. And now they are ready to start a new game. They have placed n chocolate bars in a line. Alice starts to eat chocolate bars one by one from left to right, and Bob — from right to left. For each chocololate bar the time, needed for the player to consume it, is known (Alice and Bob eat them with...
```python n=int(input()) *l,=map(int,input().split()) a=b=i=0 j=n-1 while i<=j: if a<=b:a+=l[i];i+=1 else:b+=l[j];j-=1 print(i,n-i) #hello ```
743_C. Vladik and fractions
Vladik and Chloe decided to determine who of them is better at math. Vladik claimed that for any positive integer n he can represent fraction <image> as a sum of three distinct positive fractions in form <image>. Help Vladik with that, i.e for a given n find three distinct positive integers x, y and z such that <image...
```python n = int(input()) if n == 1: print(-1) else: print(n, n + 1, n + n ** 2) ```
78_D. Archer's Shot
A breakthrough among computer games, "Civilization XIII", is striking in its scale and elaborate details. Let's take a closer look at one of them. The playing area in the game is split into congruent cells that are regular hexagons. The side of each cell is equal to 1. Each unit occupies exactly one cell of the playin...
```python import math k = int(input()) n = int(k/3)*2 + 1 # print('n', n) ans = 0 last = 0 while True: point_to_check = (n+2)//2 # print('p', point_to_check) x = 0.0 y = n# *math.sqrt(3) # print('r', math.sqrt((x**2+y**2))) # p1 x -= 0.5 y += 0.5 #* math.sqrt(3) # print('r',...
811_A. Vladik and Courtesy
At regular competition Vladik and Valera won a and b candies respectively. Vladik offered 1 his candy to Valera. After that Valera gave Vladik 2 his candies, so that no one thought that he was less generous. Vladik for same reason gave 3 candies to Valera in next turn. More formally, the guys take turns giving each ot...
```python # coding: utf-8 import math vs = ["Vladik", "Valera"] a, b = map(int, input().split(" ")) an = math.floor(math.sqrt(a)) bn = 0 while True: bn += 1 if b < bn * (bn + 1): bn -= 1 break print(vs[an > bn]) ```
837_C. Two Seals
One very important person has a piece of paper in the form of a rectangle a × b. Also, he has n seals. Each seal leaves an impression on the paper in the form of a rectangle of the size xi × yi. Each impression must be parallel to the sides of the piece of paper (but seal can be rotated by 90 degrees). A very importa...
```python n,A,B=map(int,input().split()) arr=[] for x in range(n): i,j=map(int,input().split()) arr.append([i,j]) ans=int(0) i=int(0) j=int(0) for i in range(n): for j in range(i+1,n): a=arr[i][0] b=arr[i][1] c=arr[j][0] d=arr[j][1] temp=a*b+c*d if(temp<=ans):...
883_E. Field of Wonders
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden. The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter ...
```python n = int(input()) S = input() HaveLetters = set(list(S)) m = int(input()) words = [] CanLetters = set([chr(i) for i in range(ord("a"), ord("z") + 1)]) - HaveLetters for _ in range(m): Word = input() for i in range(n): if S[i] == "*": if Word[i] in HaveLetters: break ...
926_G. Large Bouquets
A flower shop has got n bouquets, and the i-th bouquet consists of ai flowers. Vasya, the manager of the shop, decided to make large bouquets from these bouquets. Vasya thinks that a bouquet is large if it is made of two or more initial bouquets, and there is a constraint: the total number of flowers in a large bouqu...
```python n = int(input()) flowers = input().split() odd = 0 ott = 0 for val in flowers: if int(val) % 2 == 0: odd += 1 else: ott += 1 while ott > odd + 2: ott -= 2 odd += 1 print(min(odd, ott)) ```
p02556 AtCoder Beginner Contest 178 - Dist Max
There are N points on the 2D plane, i-th of which is located on (x_i, y_i). There can be multiple points that share the same coordinate. What is the maximum possible Manhattan distance between two distinct points? Here, the Manhattan distance between two points (x_i, y_i) and (x_j, y_j) is defined by |x_i-x_j| + |y_i-...
```python N=int(input()) x=[] y=[] for i in range(N): b,c=map(int,input().split(" ")) x.append(b+c) y.append(b-c) print(max([max(x)-min(x),max(y)-min(y)])) ```
p02687 AtCoder Beginner Contest 166 - A?C
AtCoder Inc. holds a contest every Saturday. There are two types of contests called ABC and ARC, and just one of them is held at a time. The company holds these two types of contests alternately: an ARC follows an ABC and vice versa. Given a string S representing the type of the contest held last week, print the str...
```python s = str(input()) print("ARC" if s == "ABC" else "ABC") ```
p02816 AtCoder Beginner Contest 150 - Xor Shift
Given are two sequences a=\\{a_0,\ldots,a_{N-1}\\} and b=\\{b_0,\ldots,b_{N-1}\\} of N non-negative integers each. Snuke will choose an integer k such that 0 \leq k < N and an integer x not less than 0, to make a new sequence of length N, a'=\\{a_0',\ldots,a_{N-1}'\\}, as follows: * a_i'= a_{i+k \mod N}\ XOR \ x F...
```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) a = a + a[:-1] da = [a[i] ^ a[i+1] for i in range(len(a) - 1)] db = [b[i] ^ b[i+1] for i in range(len(b) - 1)] fail = [0 for i in range(len(da))] fail[0] = -1 p = 0 for q in range(2, len(da)): while p >= 0 and da[q...
p02952 AtCoder Beginner Contest 136 - Uneven Numbers
Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros). Constraints * 1 \leq N \leq 10^5 Input Input is given from Standard Input in the following format: N Output Print the number of positive integers less than ...
```python a = int(input()) b = [i for i in range(a) if len(str(i+1))%2!=0] print(len(b)) ```
p03088 AtCoder Beginner Contest 122 - We Like AGC
You are given an integer N. Find the number of strings of length N that satisfy the following conditions, modulo 10^9+7: * The string does not contain characters other than `A`, `C`, `G` and `T`. * The string does not contain `AGC` as a substring. * The condition above cannot be violated by swapping two adjacent chara...
```python N = int(input()) memo = [{} for i in range(N + 1)] MOD = 10 ** 9 + 7 def ok(last4): for i in range(4): t = list(last4) if i >= 1: t[i], t[i - 1] = t[i - 1], t[i] if "".join(t).count("AGC") >= 1: return False return True def ...
p03233 AtCoder Grand Contest 028 - Min Cost Cycle
We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in thi...
```python import sys import socket if socket.gethostname() in ['N551J', 'F551C']: test_case = 'c1.in' sys.stdin = open(test_case) def read_int_list(): return list(map(int, input().split())) def read_int(): return int(input()) def read_str_list(): return input().split() def read_str(): r...
p03384 AtCoder Regular Contest 095 - Permutation Tree
Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. S...
```python import sys from collections import deque def diameter(n, links): q = deque([(0, -1)]) v = 0 while q: v, p = q.popleft() q.extend((u, v) for u in links[v] if u != p) q = deque([(v, -1)]) w = 0 parents = [-1] * n while q: w, p = q.popleft() parents[...
p03548 AtCoder Beginner Contest 078 - ISU
We have a long seat of width X centimeters. There are many people who wants to sit here. A person sitting on the seat will always occupy an interval of length Y centimeters. We would like to seat as many people as possible, but they are all very shy, and there must be a gap of length at least Z centimeters between two...
```python x,y,z=map(int,input().split()) x-=z print(x//(z+y)) ```
p03704 AtCoder Regular Contest 075 - Mirrored
For a positive integer n, we denote the integer obtained by reversing the decimal notation of n (without leading zeroes) by rev(n). For example, rev(123) = 321 and rev(4000) = 4. You are given a positive integer D. How many positive integers N satisfy rev(N) = N + D? Constraints * D is an integer. * 1 ≤ D < 10^9 In...
```python def solve(d, K): r = 1 for k in range(K,1,-2): if d >= 10**k: return 0 t = (-d)%10 d = abs((d-t*(10**(k-1)-1))//10) r *= 10-t-(K==k) return r*(10**(K%2)) if d == 0 else 0 D = int(input()) result = 0 l = len(str(D)) for k in range(l,2*l+1): result += solve(D, k) print(result) ``...
p03859 AtCoder Regular Contest 065 - Shuffling
There is a string S of length N consisting of characters `0` and `1`. You will perform the following operation for each i = 1, 2, ..., m: * Arbitrarily permute the characters within the substring of S starting at the l_i-th character from the left and extending through the r_i-th character. Here, the sequence l_i i...
```python # coding: utf-8 # Your code here! import sys read = sys.stdin.read readline = sys.stdin.readline n,m = map(int,readline().split()) s = input() mp = map(int,read().split()) r = list(range(n)) for i,j in zip(mp,mp): if r[i-1] < j-1: r[i-1] = j-1 for i in range(1,n): if r[i] < r[i-1]: r[i] = r...
p00108 Operation of Frequency of Appearance
There is a frequency operation in the conversion operation of a finite number sequence. The conversion result of the sequence $ S = \\ {s_1, s_2, ... s_n \\} $ is a sequence of the same length. If the result is $ C = \\ {c_1, c_2, ..., c_n \\} $, then $ c_i $ represents the number of $ s_i $ in the sequence $ S $. For...
```python from collections import Counter def pr(s): c=0 while 1: b=s t=Counter(s) s=[t[i] for i in s] c+=1 if b==s:break return s,c-1 while 1: le=int(input()) if not le:break s=list(map(int,input().split())) s,c=pr(s) print(c) print(" "....
p00242 Input Candidates
Mobile phones are equipped with a function that displays input candidates in order to efficiently input texts such as emails. This records frequently used words and presents words that have the entered letters as initial letters as input candidates. For example, if you usually enter the word "computer" a lot, just ente...
```python from collections import defaultdict while True: n = int(input()) if n==0: break initial = defaultdict(set) cnt = defaultdict(int) for _ in range(n): l = list(input().split()) for li in l: initial[li[0]].add(li) cnt[li...
p00423 Card Game
Two players, A and B, play the game using cards with numbers from 0 to 9. First, the two arrange the given n cards face down in a horizontal row. After that, the two players turn their cards face up one by one from the left, and the owner of the card with the larger number takes the two cards. At this time, the sum of ...
```python while True: n = int(input()) if n == 0: break pointA, pointB = 0, 0 for i in range(n): cardA, cardB = map(int, input().split()) if cardA == cardB: pointA += cardA pointB += cardB elif cardA > cardB: pointA += cardA + cardB ...
p00762 Biased Dice
Professor Random, known for his research on randomized algorithms, is now conducting an experiment on biased dice. His experiment consists of dropping a number of dice onto a plane, one after another from a fixed position above the plane. The dice fall onto the plane or dice already there, without rotating, and may rol...
```python def get_num(top): # 転がす番号の候補を決める if top == 1: return [5, 4] elif top == 2: return [6, 4] elif top == 3: return [6, 5] elif top == 4: return [6, 5] elif top == 5: return [6, 4] elif top == 6: return [5, 4] def get_dir(num, front, top): ...
p00894 Gift from the Goddess of Programming
The goddess of programming is reviewing a thick logbook, which is a yearly record of visitors to her holy altar of programming. The logbook also records her visits at the altar. The altar attracts programmers from all over the world because one visitor is chosen every year and endowed with a gift of miracle programmin...
```python import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in ...
p01297 Safe Area
Nathan O. Davis is challenging a kind of shooter game. In this game, enemies emit laser beams from outside of the screen. A laser beam is a straight line with a certain thickness. Nathan moves a circular-shaped machine within the screen, in such a way it does not overlap a laser beam. As in many shooters, the machine i...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def cross_point(p0, q0, p1, q1): x0, y0 = p0; x1, y1 = q0 x2, y2 = p1; x3, y3 = q1 dx0 = x1 - x0 dy0 = y1 - y0 dx1 = x3 - x2 dy1 = y3 - y2 s = (y0-y2)*dx1 - (x0-x2)*dy1 sm = dx0*dy1 - dy0*dx1 if sm == 0: ...
p02347 Range Search (kD Tree)
The range search problem consists of a set of attributed records S to determine which records from S intersect with a given range. For n points on a plane, report a set of points which are within in a given range. Note that you do not need to consider insert and delete operations for the set. Constraints * 0 ≤ n ≤ 5...
```python import math import sys from bisect import bisect_left, bisect_right from typing import List, Optional, Tuple class KDTree(object): def __init__(self, n: int) -> None: self.n = n self.root = int(math.sqrt(n)) self.coordinates = [(0, 0, 0)] * n self.low: List[int] = [] ...
101_A. Homework
Once when Gerald studied in the first year at school, his teacher gave the class the following homework. She offered the students a string consisting of n small Latin letters; the task was to learn the way the letters that the string contains are written. However, as Gerald is too lazy, he has no desire whatsoever to l...
```python from collections import Counter import operator import random a=list(input()) k=int(input()) omap=(Counter(a)) x=sorted(omap.items(), key = operator.itemgetter(1)) i=0 while(k>0 and i<len(x)): if(x[i][1]<=k): k=k-x[i][1] del omap[x[i][0]] else: omap[x[i][0]]=omap[x[i][0]]-k k=0 i+=1 print(len(oma...
1042_E. Vasya and Magic Matrix
Vasya has got a magic matrix a of size n × m. The rows of the matrix are numbered from 1 to n from top to bottom, the columns are numbered from 1 to m from left to right. Let a_{ij} be the element in the intersection of the i-th row and the j-th column. Vasya has also got a chip. Initially, the chip is in the intersec...
```python import io, os ns = iter(os.read(0, os.fstat(0).st_size).split()).__next__ MX = 10 ** 6 MOD = 998244353 n, m = int(ns()), int(ns()) a = [int(ns()) for i in range(n * m)] s = (int(ns()) - 1) * m + int(ns()) - 1 inv = [1] * MX for i in range(2, MX): inv[i] = -(MOD // i) * inv[MOD % i] % MOD ind = sorted(...
1065_D. Three Pieces
You stumbled upon a new kind of chess puzzles. The chessboard you are given is not necesserily 8 × 8, but it still is N × N. Each square has some number written on it, all the numbers are from 1 to N^2 and all the numbers are pairwise distinct. The j-th square in the i-th row has a number A_{ij} written on it. In your...
```python import sys from math import * def minp(): return sys.stdin.readline().strip() n = int(minp()) m = [None]*n k = [None]*3 dp = [None]*3 dp[0] = [None]*(n*n) dp[1] = [None]*(n*n) dp[2] = [None]*(n*n) path = [None]*(n*n) for i in range(n): m[i] = list(map(int, minp().split())) for j in range(n): path[m[i][...
1088_B. Ehab and subtraction
You're given an array a. You should repeat the following operation k times: find the minimum non-zero element in the array, print it, and then subtract it from all the non-zero elements of the array. If all the elements are 0s, just print 0. Input The first line contains integers n and k (1 ≤ n,k ≤ 10^5), the length ...
```python # coding: utf-8 # Your code here! import sys n,k = map(int,input().split()) A = list(map(int,input().split())) A.sort() cnt = 0 prev = 0 for i in range(len(A)): ans = A[i] - prev if ans != 0: print(ans) prev = A[i] cnt += 1 if cnt == k: break for _ in ...
1107_B. Digital root
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d...
```python n = int(input()) for _ in range(n): k,x = map(int,input().split(" ")) print((k-1)*9+x) ```
1136_B. Nastya Is Playing Computer Games
Finished her homework, Nastya decided to play computer games. Passing levels one by one, Nastya eventually faced a problem. Her mission is to leave a room, where a lot of monsters live, as quickly as possible. There are n manholes in the room which are situated on one line, but, unfortunately, all the manholes are clo...
```python n,k=map(int,input().split()) print(n+min(k-1,n-k)+2*n) ```
1154_F. Shovels Shop
There are n shovels in the nearby shop. The i-th shovel costs a_i bourles. Misha has to buy exactly k shovels. Each shovel can be bought no more than once. Misha can buy shovels by several purchases. During one purchase he can choose any subset of remaining (non-bought) shovels and buy this subset. There are also m ...
```python from sys import stdin, stdout n, m, k = tuple(map(lambda x: int(x), stdin.readline().split())) a = stdin.readline().split() for i in range(len(a)): a[i] = int(a[i]) prefix_sum = [] a = sorted(a, key=lambda x: x) for x in a: if prefix_sum: prefix_sum.append(prefix_sum[-1] + x) else: ...
1176_D. Recover it!
Authors guessed an array a consisting of n integers; each integer is not less than 2 and not greater than 2 ⋅ 10^5. You don't know the array a, but you know the array b which is formed from it with the following sequence of operations: 1. Firstly, let the array b be equal to the array a; 2. Secondly, for each i f...
```python from sys import stdin, stdout import collections import math import heapq def primes(n): """ Returns a list of primes < n """ sieve = [True] * n for i in range(3,int(n**0.5)+1,2): if sieve[i]: sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1) return [2] + [i for i in range(3,n...
1195_C. Basketball Exercise
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ...
```python n=int(input()) a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] dp=[[-1,-1] for i in range(n-1)] dp.append([a[n-1],b[n-1]]) dp.append([0,0]) for i in range(n-1): dp[n-2-i][0]=a[n-2-i]+max(dp[n-1-i][1],dp[n-i][1]) dp[n-2-i][1]=b[n-2-i]+max(dp[n-1-i][0],dp[n-i][0]) print(max(dp[0]...
1234_E. Special Permutations
Let's define p_i(n) as the following permutation: [i, 1, 2, ..., i - 1, i + 1, ..., n]. This means that the i-th permutation is almost identity (i.e. which maps every element to itself) permutation but the element i is on the first position. Examples: * p_1(4) = [1, 2, 3, 4]; * p_2(4) = [2, 1, 3, 4]; * p_3(4) ...
```python """ > File Name: e.py > Author: Code_Bear > Mail: secret > Created Time: Tue Oct 15 17:00:25 2019 """ #import sys #input = sys.stdin.readline def solver(): n, m = map(int, input().split()) s = list(map(int, input().split())) xin, xout = [0] * (n + 10), [0] * (n + 10) xsum = [...
1253_D. Harmonious Graph
You're given an undirected graph with n nodes and m edges. Nodes are numbered from 1 to n. The graph is considered harmonious if and only if the following property holds: * For every triple of integers (l, m, r) such that 1 ≤ l < m < r ≤ n, if there exists a path going from node l to node r, then there exists a pat...
```python import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(300000) n, m = map(int, input().split()) sn, smx = list(range(n+1)), list(range(n+1)) def s_find(u): p = [] while sn[u] != u: p.append(u) u = sn[u] for v in p: sn[v] = u return u def s_union(u, v): su, sv...
1277_C. As Simple as One and Two
You are given a non-empty string s=s_1s_2... s_n, which consists only of lowercase Latin letters. Polycarp does not like a string if it contains at least one string "one" or at least one string "two" (or both at the same time) as a substring. In other words, Polycarp does not like the string s if there is an integer j ...
```python t = int(input()) for _ in range(t): s = input() i = 0 R = [] while i < len(s): # print(s[i:i+5]) if i+4<len(s) and s[i:i+5] == "twone": # print('paso') R.append(i+2+1) i+=5 elif i+2<len(s) and (s[i:i+3] == "one" or s[i:i+3] == "two"):...
1320_D. Reachable Strings
In this problem, we will deal with binary strings. Each character of a binary string is either a 0 or a 1. We will also deal with substrings; recall that a substring is a contiguous subsequence of a string. We denote the substring of string s starting from the l-th character and ending with the r-th character as s[l .....
```python import sys input = sys.stdin.readline n=int(input()) t=input().strip() q=int(input()) ZEROS=[0]*n ZERO_ONE=[] ONECOUNT=[0]*n ind=0 count=0 for i in range(n): ZEROS[i]=ind if t[i]=="0": ind+=1 ONECOUNT[i]=count%2 ZERO_ONE.append(count%2) count=0 else: coun...
133_B. Unary
Unary is a minimalistic Brainfuck dialect in which programs are written using only one token. Brainfuck programs use 8 commands: "+", "-", "[", "]", "<", ">", "." and "," (their meaning is not important for the purposes of this problem). Unary programs are created from Brainfuck programs using the following algorithm...
```python # n=bin() s=input() ans="" for i in s: if i==">": ans+="1000" elif i=="<": ans+="1001" elif i =="+": ans+="1010" elif i=="-": ans+="1011" elif i==".": ans+="1100" elif i==",": ans+="1101" elif i=="[": ans+="1110" elif i=...
1381_D. The Majestic Brown Tree Snake
There is an undirected tree of n vertices, connected by n-1 bidirectional edges. There is also a snake stuck inside of this tree. Its head is at vertex a and its tail is at vertex b. The snake's body occupies all vertices on the unique simple path between a and b. The snake wants to know if it can reverse itself — tha...
```python import sys T=int(sys.stdin.readline().strip()) #T=1 def dfs(x, h, fa): stack_queue=[] stack_queue.append((x,h,fa,0, 0)) while (len(stack_queue)>0) : now=stack_queue.pop() x,h,fa,r, idone=now #print (x,r,idone,fa,stack_queue) if r==0: for i1 in range(idone,len(e[x])): i=e[x][i1] if...
1401_E. Divide Square
There is a square of size 10^6 × 10^6 on the coordinate plane with four points (0, 0), (0, 10^6), (10^6, 0), and (10^6, 10^6) as its vertices. You are going to draw segments on the plane. All segments are either horizontal or vertical and intersect with at least one side of the square. Now you are wondering how many ...
```python import sys, math import io, os data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline #from bisect import bisect_left as bl, bisect_right as br, insort #from heapq import heapify, heappush, heappop #from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations ...
1446_C. Xor Tree
For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way: * Consider a graph on k nodes, with numbers from b_1 to b_k written on them. * For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j,...
```python from bisect import bisect_left import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n=int(input()) a=list(map(int,input().split())) a.sort() ans=0 tmp=0 t=bisect_left(a,0) s=bisect_left(a,1<<31) stack=[(0,1<<31,t,s,0)] while stack: l,r,l1,r1,score=stack.pop() ans=max(score,ans) if l+1=...
1497_B. M-arrays
You are given an array a_1, a_2, …, a_n consisting of n positive integers and a positive integer m. You should divide elements of this array into some arrays. You can order the elements in the new arrays as you want. Let's call an array m-divisible if for each two adjacent numbers in the array (two numbers on the pos...
```python import math for _ in range(int(input())): n,m=map(int,input().split()) a=list(map(int,input().split())) rems=[0]*m for e in a: rems[e%m]+=1 ans=1 if rems[0]>0 else 0 for i in range(1,m//2+1): if rems[i]==0 and rems[m-i]==0: continue ma...
151_A. Soft Drinking
This winter is so cold in Nvodsk! A group of n friends decided to buy k bottles of a soft drink called "Take-It-Light" to warm up a bit. Each bottle has l milliliters of the drink. Also they bought c limes and cut each of them into d slices. After that they found p grams of salt. To make a toast, each friend needs nl ...
```python party = list(map(int, input().split())) friends, bottles, ml, limes, lime_slices, salt, friend_ml, friend_salt = party total_gas = bottles * ml total_limes = limes * lime_slices rotation_ml = friend_ml * friends q_tosts = -1 while all(x >= 0 for x in (salt, total_gas, total_limes)): total_gas -= rota...
1547_A. Shortest Path with Obstacle
There are three cells on an infinite 2-dimensional grid, labeled A, B, and F. Find the length of the shortest path from A to B if: * in one move you can go to any of the four adjacent cells sharing a side; * visiting the cell F is forbidden (it is an obstacle). Input The first line contains an integer t (1 ≤ ...
```python import sys import bisect #import math #import itertools def get_line(): return list(map(int, sys.stdin.readline().strip().split())) def in1(): return int(input()) def decimalToBinary(n): return bin(n).replace("0b", "") for _ in range(in1()): t=get_line() a1,a2=get_line() b1,b2=get_line() f1,...
174_C. Range Increments
Polycarpus is an amateur programmer. Now he is analyzing a friend's program. He has already found there the function rangeIncrement(l, r), that adds 1 to each element of some array a for all indexes in the segment [l, r]. In other words, this function does the following: function rangeIncrement(l,...
```python n = int(input()) big = 10 ** 5 last = (big + 1) * [ -1 ] data = list(map(int, input().split())) data.insert(0, 0) data.append(0) result = [] previous = 0 for pos, current in enumerate(data): if current > previous: for x in range(previous + 1, current + 1): last[x] = pos elif curre...
242_A. Heads or Tails
Petya and Vasya are tossing a coin. Their friend Valera is appointed as a judge. The game is very simple. First Vasya tosses a coin x times, then Petya tosses a coin y times. If the tossing player gets head, he scores one point. If he gets tail, nobody gets any points. The winner is the player with most points by the e...
```python x, y, a, b = map(int, input().split()) ans = [] for x1 in range(a,x+1): if x1<=b: continue for y1 in range(b,y+1): if x1>y1 and x1>=a and y1>=b: ans.append((x1,y1)) print(len(ans)) for x in ans: print(*x) ```
267_B. Dominoes
You have a set of dominoes. Each domino is a rectangular tile with a line dividing its face into two square ends. Can you put all dominoes in a line one by one from left to right so that any two dominoes touched with the sides that had the same number of points? You can rotate the dominoes, changing the left and the ri...
```python def euler(start): s = [(start,0)] ans = [] while s: i,e = s[-1] if i in mark: mark.remove(i) if degree[i]==0: ans.append(e) s.pop() else: for j,e in graph[i]: if vis[abs(e)]==0: d...
290_B. QR code
<image> Input The input contains two integers a1, a2 (0 ≤ ai ≤ 32), separated by a single space. Output Output a single integer. Examples Input 1 1 Output 0 Input 3 7 Output 0 Input 13 10 Output 1
```python num = input().split() print(int(num[0]) + int(num[1][::-1])) ```
316_A2. Special Task
Special Agent Smart Beaver works in a secret research department of ABBYY. He's been working there for a long time and is satisfied with his job, as it allows him to eat out in the best restaurants and order the most expensive and exotic wood types there. The content special agent has got an important task: to get th...
```python import math ''' r,c,n,k = map(int,input().split()) matrix = [['*' for row in range(c)] for column in range(r)] for i in range(n): x,y = map(int,input().split()) matrix[x-1][y-1] = '#' ans = 0 for row1 in range(r): for row2 in range(r): if matrix[row1:row2+1].count('#') >= k: an...
338_D. GCD Table
Consider a table G of size n × m such that G(i, j) = GCD(i, j) for all 1 ≤ i ≤ n, 1 ≤ j ≤ m. GCD(a, b) is the greatest common divisor of numbers a and b. You have a sequence of positive integer numbers a1, a2, ..., ak. We say that this sequence occurs in table G if it coincides with consecutive elements in some row, s...
```python from math import gcd def LCM(a, b): if min(a, b) == 0: return max(a, b) return a // gcd(a, b) * b class Eqn(): def __init__(self, r, mod): self.r = r self.mod = mod def bye(): print("NO") exit(0) def exgcd(a, b): if b == 0: return (1, 0) xp, yp = e...
361_A. Levko and Table
Levko loves tables that consist of n rows and n columns very much. He especially loves beautiful tables. A table is beautiful to Levko if the sum of elements in each row and column of the table equals k. Unfortunately, he doesn't know any such table. Your task is to help him to find at least one of them. Input The ...
```python n, p = map(int, input().split()) for i in range(n): arr = [] for j in range(n): arr.append("0") arr[i] = str(p) answer = " ".join(arr) print(answer) ```
405_C. 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 operator import and_, xor # from functools import reduce # from itertools import chain from sys import stdin input = stdin.readline n = int(input()) l = list(list(map(int, input().split())) for _ in range(n)) q = int(input()) output = [] ans = 0 # We don't care about anything except for the trace of ...
432_D. Prefixes and Suffixes
You have a string s = s1s2...s|s|, where |s| is the length of string s, and si its i-th character. Let's introduce several definitions: * A substring s[i..j] (1 ≤ i ≤ j ≤ |s|) of string s is string sisi + 1...sj. * The prefix of string s of length l (1 ≤ l ≤ |s|) is string s[1..l]. * The suffix of string s o...
```python def zeta(s): n = len(s) z = [0]*n l,r = 0,0 for i in range(1,n): if(i<=r): z[i] = min(r-i+1,z[i-l]) while(i+z[i]<n and s[z[i]]==s[i+z[i]]): z[i]+=1 if(i+z[i]-1>r): l=i r = i+z[i]-1 return z s = input() n = len(s) z = zeta(s) l = [0]*n for i in z: l[i]+=1 cum = [l[-1]] for i in range(n-2,-...
455_A. Boredom
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
```python n = int(input()) l = input().split() g = [0]*100000 for i in l: g[int(i)-1] += 1 ''' p = [] a = [] for i in range(100000): b = g[i] if b!=0: a.append((i+1)*b) else: if a != []: p.append(a) a = [] def f(v): if v==[]: return 0 elif len(v)==...
500_A. New Year Transportation
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells. So, user tncks0121 has ...
```python a, b = map(int, input().split()) c = list(map(int, input().split())) d = 0 while d < b - 1: d += c[d] if d == b - 1: print("YES") else: print("NO") ```
550_E. Brackets in Implications
Implication is a function of two logical arguments, its value is false if and only if the value of the first argument is true and the value of the second argument is false. Implication is written by using character '<image>', and the arguments and the result of the implication are written as '0' (false) and '1' (true...
```python n = int(input()) c = list(map(int, input().split())) idx = [i for i in range(n) if c[i] == 0] one = [i for i in range(n) if c[i] == 1] if len(idx) >= 1 and idx[-1] == n-1: if len(idx) >= 2 and idx[-2] == n-2: if len(idx) >= 3 and idx[-3] <= n-3: if idx[0] == 0: print("...
578_A. A Problem about Polyline
There is a polyline going through points (0, 0) – (x, x) – (2x, 0) – (3x, x) – (4x, 0) – ... - (2kx, 0) – (2kx + x, x) – .... We know that the polyline passes through the point (a, b). Find minimum positive value x such that it is true or determine that there is no such x. Input Only one line containing two positiv...
```python a,b=map(float,input().split()) if b>a : print(-1) exit() v=((a+b)/2)/((a+b)//(2*b)) print(v); ```
59_D. Team Arrangement
Recently personal training sessions have finished in the Berland State University Olympiad Programmer Training Centre. By the results of these training sessions teams are composed for the oncoming team contest season. Each team consists of three people. All the students of the Centre possess numbers from 1 to 3n, and a...
```python import sys I = lambda: int(input()) RL = readline = lambda: sys.stdin.readline().strip('\n') RM = readmap = lambda x = int: map(x,readline().split(' ')) def f(l,x): if x==l[0]: return l[1],l[2] if x==l[1]: return l[0],l[2] if x==l[2]: return l[0],l[1] return -1 def delrank(x): global p...
621_B. Wet Shark and Bishops
Today, Wet Shark is given n bishops on a 1000 by 1000 grid. Both rows and columns of the grid are numbered from 1 to 1000. Rows are numbered from top to bottom, while columns are numbered from left to right. Wet Shark thinks that two bishops attack each other if they share the same diagonal. Note, that this is the onl...
```python a=[0]*2001 b=[0]*2001 n=int(input()) for i in range(n): x,y=map(int,input().split()) a[x+y]+=1 b[x-y]+=1 s=0 for i in a: s=s+(i-1)*i//2 for i in b: s=s+(i-1)*i//2 print(s) ```
66_E. Petya and Post
Little Vasya's uncle is a postman. The post offices are located on one circular road. Besides, each post office has its own gas station located next to it. Petya's uncle works as follows: in the morning he should leave the house and go to some post office. In the office he receives a portion of letters and a car. Then ...
```python n = int(input()) a = list(map(int, input().split())) b = list(map(int, input().split())) INF = 1000000000000009 ml = INF mr = INF i = 0 first = True cur = 0 while first or i != 0: cur += a[i] cur -= b[i] i += 1 i %= n ml = min(ml, cur) first = False first = True cur = 0 i = 0 while fi...
691_B. s-palindrome
Let's call a string "s-palindrome" if it is symmetric about the middle of the string. For example, the string "oHo" is "s-palindrome", but the string "aa" is not. The string "aa" is not "s-palindrome", because the second half of it is not a mirror reflection of the first half. <image> English alphabet You are given a...
```python rever = "AHIMOTUVWXYovwx" rev = ["bd", "pq","db","qp"] line = input().rstrip() if len(line) & 1 and line[len(line) // 2] not in rever: print("NIE") exit() l = len(line) // 2 - 1 r = len(line) // 2 if len(line) & 1 == 0 else\ len(line) // 2 + 1 for i in range(len(line) // 2): if line[l] + lin...
716_B. Complete the Word
ZS the Coder loves to read the dictionary. He thinks that a word is nice if there exists a substring (contiguous segment of letters) of it of length 26 where each letter of English alphabet appears exactly once. In particular, if the string has length strictly less than 26, no such substring exists and thus it is not n...
```python s = input() for i in range(len(s) - 25): sub = s[i:i+26] missing = set('ABCDEFGHIJKLMNOPQRSTUVWXYZ') - set(sub) if len(missing) == sub.count('?'): while missing: sub = sub.replace('?', missing.pop(), 1) print((s[:i] + sub + s[i+26:]).replace('?', 'A')) ...
760_D. Travel Card
A new innovative ticketing systems for public transport is introduced in Bytesburg. Now there is a single travel card for all transport. To make a trip a passenger scan his card and then he is charged according to the fare. The fare is constructed in the following manner. There are three types of tickets: 1. a tic...
```python #-*- coding:utf-8 -*- #!/usr/bin/python3 n = int(input()) a = [0,] for i in range(n): x = int(input()) a.append(x) dp = [0] * (n + 1) dp[0] = 0 p90 = 1 p1440 = 1 for i in range(1, n + 1): dp[i] = dp[i - 1] + 20 while a[p90] + 90 <= a[i]: p90 = p90 + 1 dp[i] = min(dp[i], dp[p90 - 1] + 50) while a[p14...
804_E. The same permutation
Seyyed and MoJaK are friends of Sajjad. Sajjad likes a permutation. Seyyed wants to change the permutation in a way that Sajjad won't like it. Seyyed thinks more swaps yield more probability to do that, so he makes MoJaK to perform a swap between every pair of positions (i, j), where i < j, exactly once. MoJaK doesn't ...
```python n = int(input()) p = lambda a,b: print(a+1,b+1) if n % 4 > 1: print("NO") else: print("YES") for i in range(n%4,n,4): for x in range(2): for j in range(i): p(j,i+2*x) p(i+2*x,i+2*x+1) for j in range(i,0,-1): p(j-1,i+2*x+1) p(i,i+3) p(i+1,i+2) p(i,i+2) p(i+1,i+3) ```
82_D. Two out of Three
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem. Let the queue to the cashier contain n people, at that each of them is characterized by a positive integer ai — that is the time needed to work with this customer. What is special about this...
```python # 82D def do(): n = int(input()) costs = [int(c) for c in input().split(" ")] next = {} memo = {} def dp(i, pre): if i == n: memo[i, pre] = [costs[pre], [pre]] return memo[i, pre] if i == n - 1: memo[i, pre] = [max(costs[pre], costs[i])...
875_B. Sorting the Coins
Recently, Dima met with Sasha in a philatelic store, and since then they are collecting coins together. Their favorite occupation is to sort collections of coins. Sasha likes having things in order, that is why he wants his coins to be arranged in a row in such a way that firstly come coins out of circulation, and then...
```python from sys import stdin, stdout n = int(stdin.readline()) values = list(map(int, stdin.readline().split())) used = [0 for i in range(n)] right, cnt = n, 0 ans = 1 stdout.write(str(ans) + ' ') for v in values: used[v - 1] = 1 ans += 1 while right and used[right - 1]: ans -= 1 ...
89_A. Robbery
It is nighttime and Joe the Elusive got into the country's main bank's safe. The safe has n cells positioned in a row, each of them contains some amount of diamonds. Let's make the problem more comfortable to work with and mark the cells with positive numbers from 1 to n from the left to the right. Unfortunately, Joe ...
```python #------------------------template--------------------------# import os import sys from math import * from collections import * from fractions import * from bisect import * from heapq import* from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt'...
920_C. Swap Adjacent Elements
You have an array a consisting of n integers. Each integer from 1 to n appears exactly once in this array. For some indices i (1 ≤ i ≤ n - 1) it is possible to swap i-th element with (i + 1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the ...
```python n=int(input()) l=[int(i) for i in input().split()] #canswap=[int(i) for i in input().split()] canswap=input() maxi=l[0] for i in range(0,n-1,): maxi=max(maxi,l[i]) if canswap[i]=='0' and i+1<maxi: print('NO') exit() print('YES') ```
949_A. Zebras
Oleg writes down the history of the days he lived. For each day he decides if it was good or bad. Oleg calls a non-empty sequence of days a zebra, if it starts with a bad day, ends with a bad day, and good and bad days are alternating in it. Let us denote bad days as 0 and good days as 1. Then, for example, sequences o...
```python s = input() o = -1 sol=[] p = True for i in range(0,len(s)): if s[i]=='0': if o == -1: sol.append([i+1]) else: sol[o].append(i+1) o-=1 else: o+=1 if o == len(sol): p = False break else: sol[...
996_D. Suit and Tie
Allen is hosting a formal dinner party. 2n people come to the event in n pairs (couples). After a night of fun, Allen wants to line everyone up for a final picture. The 2n people line up, but Allen doesn't like the ordering. Allen prefers if each pair occupies adjacent positions in the line, as this makes the picture m...
```python def move(a, i, j): f = a[i] for g in range(i, j, -1): a[g] = a[g - 1] a[j] = f n = int(input()) a = list(map(int, input().split())) c = 0 for i in range(0, 2 * n, 2): if a[i] != a[i + 1]: f = a[i + 1:].index(a[i]) + i + 1 move(a, f, i + 1) c += f - i - 1 print(c...
p02779 AtCoder Beginner Contest 154 - Distinct or Not
Given is a sequence of integers A_1, A_2, ..., A_N. If its elements are pairwise distinct, print `YES`; otherwise, print `NO`. Constraints * 2 ≤ N ≤ 200000 * 1 ≤ A_i ≤ 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 ... A_N Output If the elements...
```python #154_C n = int(input()) a = set(input().split()) print('YES' if len(a) == n else 'NO') ```
p02914 AtCoder Beginner Contest 141 - Xor Sum 3
We have N non-negative integers: A_1, A_2, ..., A_N. Consider painting at least one and at most N-1 integers among them in red, and painting the rest in blue. Let the beauty of the painting be the \mbox{XOR} of the integers painted in red, plus the \mbox{XOR} of the integers painted in blue. Find the maximum possibl...
```python n = int(input()) a = list(map(int, input().split())) ans = 0 #even = [] for i in range(60): cnt = 0 for x in a: if (x>>i) & 1: cnt += 1 if cnt%2 == 1: ans += (1<<i) for j in range(n): if (a[j]>>i) & 1: a[j] -= (1<<i) #print(ans, even) yet = 0 for r in range(59, -1, -1): stood = False fo...
p03050 diverta 2019 Programming Contest - DivRem Number
Snuke received a positive integer N from Takahashi. A positive integer m is called a favorite number when the following condition is satisfied: * The quotient and remainder of N divided by m are equal, that is, \lfloor \frac{N}{m} \rfloor = N \bmod m holds. Find all favorite numbers and print the sum of those. Con...
```python n=int(input()) print(sum([n//x-1 for x in range(1,int(n**.5)+1) if n%x==0 and n//x-1>x])) ```
p03338 AtCoder Beginner Contest 098 - Cut and Count
You are given a string S of length N consisting of lowercase English letters. We will cut this string at one position into two strings X and Y. Here, we would like to maximize the number of different letters contained in both X and Y. Find the largest possible number of different letters contained in both X and Y when ...
```python n=int(input()) s=list(input()) ans=0 for i in range(n): ans=max(ans,len(set(s[:i])&set(s[i:]))) print(ans) ```
p03659 AtCoder Beginner Contest 067 - Splitting Pile
Snuke and Raccoon have a heap of N cards. The i-th card from the top has the integer a_i written on it. They will share these cards. First, Snuke will take some number of cards from the top of the heap, then Raccoon will take all the remaining cards. Here, both Snuke and Raccoon have to take at least one card. Let th...
```python n,*a = map(int,open(0).read().split()) total = sum(a) ans = 10**18 dt = 0 for i in range(n-1): dt += a[i] ans = min(ans,abs(total-dt-dt)) print(ans) ```
p03815 AtCoder Beginner Contest 053 - X: Yet Another Die Game
Snuke has decided to play with a six-sided die. Each of its six sides shows an integer 1 through 6, and two numbers on opposite sides always add up to 7. Snuke will first put the die on the table with an arbitrary side facing upward, then repeatedly perform the following operation: * Operation: Rotate the die 90° tow...
```python x=int(input()) print((-(-(2*x-1)//11))) ```
p00072 Carden Lantern
Aizuwakamatsu City is known as the "City of History". About 400 years ago, the skeleton of the castle town was created by Gamo Ujisato, but after that, it became the central city of the Aizu clan 230,000 stones, whose ancestor was Hoshina Masayuki, the half-brother of Tokugawa's third shogun Iemitsu. Developed. Many to...
```python # -*- coding: utf-8 -*- """ http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0072 """ import sys from enum import Enum class Mst(object): """ minimum spanning tree """ INFINITY = 999999999 class Status(Enum): """ ?????????????¨??????¶??? """ white = 1 # ????¨???? ...
p00204 UFO Shooting Down Operation
In 40XX, the Earth was invaded by aliens! Already most of the Earth has been dominated by aliens, leaving Tsuruga Castle Fortress as the only remaining defense base. Suppression units are approaching the Tsuruga Castle Fortress one after another. <image> But hope remains. The ultimate defense force weapon, the ultra...
```python import math class Ufo: def __init__(self, x, y, r, v): self.dist = get_dist(x, y) self.angle = get_angle(y, x) self.rad = r self.v = v def get_dist(x, y): return (x ** 2 + y ** 2) ** (1 / 2) def get_angle(x, y): angle = math.atan2(y, x) if angle < 0: angle += math.pi * 2 retur...
p00360 Swapping Characters
You are given a string and a number k. You are suggested to generate new strings by swapping any adjacent pair of characters in the string up to k times. Write a program to report the lexicographically smallest string among them. Input The input is given in the following format. s k The first line provides a st...
```python import sys def main(): NI = lambda : int(sys.stdin.readline()) SI = lambda : sys.stdin.readline().rstrip() s = SI() n = len(s) k = NI() def conv(x): return ord(x) - ord('a') bit = [0] * (n+1) def bit_add(i): while i <= n: bit[i] += 1 ...
p00571 Art Exhibition
An art exhibition will be held in JOI. At the art exhibition, various works of art from all over the country will be exhibited. N works of art were collected as candidates for the works of art to be exhibited. These works of art are numbered 1, 2, ..., N. Each work of art has a set value called size and value. The siz...
```python N = int(input()) P = [list(map(int, input().split())) for i in range(N)] P.sort() su = 0 S = -P[0][0] ans = -10**19 for a, b in P: S = min(S, su - a) ans = max(ans, su + b - a - S) su += b print(ans) ```
p00718 Numeral System
Prof. Hachioji has devised a new numeral system of integral numbers with four lowercase letters "m", "c", "x", "i" and with eight digits "2", "3", "4", "5", "6", "7", "8", "9". He doesn't use digit "0" nor digit "1" in this system. The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1, respectively, and ...
```python ans_list = [] n = int(input()) def mcxl2digit(s): ans = 0 dig = 1 for i in range(len(s)): if "2" <= s[i] <= "9": dig = int(s[i]) else: if s[i] == "m": key = 1000 elif s[i] == "c": key = 100 elif s[i] =...
p00858 Geometric Map
Your task in this problem is to create a program that finds the shortest path between two given locations on a given street map, which is represented as a collection of line segments on a plane. <image> Figure 4 is an example of a street map, where some line segments represent streets and the others are signs indicat...
```python from heapq import heappush, heappop import sys readline = sys.stdin.readline write = sys.stdout.write def dot3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (bx - ox) + (ay - oy) * (by - oy) def cross3(O, A, B): ox, oy = O; ax, ay = A; bx, by = B return (ax - ox) * (by - oy)...
p01420 Marathon Match
N people run a marathon. There are M resting places on the way. For each resting place, the i-th runner takes a break with probability P_i percent. When the i-th runner takes a break, he gets rest for T_i time. The i-th runner runs at constant speed V_i, and the distance of the marathon is L. You are requested to com...
```python import bisect def nCr(n, r): r = min(r, n-r) numerator = 1 for i in range(n, n-r, -1): numerator *= i denominator = 1 for i in range(r, 1, -1): denominator *= i return numerator // denominator n,m,l=map(int,input().split()) data = [[0 for i in range(m+1)]for i in rang...
p01574 Dial Key
You are a secret agent from the Intelligence Center of Peacemaking Committee. You've just sneaked into a secret laboratory of an evil company, Automated Crime Machines. Your mission is to get a confidential document kept in the laboratory. To reach the document, you need to unlock the door to the safe where it is kept...
```python n,m=map(int,input().split()) for _ in range(m): a=int(input()) while a:n,a=a,n%a print(['No','Yes'][n==1]) ```
p02012 Sum of QQ
You received a card with an integer $S$ and a multiplication table of infinite size. All the elements in the table are integers, and an integer at the $i$-th row from the top and the $j$-th column from the left is $A_{i,j} = i \times j$ ($i,j \geq 1$). The table has infinite size, i.e., the number of the rows and the n...
```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(...