name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p01925 Quiz
quiz You are the director of a quiz show. N people will appear in the quiz show as answerers, each numbered from 1 to N. Questions will be M + 1 questions, and each question is numbered from 1 to M + 1. Questions are given in numerical order, and points are given only to the person who answers correctly first by pres...
```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 = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in ...
p02063 Is Greedy Optimal?
D: Is greed the best? story In Japan, where there are 1, 5, 10, 50, 100, 500 yen coins, it is known that the number of coins can be minimized by using as many coins as possible when paying a certain amount. .. If the amount of coins is different from that of Japan, it is not always possible to minimize it by paying ...
```python A,B=map(int,input().split()) if A>B: A,B=B,A if B%A==0: print(-1) else: for i in range(((B//A+1)*A),B+A*2,A): if i//A < i//B+(i-i//B*B)//A+(i-i//B*B)%A: print(i) break else: print(-1) ```
p02205 Calculation Training
Tashizan Hikizan (Calculation Training) square1001 You gave E869120 two numbers, $ A $ and $ B $, as birthday presents. E869120 You decided to use these two numbers for calculation training. Specifically, E869120 does the following for these numbers exactly $ N $ times: * Replace $ A $ with $ A-B $ on odd-numbered ...
```python N = int(input()) A, B = map(int,input().split()) N = N%12 for k in range(1,N+1): if k%2 == 1: A -= B else: B += A print(A,B) ```
p02359 The Maximum Number of Customers
$N$ persons visited a restaurant. The restaurant is open from 0 to $T$. The $i$-th person entered the restaurant at $l_i$ and left at $r_i$. Find the maximum number of persons during the business hours. Constraints * $ 1 \leq N \leq 10^5 $ * $ 1 \leq T \leq 10^5 $ * $ 0 \leq l_i < r_i \leq T $ Input The input is gi...
```python def main(): n,t = map(int,input().split()) t+=1 T = [0]*t for _ in range(n): l,r = map(int,input().split()) T[l]+=1 T[r]-=1 num = 0 res = 0 for i in range(t): num += T[i] res = max(num,res) print (res) if __name__ == '__main__': main...
1004_B. Sonya and Exhibition
Sonya decided to organize an exhibition of flowers. Since the girl likes only roses and lilies, she decided that only these two kinds of flowers should be in this exhibition. There are n flowers in a row in the exhibition. Sonya can put either a rose or a lily in the i-th position. Thus each of n positions should cont...
```python def calc(s): presum = [0] for ch in s: presum.append(presum[-1]) if ch == '1': presum[-1] += 1 ans = 0 for (l,r) in points: ans += ((r-l+1) - (presum[r] - presum[l-1])) * (presum[r] - presum[l-1]) return ans n, m = list(map(int, input().split())) """ points = [] for _ in range(m)...
1028_B. Unnatural Conditions
Let s(x) be sum of digits in decimal representation of positive integer x. Given two integers n and m, find some positive integers a and b such that * s(a) ≥ n, * s(b) ≥ n, * s(a + b) ≤ m. Input The only line of input contain two integers n and m (1 ≤ n, m ≤ 1129). Output Print two lines, one for decimal...
```python def sum_digit(n): c=0 x=n while x>0: c+=(x%10) x=x//10 return c n,m=map(int,input().split()) r='5' su=5 while su<n: r='4'+r su+=4 r=r[0:len(r)-1] r+='5' t1="" for i in range(len(r)): t1+='5' print(int(t1)) print(int(r)) ```
1046_H. Palindrome Pairs
After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given string whether it's a palindrome or not, but soon she grew tired of this problem, so s...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 11/20/18 After learning a lot about space exploration, a little girl named Ana wants to change the subject. Ana is a girl who loves palindromes (string that can be read the same backwards as forward). She has learned how to check for a given stri...
1070_G. Monsters and Potions
Polycarp is an introvert person. In fact he is so much of an introvert that he plays "Monsters and Potions" board game alone. The board of the game is a row of n cells. The cells are numbered from 1 to n from left to right. There are three types of cells: a cell containing a single monster, a cell containing a single p...
```python import sys n, m = tuple(int(x) for x in sys.stdin.readline().split()) heroes = [] for i in range(m): s, h = tuple(int(x) for x in sys.stdin.readline().split()) heroes.append((s - 1, h, i)) heroes = tuple(sorted(heroes)) a = tuple(int(x) for x in sys.stdin.readline().split()) def move_right(heroes,...
1092_C. Prefixes and Suffixes
Ivan wants to play a game with you. He picked some string s of length n consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from 1 to n-1), but he didn't tell you which strings are prefixes an...
```python def is_suffix(par,child): l=len(child) if par[n-l-1:] == child: return 1 return 0 def is_prefix(par,child): l=len(child) if par[:l] ==child: return 1 return 0 def make(pri_par,sec_par,f,s): ans=[0 for i in range(2*n-2)] ans[f]='P' ans[s]='S' for i in r...
1111_A. Superhero Transformation
We all know that a superhero can transform to certain other superheroes. But not all Superheroes can transform to any other superhero. A superhero with name s can transform to another superhero with name t if s can be made equal to t by changing any vowel in s to any other vowel and any consonant in s to any other cons...
```python import math # n=int(input()) s=input() t=input() c = ['a','e','i','o','u'] if len(s)!=len(t): print("No") exit(0) for i in range(len(s)): if(s[i] in c and not(t[i] in c)): print("No") exit(0) elif(t[i] in c and not (s[i] in c)): print("No") exit(0) print("Yes") ```
1159_D. The minimal unique substring
Let s be some string consisting of symbols "0" or "1". Let's call a string t a substring of string s, if there exists such number 1 ≤ l ≤ |s| - |t| + 1 that t = s_l s_{l+1} … s_{l + |t| - 1}. Let's call a substring t of string s unique, if there exist only one such l. For example, let s = "1010111". A string t = "010...
```python n, k = map(int, input().split()) strr = "" while len(strr) < n: strr += "0" * ((n-k) // 2) + "1" strr = strr[:n] print(strr) ```
1181_D. Irrigation
Misha was interested in water delivery from childhood. That's why his mother sent him to the annual Innovative Olympiad in Irrigation (IOI). Pupils from all Berland compete there demonstrating their skills in watering. It is extremely expensive to host such an olympiad, so after the first n olympiads the organizers int...
```python from bisect import bisect_left as bl import sys N, M, Q = map(int, sys.stdin.readline().split()) count = [0] * (M + 1) A = [] for a in sys.stdin.readline().split(): a = int(a) A.append(count[a] * M + a) count[a] += 1 A.sort() A = [a - i for i, a in enumerate(A, 1)] for _ in range(Q): q = int(...
119_C. Education Reform
Yet another education system reform has been carried out in Berland recently. The innovations are as follows: An academic year now consists of n days. Each day pupils study exactly one of m subjects, besides, each subject is studied for no more than one day. After the lessons of the i-th subject pupils get the home ta...
```python class Subject: def __init__(self, id, low, high, complexity): self.id = id self.low = low self.high = high self.complexity = complexity self.day_links = [ {} for i in range(high - low + 1) ] def add_link(self, link): day = link.day links = self....
1217_A. Creating a Character
You play your favourite game yet another time. You chose the character you didn't play before. It has str points of strength and int points of intelligence. Also, at start, the character has exp free experience points you can invest either in strength or in intelligence (by investing one point you can either raise stre...
```python from sys import stdin input=stdin.readline R=lambda:map(int,input().split()) I=lambda:int(input()) S=lambda:input().rstrip('\n') for _ in range(I()): a,b,c=R() ans=0 l=0;r=c while l<=r: m=(l+r)//2 if a+m>b+(c-m):ans=c-m+1;r=m-1 else:l=m+1 print(ans) ```
1325_F. Ehab's Last Theorem
It's the year 5555. You have a graph, and you want to find a long cycle and a huge independent set, just because you can. But for now, let's just stick with finding either. Given a connected graph with n vertices, you can choose to either: * find an independent set that has exactly ⌈√{n}⌉ vertices. * find a simpl...
```python from collections import deque from sys import stdin import sys from math import ceil sys.setrecursionlimit(3*10**5) n,m = map(int,stdin.readline().split()) rn = ceil(n**0.5) lis = [ [] for i in range(n) ] for i in range(m): u,v = map(int,stdin.readline().split()) u -= 1 v -= 1 lis[u].append(...
1366_E. Two Arrays
You are given two arrays a_1, a_2, ... , a_n and b_1, b_2, ... , b_m. Array b is sorted in ascending order (b_i < b_{i + 1} for each i from 1 to m - 1). You have to divide the array a into m consecutive subarrays so that, for each i from 1 to m, the minimum on the i-th subarray is equal to b_i. Note that each element ...
```python import math n, m = tuple(map(int, input().split())) a = list(map(int, input().split())) b = list(map(int, input().split())) ai = n - 1 bi = m - 1 num_split = [0] * (m - 1) while bi > 0: while a[ai] > b[bi]: ai -= 1 while ai >= 0 and a[ai] >= b[bi]: num_split[bi - 1] += 1 ai -...
1387_B1. Village (Minimum)
This problem is split into two tasks. In this task, you are required to find the minimum possible answer. In the task Village (Maximum) you are required to find the maximum possible answer. Each task is worth 50 points. There are N houses in a certain village. A single villager lives in each of the houses. The houses ...
```python import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self....
1408_E. Avoid Rainbow Cycles
You are given m sets of integers A_1, A_2, …, A_m; elements of these sets are integers between 1 and n, inclusive. There are two arrays of positive integers a_1, a_2, …, a_m and b_1, b_2, …, b_n. In one operation you can delete an element j from the set A_i and pay a_i + b_j coins for that. You can make several (ma...
```python import sys;input=sys.stdin.readline def root(x): if x == p[x]:return x p[x] = y = root(p[x]);return y def unite(x, y): px = root(x); py = root(y) if px == py:return 0 rx = rank[px]; ry = rank[py] if ry < rx:p[py] = px elif rx < ry:p[px] = py else:p[py] = px;rank[px] += 1 re...
1452_C. Two Brackets
You are given a string s, consisting of brackets of two types: '(', ')', '[' and ']'. A string is called a regular bracket sequence (RBS) if it's of one of the following types: * empty string; * '(' + RBS + ')'; * '[' + RBS + ']'; * RBS + RBS. where plus is a concatenation of two strings. In one move...
```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...
1476_A. K-divisible Sum
You are given two integers n and k. You should create an array of n positive integers a_1, a_2, ..., a_n such that the sum (a_1 + a_2 + ... + a_n) is divisible by k and maximum element in a is minimum possible. What is the minimum possible maximum element in a? Input The first line contains a single integer t (1 ≤ ...
```python import sys import math import itertools import functools import collections import operator import fileinput import copy from collections import * ORDA = 97 # a def ii(): return int(input()) def mi(): return map(int, input().split()) def li(): return [int(i) for i in input().split()] def lcm(a, b): return ...
1526_B. I Hate 1111
You are given an integer x. Can you make x by summing up some number of 11, 111, 1111, 11111, …? (You can use any number among them any number of times). For instance, * 33=11+11+11 * 144=111+11+11+11 Input The first line of input contains a single integer t (1 ≤ t ≤ 10000) — the number of testcases. The fi...
```python for i in range(int(input())): n=int(input()) if(n>=111*(n%11)): print("YES") else : print("NO") ```
1_A. Theatre Square
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a. What is the least number of flagstones needed to pave the Square? It'...
```python import math def main(): n, m, a = map(int, input().split()) sq_area = n * m stone_area = a * a if stone_area > sq_area: return 1 return math.ceil(m / a) * math.ceil(n / a) if __name__ == '__main__': print(main()) ```
224_B. Array
You've got an array a, consisting of n integers: a1, a2, ..., an. Your task is to find a minimal by inclusion segment [l, r] (1 ≤ l ≤ r ≤ n) such, that among numbers al, al + 1, ..., ar there are exactly k distinct numbers. Segment [l, r] (1 ≤ l ≤ r ≤ n; l, r are integers) of length m = r - l + 1, satisfying the given...
```python MAX_N = 100005 n, k = map(int, input().split(' ')) a = list(map(int, input().split(' '))) cnt = [0 for i in range(MAX_N)] l = 0 count = 0 for i in range(n): cnt[a[i]] += 1 if cnt[a[i]] == 1: count += 1 if count == k: while l <= i: cnt[a[l]] -= 1 if cnt[a[l]] == 0: print(l + 1, end = ' ') ...
273_A. Dima and Staircase
Dima's got a staircase that consists of n stairs. The first stair is at height a1, the second one is at a2, the last one is at an (1 ≤ a1 ≤ a2 ≤ ... ≤ an). Dima decided to play with the staircase, so he is throwing rectangular boxes at the staircase from above. The i-th box has width wi and height hi. Dima throws eac...
```python n, t, d, p = input(), [0] + list(map(int, input().split())), 0, [] for i in range(int(input())): w, h = map(int, input().split()) p.append(max(d, t[w])) d = p[i] + h print(*p) ```
296_C. Greg and Array
Greg has an array a = a1, a2, ..., an and m operations. Each operation looks as: li, ri, di, (1 ≤ li ≤ ri ≤ n). To apply operation i to the array means to increase all array elements with numbers li, li + 1, ..., ri by value di. Greg wrote down k queries on a piece of paper. Each query has the following form: xi, yi, ...
```python n, m, k = [int(n) for n in input().split()] a = [int(n) for n in input().split()] instructions = [] temp = [] for i in range(n+1): temp.append(0) for i in range(m): instructions.append([int(n) for n in input().split()]) queries = [] for i in range(m+1): queries.append(0) for i in range(k): x, y = [int(n) ...
31_A. Worms Evolution
Professor Vasechkin is studying evolution of worms. Recently he put forward hypotheses that all worms evolve by division. There are n forms of worms. Worms of these forms have lengths a1, a2, ..., an. To prove his theory, professor needs to find 3 different forms that the length of the first form is equal to sum of len...
```python n = int(input()) line = list(map(int,input().split())) for i in range(n-1): for j in range(i+1,n): if line[i] + line[j] in line: print(line.index(line[i] + line[j])+1, i+1, j+1) exit(0) print('-1') ```
344_A. Magnets
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo...
```python s=0 prev='' for i in range(int(input())): kk=input() if kk!=prev: s+=1 prev=kk print(s) ```
367_C. Sereja and the Arrangement of Numbers
Let's call an array consisting of n integer numbers a1, a2, ..., an, beautiful if it has the following property: * consider all pairs of numbers x, y (x ≠ y), such that number x occurs in the array a and number y occurs in the array a; * for each pair x, y must exist some position j (1 ≤ j < n), such that at leas...
```python def readdata(): #fread = open('input.txt', 'r') global n, m, w, q n, m = [int(x) for x in input().split()] q = [0] * m w = [0] * m for i in range(m): q[i], w[i] = [int(x) for x in input().split()] def podg(): global summ w.sort(reverse = True)...
411_A. Password Check
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che...
```python n=input() d=[] sp="!?.,_" for i in n: if len(n)>=5: d.append(1) if i.isupper()==True: d.append(2) if i.islower()==True: d.append(3) if i.isdigit()==True: d.append(4) if i in sp: d.append(5) s=set(d) if s=={1,2,3,4} or s=={1,2,3,4,5}: print("Corre...
460_B. Little Dima and Equation
Little Dima misbehaved during a math lesson a lot and the nasty teacher Mr. Pickles gave him the following problem as a punishment. Find all integer solutions x (0 < x < 109) of the equation: x = b·s(x)a + c, where a, b, c are some predetermined constant values and function s(x) determines the sum of all digits in...
```python a,b,c=map(int,input().split()) L=[] for i in range(1,82): val=b*(i**a)+c check=0 if val>0 and val<10**9: s=str(val) for j in s: check+=int(j) if check==i: L.append(val) if len(L)==0: print(0) else: print(len(L)) print(*L) ```
484_A. Bits
Let's denote as <image> the number of bits set ('1' bits) in the binary representation of the non-negative integer x. You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and <image> is maximum possible. If there are multiple such numbers find the sma...
```python n = int(input()) for i in range(n): l,r=map(int,input().split()) while(l|(l+1)<=r): # or make like max function here . l|=l+1 # or here like equal print(l) ```
508_A. Pasha and Pixels
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant. Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of n row with m pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose an...
```python n,m,k = map(int,input().split()) l = [] for i in range(n+2): l.append([0 for i in range(m+2)]) ans = 0 done = 'no' for i in range(k): x,y = map(int,input().split()) l[x][y] = 1 if done == 'no' and ((l[x][y-1] == 1 and l[x-1][y] == 1 and l[x-1][y-1] == 1) or (l[x][y-1] == 1 and l[x+1][y] == 1 a...
557_B. Pasha and Tea
Pasha decided to invite his friends to a tea party. For that occasion, he has a large teapot with the capacity of w milliliters and 2n tea cups, each cup is for one of Pasha's friends. The i-th cup can hold at most ai milliliters of water. It turned out that among Pasha's friends there are exactly n boys and exactly n...
```python import sys def fastio(): from io import StringIO from atexit import register global input sys.stdin = StringIO(sys.stdin.read()) input = lambda : sys.stdin.readline().rstrip('\r\n') sys.stdout = StringIO() register(lambda : sys.__stdout__.write(sys.stdout.getvalue())) fastio() def...
604_E. Lieges of Legendre
Kevin and Nicky Sun have invented a new game called Lieges of Legendre. In this game, two players take turns modifying the game state with Kevin moving first. Initially, the game is set up so that there are n piles of cows, with the i-th pile containing ai cows. During each player's turn, that player calls upon the pow...
```python G_EVEN = {0:0, 1:1, 2:2} G_ODD = {0:0, 1:1, 2:0, 3:1} def grundy(k, ai): if k % 2: if ai <= 3: return G_ODD[ai] elif ai % 2: return 0 else: p = 0 j = ai while not j & 1: p += 1 j >>= 1 ...
627_A. XOR Equation
Two positive integers a and b have a sum of s and a bitwise XOR of x. How many possible values are there for the ordered pair (a, b)? Input The first line of the input contains two integers s and x (2 ≤ s ≤ 1012, 0 ≤ x ≤ 1012), the sum and bitwise xor of the pair of positive integers, respectively. Output Print a s...
```python R = lambda: map(int, input().split()) s, x = R() if s < x or (s - x) & 1: print(0) exit(0) u, d = (s - x) // 2, x res = 1 while u or d: uu, dd = u & 1, d & 1 if uu and dd: res *= 0 elif uu == 0 and dd == 1: res *= 2 u, d = u >> 1, d >> 1 if s == x: res = max(0, res ...
651_A. Joysticks
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c...
```python import sys input = sys.stdin.readline def inp(): return (int(input())) def inlt(): return (list(map(int, input().split()))) def insr(): s = input() return (list(s[:len(s) - 1])) def invr(): return list((map(int, input().split()))) hash_map = {} def solve(a1, a2): if a1 <= ...
69_D. Dot
Anton and Dasha like to play different games during breaks on checkered paper. By the 11th grade they managed to play all the games of this type and asked Vova the programmer to come up with a new game. Vova suggested to them to play a game under the code name "dot" with the following rules: * On the checkered pape...
```python import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') x, y, n, d = map(int, input().split()) vector = [list(map(int, input().split())) for _ in range(n)] dp = [[-1] * (d * 2 + 1) for _ in range(d * 2 + 1)] for i in range(d * 2 + 1): for j...
721_A. One-dimensional Japanese Crossword
Recently Adaltik discovered japanese crosswords. Japanese crossword is a picture, represented as a table sized a × b squares, and each square is colored white or black. There are integers to the left of the rows and to the top of the columns, encrypting the corresponding row or column. The number of integers represents...
```python n=int(input()) s=input() arr,k=[],0 for i in range(len(s)): if(s[i]=='B'): k+=1 else: if(k>0): arr.append(k) k=0 if(k>0): arr.append(k) print(len(arr)) print(*arr,sep=' ') ```
742_D. Arpa's weak amphitheater and Mehrdad's valuable Hoses
Just to remind, girls in Arpa's land are really nice. Mehrdad wants to invite some Hoses to the palace for a dancing party. Each Hos has some weight wi and some beauty bi. Also each Hos may have some friends. Hoses are divided in some friendship groups. Two Hoses x and y are in the same friendship group if and only if...
```python from sys import stdin, stdout from collections import defaultdict as dd read, write = stdin.readline, stdout.write class DisjointSetUnion: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n def find(self, a): acopy = a wh...
766_A. Mahmoud and Longest Uncommon Subsequence
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem. Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o...
```python def uncommon(a, b): if (a == b): return -1 return max(len(a), len(b)) A = input() B = input() print(uncommon(A, B)) ```
789_E. The Great Mixing
Sasha and Kolya decided to get drunk with Coke, again. This time they have k types of Coke. i-th type is characterised by its carbon dioxide concentration <image>. Today, on the party in honour of Sergiy of Vancouver they decided to prepare a glass of Coke with carbon dioxide concentration <image>. The drink should als...
```python from collections import deque MAX_A = 1000 def main(): n, k = map(int, input().split()) a = set(int(x) - n for x in input().split()) visited = [False] * (2 * MAX_A + 1) visited[n] = True Q = deque() Q.append((n, 0)) result = None while Q: u, l = Q.popleft() ...
810_B. Summer sell-off
Summer holidays! Someone is going on trips, someone is visiting grandparents, but someone is trying to get a part-time job. This summer Noora decided that she wants to earn some money, and took a job in a shop as an assistant. Shop, where Noora is working, has a plan on the following n days. For each day sales manager...
```python def get_line(): return [int(s) for s in input().strip().split()] n, f = get_line() kl = [] for _ in range(n): kl.append(get_line()) def get_extra(k, l): if l <= k: return 0 if l <= 2*k: return l - k return k extras = [get_extra(k, l) for k, l in kl] if f == 0: ext...
856_A. Set Theory
Masha and Grisha like studying sets of positive integers. One day Grisha has written a set A containing n different integers ai on a blackboard. Now he asks Masha to create a set B containing n different integers bj such that all n2 integers that can be obtained by summing up ai and bj for all possible pairs of i and ...
```python from random import randint def solve(): n, a = int(input()), list(map(int, input().split())) bb, ab = set(), set() while True: b = randint(1, 1000000) for i in a: if i + b in ab: break else: bb.add(b) if len(bb) == n: break for i in a: ab.add(b + i) print('YES') print(' '.jo...
883_A. Automatic Door
There is an automatic door at the entrance of a factory. The door works in the following way: * when one or several people come to the door and it is closed, the door immediately opens automatically and all people immediately come inside, * when one or several people come to the door and it is open, all people im...
```python BigNum = 10 ** 20 n, m, a, d = map(int, input().split(' ')) ts = [0] + list(map(int, input().split(' '))) + [BigNum] def empsInRange(l, r): em1 = l // a + 1 em2 = r // a return (em1, min(em2, n)) empDoorGroup = d // a + 1 def moveEmps(emps, last): em1, em2 = emps if em1 > em2: ...
906_A. Shockers
Valentin participates in a show called "Shockers". The rules are quite easy: jury selects one letter which Valentin doesn't know. He should make a small speech, but every time he pronounces a word that contains the selected letter, he receives an electric shock. He can make guesses which letter is selected, but for eac...
```python n = int(input()) alphabet = "abcdefghijklmnopqrstuvwxyz" possible = set(alphabet[i] for i in range(len(alphabet))) i = 0 while i < n: signal, word = input().split() if signal == '!': possible = possible & set(word[j] for j in range(len(word))) elif signal == '.' or (signal == '?' and i != n-1): ...
926_C. Is This a Zebra?
A camera you have accidentally left in a desert has taken an interesting photo. The photo has a resolution of n pixels width, and each column of this photo is all white or all black. Thus, we can represent the photo as a sequence of n zeros and ones, where 0 means that the corresponding column is all white, and 1 means...
```python n = int(input()) a = input().split() for j in range(n): a[j] = int(a[j]) i = 1 last = a[0] count = 1; while (i < n and last == a[i]): i+=1 count+=1 if (i < n): last = a[i] buf = 1 i += 1 flag = 1 while (i < n): if (last == a[i]): buf += 1 else: if (count != buf): flag = 0 break ...
955_A. Feed the cat
After waking up at hh:mm, Andrew realised that he had forgotten to feed his only cat for yet another time (guess why there's only one cat). The cat's current hunger level is H points, moreover each minute without food increases his hunger by D points. At any time Andrew can visit the store where tasty buns are sold (y...
```python h,m = map(int,input().split()) hu,d,c,n = map(int,input().split()) if h >= 20: if hu % n != 0: hu = hu + n-hu%n print((hu*4*c)/(5*n)) else: lhu = hu p = float('inf') if hu % n != 0: hu = hu + n-hu%n p = min(p,hu*c/n) #print(p) hu = lhu+((19-h)*60+(60-m))*d i...
981_C. Useful Decomposition
Ramesses knows a lot about problems involving trees (undirected connected graphs without cycles)! He created a new useful tree decomposition, but he does not know how to construct it, so he asked you for help! The decomposition is the splitting the edges of the tree in some simple paths in such a way that each two pa...
```python n = int(input()) flag = True f = [0] * (n - 1) t = [0] * (n - 1) co = [0] * n for i in range(n - 1): f[i], t[i] = map(int, input().split()) co[f[i] - 1] += 1 co[t[i] - 1] += 1 mid = 0 en = [] for i in range(n): if co[i] == 1: en.append(i + 1) elif co[i] > 2: if mid == 0: ...
p02552 AtCoder Beginner Contest 178 - Not
Given is an integer x that is greater than or equal to 0, and less than or equal to 1. Output 1 if x is equal to 0, or 0 if x is equal to 1. Constraints * 0 \leq x \leq 1 * x is an integer Input Input is given from Standard Input in the following format: x Output Print 1 if x is equal to 0, or 0 if x is equal ...
```python x = int(input()) print(x * -1 + 1) ```
p02683 AtCoder Beginner Contest 167 - Skill Up
Constraints * All values in input are integers. * 1\leq N, M\leq 12 * 1\leq X\leq 10^5 * 1\leq C_i \leq 10^5 * 0\leq A_{i, j} \leq 10^5 Input Input is given from Standard Input in the following format: N M X C_1 A_{1,1} A_{1,2} \cdots A_{1,M} C_2 A_{2,1} A_{2,2} \cdots A_{2,M} \vdots C_N A_{N,1} A_{N,2} \cdots A_{...
```python from itertools import combinations n, m, x = map(int, input().split()) ca = [list(map(int, input().split())) for _ in range(n)] ans = 10**9 for i in range(1,n+1): for j in combinations(ca, i): s = [0]*(m+1) for k in j: for l in range(m+1): s[l] += k[l] if min(s[1:]) >= x: an...
p02811 AtCoder Beginner Contest 150 - 500 Yen Coins
Takahashi has K 500-yen coins. (Yen is the currency of Japan.) If these coins add up to X yen or more, print `Yes`; otherwise, print `No`. Constraints * 1 \leq K \leq 100 * 1 \leq X \leq 10^5 Input Input is given from Standard Input in the following format: K X Output If the coins add up to X yen or more, prin...
```python k,x=map(int,input().split());print('YNeos'[500*k<x::2]) ```
p02948 AtCoder Beginner Contest 137 - Summer Vacation
There are N one-off jobs available. If you take the i-th job and complete it, you will earn the reward of B_i after A_i days from the day you do it. You can take and complete at most one of these jobs in a day. However, you cannot retake a job that you have already done. Find the maximum total reward that you can ea...
```python import heapq N, M = map(int,input().split()) J = [[] for k in range(M+1)] for k in range(N): A, B = map(int,input().split()) if A <= M: J[A].append(B) Q = [] ans = 0 for d in range(1,M+1): for e in J[d]: heapq.heappush(Q,-e) if len(Q) > 0: ans += -heapq.heappop(Q) pri...
p03229 Tenka1 Programmer Beginner Contest - Align
You are given N integers; the i-th of them is A_i. Find the maximum possible sum of the absolute differences between the adjacent elements after arranging these integers in a row in any order you like. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * All values in input are integers. Input Input is given f...
```python N = int(input()) A = sorted([int(input()) for i in range(N)]) if N % 2 == 0: print(2 * (sum(A[N // 2:]) - sum(A[:N // 2])) - (A[N // 2] - A[N // 2 - 1])) else: print(2 * (sum(A[N // 2 + 1:]) - sum(A[:N // 2])) - min(A[N // 2] - A[N // 2 - 1], A[N // 2 + 1] - A[N // 2])) ```
p03377 AtCoder Beginner Contest 094 - Cats and Dogs
There are a total of A + B cats and dogs. Among them, A are known to be cats, but the remaining B are not known to be either cats or dogs. Determine if it is possible that there are exactly X cats among these A + B animals. Constraints * 1 \leq A \leq 100 * 1 \leq B \leq 100 * 1 \leq X \leq 200 * All values in input...
```python a,b,x=map(int,input().split()) print("YES" if a+b-x>=0 and x>=a else "NO") ```
p03544 AtCoder Beginner Contest 079 - Lucas Number
It is November 18 now in Japan. By the way, 11 and 18 are adjacent Lucas numbers. You are given an integer N. Find the N-th Lucas number. Here, the i-th Lucas number L_i is defined as follows: * L_0=2 * L_1=1 * L_i=L_{i-1}+L_{i-2} (i≥2) Constraints * 1≤N≤86 * It is guaranteed that the answer is less than 10^{18}. ...
```python n = int(input()) l = [2, 1] for i in range(n-1): l.append(l[i]+l[i+1]) print(l[-1]) ```
p03698 AtCoder Beginner Contest 063 - Varied
You are given a string S consisting of lowercase English letters. Determine whether all the characters in S are different. Constraints * 2 ≤ |S| ≤ 26, where |S| denotes the length of S. * S consists of lowercase English letters. Input Input is given from Standard Input in the following format: S Output If all ...
```python s=input();print("yneos"[len(set(s))<len(s)::2]) ```
p03853 AtCoder Beginner Contest 049 - Thin
There is an image with a height of H pixels and a width of W pixels. Each of the pixels is represented by either `.` or `*`. The character representing the pixel at the i-th row from the top and the j-th column from the left, is denoted by C_{i,j}. Extend this image vertically so that its height is doubled. That is, p...
```python h,w=map(int,input().split()) for i in range(h): a=input() print('{}\n{}'.format(a,a)) ```
p04020 AtCoder Grand Contest 003 - Simplified mahjong
Snuke has a large collection of cards. Each card has an integer between 1 and N, inclusive, written on it. He has A_i cards with an integer i. Two cards can form a pair if the absolute value of the difference of the integers written on them is at most 1. Snuke wants to create the maximum number of pairs from his card...
```python a = int(input()) count = 0 mod = 0 for i in range(a): b = int(input()) if b == 0: mod = 0 c = b + mod if not c==0: count += c//2 mod = c%2 print(count) ```
p00104 Magical Tiles
There is a magic room in a homestead. The room is paved with H × W tiles. There are five different tiles: * Tile with a east-pointing arrow * Tile with a west-pointing arrow * Tile with a south-pointing arrow * Tile with a north-pointing arrow * Tile with nothing Once a person steps onto a tile which has an arrow, ...
```python while True: h,w = map(int,input().split()) if (h,w) == (0,0): break l = [] for i in range(h): l.append(input()) x,y = 0,0 l1 = [] while True: if (x,y) in l1: print('LOOP') break l1.append((x,y)) pos = l[y][x] if pos == '.': print(x,y) break eli...
p00238 Time to Study
Based on the information of the time when study started and the time when study ended, check whether the total time studied in one day is t or more, and if not, create a program to find the shortage time. Time is one unit per hour, and minutes and seconds are not considered. The time is expressed in 24-hour notation in...
```python import sys f = sys.stdin while True: t = int(f.readline()) if t == 0: break n = int(f.readline()) sf = (map(int, f.readline().split()) for _ in range(n)) rest = t - sum(f - s for s, f in sf) print('OK' if rest <= 0 else rest) ```
p00614 ICPC: Ideal Coin Payment and Change
Taro, a boy who hates any inefficiencies, pays coins so that the number of coins to be returned as change is minimized in order to do smoothly when he buys something. One day, however, he doubt if this way is really efficient. When he pays more number of coins, a clerk consumes longer time to find the total value. May...
```python price = [1, 5, 10, 50, 100, 500] while True: values = list(map(int, input().split())) p, n = values[0], values[1:] ans = 1e100 if p == 0: break p_sum = sum(map(lambda s: s[0] * s[1], zip(price, n))) for change in range(1000): total = p + change pay = [0] * 6 ...
p00890 Test Case Tweaking
You are a judge of a programming contest. You are preparing a dataset for a graph problem to seek for the cost of the minimum cost path. You've generated some random cases, but they are not interesting. You want to produce a dataset whose answer is a desired value such as the number representing this year 2010. So you ...
```python import sys from heapq import heappush, heappop readline = sys.stdin.buffer.readline write = sys.stdout.write def solve(): N, M, C = map(int, readline().split()) if N == M == C == 0: return False G = [[] for i in range(N)] for i in range(M): f, t, c = map(int, readline().split(...
p01293 Whist
Whist is a game played by four players with a standard deck of playing cards. The players seat around a table, namely, in north, east, south, and west. This game is played in a team-play basis: the players seating opposite to each other become a team. In other words, they make two teams we could call the north-south te...
```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 = 998244353 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 i...
p01462 Network Reliability
An undirected graph is given. Each edge of the graph disappears with a constant probability. Calculate the probability with which the remained graph is connected. Input The first line contains three integers N (1 \leq N \leq 14), M (0 \leq M \leq 100) and P (0 \leq P \leq 100), separated by a single space. N is the...
```python from collections import deque import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): N, M, P = map(int, readline().split()) G = [[] for i in range(N)] for i in range(M): u, v = map(int, readline().split()) G[u-1].append(v-1) G[v-1].append(u-1) N1...
p01908 Password
problem AOR Ika wants to create a strong password that consists only of lowercase letters. AOR Ika-chan, who was given an example of $ N $ of dangerous passwords by a friend, decided to create a password that meets all of the following conditions. 1. The length is at least one character. 2. Different from any contigu...
```python # coding:utf-8 # AOJ 2808 RUPC 2017 Password import itertools INF = float('inf') MOD = 10 ** 9 + 7 def inpl(): return list(map(int, input().split())) class RollingHash: def __init__(self, s, base, mod): self.s = s self.length = length = len(s) self.base = base self.mo...
p02189 Min Element
Min Element Given the sequence a_1, a_2, .., a_N. Find the minimum number in this sequence. If the minimum value is in more than one place, answer the one with the lowest number. input N a_1 a_2 ... a_N output Output the smallest i such that a_i is the minimum value in the sequence. Constraint * 1 \ leq N \ ...
```python N = int(input()) a = [int(x) for x in input().split()] print(a.index(min(a)) + 1) ```
p02343 Disjoint Set: Union Find Tree
Write a program which manipulates a disjoint set S = {S1, S2, . . . , Sk}. First of all, the program should read an integer n, then make a disjoint set where each element consists of 0, 1, ... n−1 respectively. Next, the program should read an integer q and manipulate the set for q queries. There are two kinds of que...
```python # class UnionFind: # # def __init__(self,n): # self.roots = range(n) # # def def root(i): if par[i] == i: return i par[i]=root(par[i]) return par[i] def unite(x,y): xr = root(x) yr = root(y) par[yr] = xr def same(x,y): return root(x)==root(y) n,q = ma...
p02476 Remainder of Big Integers
Remainder of Big Integers Given two integers $A$ and $B$, compute the remainder of $\frac{A}{B}$. Input Two integers $A$ and $B$ separated by a space character are given in a line. Output Print the remainder in a line. Constraints * $0 \leq A, B \leq 10^{1000}$ * $B \ne 0$ Sample Input 1 5 8 Sample Output...
```python import math n, m = map(int, input().split()) print(n % m) ```
1020_C. Elections
As you know, majority of students and teachers of Summer Informatics School live in Berland for the most part of the year. Since corruption there is quite widespread, the following story is not uncommon. Elections are coming. You know the number of voters and the number of parties — n and m respectively. For each vote...
```python import sys f=sys.stdin out=sys.stdout n,m=map(int,f.readline().rstrip('\r\n').split()) cos={} cost=[] nvot=[0 for i in range(m+1)] party=[[] for i in range(m+1)] for i in range(n): p,c=map(int,f.readline().rstrip('\r\n').split()) if p!=1: if c in cos: cos[c]+=1 else: cos[c]=1 cost.append(c...
1066_D. Boxes Packing
Maksim has n objects and m boxes, each box has size exactly k. Objects are numbered from 1 to n in order from left to right, the size of the i-th object is a_i. Maksim wants to pack his objects into the boxes and he will pack objects by the following algorithm: he takes one of the empty boxes he has, goes from left to...
```python from sys import stdin input=stdin.readline def check(a,m,mx): t=mx for i in a: if t-i>=0: t-=i else: if m-1>0: m-=1 t=mx-i else: return False return True def f(n,m,mx,a): hi=len(a) lo=0 res=0 while lo<=hi: mid=(lo+hi)//2 if check(a[mid:],m,mx): hi=mid-1 res=n-mid e...
1089_G. Guest Student
Berland State University invites people from all over the world as guest students. You can come to the capital of Berland and study with the best teachers in the country. Berland State University works every day of the week, but classes for guest students are held on the following schedule. You know the sequence of se...
```python t = int(input()) while t: k = int(input()) a = [int(i) for i in input().split()] da = [999] * 8 cnt = sum(a) for i in range(0, 7): if not a[i]: continue tmp_cnt = 0 for j in range(0, 7): x = (i + j) % 7 if not a[x]: ...
1108_B. Divisors of Two Integers
Recently you have received two positive integer numbers x and y. You forgot them, but you remembered a shuffled list containing all divisors of x (including 1 and x) and all divisors of y (including 1 and y). If d is a divisor of both numbers x and y at the same time, there are two occurrences of d in the list. For ex...
```python t=int(input()) lis=list(map(int,input().split())) maxnum=max(lis) lis.remove(maxnum) for x in range (1,maxnum//2+1): if maxnum%x==0: lis.remove(x) maxnum2=max(lis) print("{} {}".format(maxnum,maxnum2)) ```
1178_C. Tiles
Bob is decorating his kitchen, more precisely, the floor. He has found a prime candidate for the tiles he will use. They come in a simple form factor — a square tile that is diagonally split into white and black part as depicted in the figure below. <image> The dimension of this tile is perfect for this kitchen, as h...
```python def powmod(x, k, m): res = 1 s = 1 while s <= k: if k & s: res = res * x % m x = x * x % m s <<= 1 return res m = 998244353 w, h = map(int, input().split()) print(powmod(2, w + h, m)) ```
1196_C. Robot Breakout
n robots have escaped from your laboratory! You have to find them as soon as possible, because these robots are experimental, and their behavior is not tested yet, so they may be really dangerous! Fortunately, even though your robots have escaped, you still have some control over them. First of all, you know the locat...
```python def solve(): n = int(input()) x_d = [-100000, 100000] y_d = [-100000, 100000] robots = [] for i in range(n): robots.append([int(i) for i in input().split(' ')]) for r in robots: x, y, l, u, r, d = r # if l == 0 and r == 0: # if x_d[0] > x or x_d[1] <...
1213_D2. Equalizing by Division (hard version)
The only difference between easy and hard versions is the number of elements in the array. You are given an array a consisting of n integers. In one move you can choose any a_i and divide it by 2 rounding down (in other words, in one move you can set a_i := ⌊(a_i)/(2)⌋). You can perform such an operation any (possibl...
```python from sys import stdin n, k = [int(i) for i in stdin.readline().strip().split()] a = [int(i) for i in stdin.readline().strip().split()] p = [19 * [0] for _ in range(max(a) + 1)] nums = set() for m in a: for i in range(19): p[m >> i][i] += 1 nums.add(m >> i) if (m >> i) == 0: ...
1278_D. Segment Tree
As the name of the task implies, you are asked to do some work with segments and trees. Recall that a tree is a connected undirected graph such that there is exactly one simple path between every pair of its vertices. You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n], l_i < r_i for every i. It is guara...
```python import sys class segmTree(): def __init__(self, size=None, array=None): if array is not None: size = len(array) N = 1 while N < size: N <<= 1 self.N = N self.tree = [0] * (2*self.N) if array is not None: for i in range(si...
1299_A. Anu Has a Function
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative. She would like to r...
```python t=1 import sys input=sys.stdin.readline while t>0: t-=1 n=int(input()) a=[int(x) for x in input().split()] d={} l=[0 for i in range(40)] for i in range(n): u=bin(a[i])[2:] #print(a[i],"0"*(40-len(u))+u) for k in range(len(u)): if u[k]=='1': l[len(u)-k-1]+=1 a.sort(reverse=True) maxi=-1 ...
1321_E. World of Darkraft: Battle for Azathoth
Roma is playing a new expansion for his favorite game World of Darkraft. He made a new character and is going for his first grind. Roma has a choice to buy exactly one of n different weapons and exactly one of m different armor sets. Weapon i has attack modifier a_i and is worth ca_i coins, and armor set j has defense...
```python # quick input by @c1729 and @pajenegod import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from bisect import bisect_right from operator import itemgetter class SegmTree: ''' - increment on interval - get max on interval ''' def __init__(self, size): N = 1 ...
1362_D. Johnny and Contribution
Today Johnny wants to increase his contribution. His plan assumes writing n blogs. One blog covers one topic, but one topic can be covered by many blogs. Moreover, some blogs have references to each other. Each pair of blogs that are connected by a reference has to cover different topics because otherwise, the readers ...
```python import sys try: sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') except: pass input = lambda: sys.stdin.buffer.readline().rstrip() n,m=map(int,input().split()) g=[[] for i in range(n)] for i in range(m): q,w=map(int,input().split()) g[q-1].append(w-1) g[w-1].append(q-1) a=list...
1382_E. Mastermind
In the game of Mastermind, there are two players — Alice and Bob. Alice has a secret code, which Bob tries to guess. Here, a code is defined as a sequence of n colors. There are exactly n+1 colors in the entire universe, numbered from 1 to n+1 inclusive. When Bob guesses a code, Alice tells him some information about ...
```python from collections import defaultdict from heapq import heapify, heappop, heappush def solve(): n, s, y = map(int, input().split()) a = input().split() d = defaultdict(list) for i, x in enumerate(a): d[x].append(i) for i in range(1, n + 2): e = str(i) if e not in d: ...
1425_E. Excitation of Atoms
Mr. Chanek is currently participating in a science fair that is popular in town. He finds an exciting puzzle in the fair and wants to solve it. There are N atoms numbered from 1 to N. These atoms are especially quirky. Initially, each atom is in normal state. Each atom can be in an excited. Exciting atom i requires D_...
```python n, k = map(int, input().split()) a = list(map(int, input().split())) d = list(map(int, input().split())) pref=[0] for i in range(n): pref.append(pref[-1]+a[i]) if k==0: ans=0 for i in range(1,n+1): ans=max(ans,pref[-1]-pref[i-1]-d[i-1]) print(ans) elif k == 1: best = sum(a[:n-1]) ...
1447_C. Knapsack
You have a knapsack with the capacity of W. There are also n items, the i-th one has weight w_i. You want to put some of these items into the knapsack in such a way that their total weight C is at least half of its size, but (obviously) does not exceed it. Formally, C should satisfy: ⌈ W/2⌉ ≤ C ≤ W. Output the list...
```python t=int(input()) for h in range(t): n,w=map(int,input().split()) Wt=w arr=[int(x) for x in input().split()] arr3=[ [arr[i],i+1] for i in range(n)] arr3.sort(key= lambda x:x[0],reverse=True) ans=[] sumi=0 for i in range(n): if arr3[i][0] <= w: w-=arr3[i][...
1472_C. Long Jumps
Polycarp found under the Christmas tree an array a of n elements and instructions for playing with it: * At first, choose index i (1 ≤ i ≤ n) — starting position in the array. Put the chip at the index i (on the value a_i). * While i ≤ n, add a_i to your score and move the chip a_i positions to the right (i.e. r...
```python for _ in range(int(input())): n = int(input()) array = list(map(int, input().split())) for i in range(n-1, -1, -1): if i+array[i]<=n-1: array[i] += array[i+array[i]] print(max(array)) ```
1498_D. Bananas in a Microwave
You have a malfunctioning microwave in which you want to put some bananas. You have n time-steps before the microwave stops working completely. At each time-step, it displays a new operation. Let k be the number of bananas in the microwave currently. Initially, k = 0. In the i-th operation, you are given three paramet...
```python #!/usr/bin/env python from __future__ import division, print_function import math import os import sys from io import BytesIO, IOBase if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip BASE = int(10**5) def main(): ...
1520_C. Not Adjacent Matrix
We will consider the numbers a and b as adjacent if they differ by exactly one, that is, |a-b|=1. We will consider cells of a square matrix n × n as adjacent if they have a common side, that is, for cell (r, c) cells (r, c-1), (r, c+1), (r-1, c) and (r+1, c) are adjacent to it. For a given number n, construct a squar...
```python '''Author- Akshit Monga''' from sys import stdin, stdout input = stdin.readline t = int(input()) for _ in range(t): n=int(input()) mat=[[-1 for i in range(n)] for j in range(n)] k=1 for i in range(n): for j in range(n): mat[i][j]=k k+=2 if k>n*n: ...
154_A. Hometask
Sergey attends lessons of the N-ish language. Each lesson he receives a hometask. This time the task is to translate some sentence to the N-ish language. Sentences of the N-ish language can be represented as strings consisting of lowercase Latin letters without spaces or punctuation marks. Sergey totally forgot about ...
```python ans = 0 t = [] x = input() y = int(input()) for i in range(y): z = input() t.append(z) #x = codeforces #y = 2 #t = [do, cs] pt = -1 ln = len(x) for i in t: a = i[0] b = i[1] pt = 0 for j in range(ln): ded1=0 ded2=0 if j >= pt: if x[j] in [a,b]: ...
196_A. Lexicographically Maximum Subsequence
You've got string s, consisting of only lowercase English letters. Find its lexicographically maximum subsequence. We'll call a non-empty string s[p1p2... pk] = sp1sp2... spk(1 ≤ p1 < p2 < ... < pk ≤ |s|) a subsequence of string s = s1s2... s|s|. String x = x1x2... x|x| is lexicographically larger than string y = y1y...
```python s = input() n = len(s) temp = list(set(s)) x = {} temp = sorted(temp,reverse=True) i = 0 while(i < n ): x[s[i]] = i i +=1 string = "" i = 0 j = 0 while(i< n and j < len(temp)): if i <= x[temp[j]]: if s[i]== temp[j]: string += temp[j] if i== x[temp[j]]: j += 1 ...
21_A. Jabber ID
Jabber ID on the national Berland service «Babber» has a form <username>@<hostname>[/resource], where * <username> — is a sequence of Latin letters (lowercase or uppercase), digits or underscores characters «_», the length of <username> is between 1 and 16, inclusive. * <hostname> — is a sequence of word separat...
```python s = input() if s.count('@') != 1 or s.count('/') > 1: print('NO') exit() p1 = s.find('@') p2 = s.find('/') if p2 == -1: p2 = len(s) import re u = re.compile('(\w){1,16}$') h = re.compile('(\w{1,16}\.)*\w{1,16}$') k1 = h.match(s[p1 + 1 : p2]) k2 = u.match(s[0:p1]) k3 = u.match(s[p2 + 1 : len(s)]) if le...
269_A. Magical Boxes
Emuskald is a well-known illusionist. One of his trademark tricks involves a set of magical boxes. The essence of the trick is in packing the boxes inside other boxes. From the top view each magical box looks like a square with side length equal to 2k (k is an integer, k ≥ 0) units. A magical box v can be put inside a...
```python from math import * n = int(input()) mx = 0 for i in range(n): k, a = map(int, input().split()) mx = max(mx, 2*k + log2(a)) mx = max(mx, 2*(k+1)) print(int(ceil(mx/2))) ```
291_C. Network Mask
The problem uses a simplified TCP/IP address model, please make sure you've read the statement attentively. Polycarpus has found a job, he is a system administrator. One day he came across n IP addresses. Each IP address is a 32 bit number, represented as a group of four 8-bit numbers (without leading zeroes), separat...
```python def f(t): a, b, c, d = map(int, t.split('.')) return d + (c << 8) + (b << 16) + (a << 24) def g(x): p = [0] * 4 for i in range(4): p[3 - i] = str(x % 256) x //= 256 return '.'.join(p) n, k = map(int, input().split()) t = [f(input()) for i in range(n)] p = [0] * n x = 1 <<...
316_D3. PE Lesson
Smart Beaver decided to be not only smart, but also a healthy beaver! And so he began to attend physical education classes at school X. In this school, physical education has a very creative teacher. One of his favorite warm-up exercises is throwing balls. Students line up. Each one gets a single ball in the beginning....
```python m = 1000000007 n = int(input()) a = map(int, input().split()) t1, t2 = 0, 0 for i in a: if i == 1: t1 += 1 else: t2 += 1 a = [1, 2] for i in range(3, t1+1): a = a[::-1] a[1] = (a[0]+(i-1)*a[1])%m if not t1 or t1 == 1: a[1] = 1 for i in range(t1+1, n+1): a[1] = a[1]*i%m print(a[1]) ```
33_A. What is for dinner?
In one little known, but very beautiful country called Waterland, lives a lovely shark Valerie. Like all the sharks, she has several rows of teeth, and feeds on crucians. One of Valerie's distinguishing features is that while eating one crucian she uses only one row of her teeth, the rest of the teeth are "relaxing". ...
```python n, m, k = list(map(int,input().split())) tooth = [[0,True]] * n for i in range(n): r, c = list(map(int,input().split())) if tooth[r-1][0] > c or tooth[r-1][1] == True: tooth[r-1] = [c,False] ad = 0 for i in tooth: ad += i[0] print(min(ad,k)) ```
362_C. Insertion Sort
Petya is a beginner programmer. He has already mastered the basics of the C++ language and moved on to learning algorithms. The first algorithm he encountered was insertion sort. Petya has already written the code that implements this algorithm and sorts the given integer zero-indexed array a of size n in the non-decre...
```python arr = [0 for i in range(5001)] def insertion_sort(n, a): def modify(t): while t > 0: arr[t] += 1 t -= t & (-t) def query(t): res = 0 while t < 5001: res += arr[t] t += t & (-t) return res s = 0 ans = 0 way ...
386_A. Second-Price Auction
In this problem we consider a special type of an auction, which is called the second-price auction. As in regular auction n bidders place a bid which is price a bidder ready to pay. The auction is closed, that is, each bidder secretly informs the organizer of the auction price he is willing to pay. After that, the auct...
```python a=int(input()) a=list(map(int,input().split())) ind=a.index(max(a)) a.sort() print(str(ind+1)+' '+str(a[-2])) ```
434_A. Ryouko's Memory Note
Ryouko is an extremely forgetful girl, she could even forget something that has just happened. So in order to remember, she takes a notebook with her, called Ryouko's Memory Note. She writes what she sees and what she hears on the notebook, and the notebook became her memory. Though Ryouko is forgetful, she is also bo...
```python def median(a): if len(a) == 0: return 0 if len(a) % 2 == 1: return a[len(a) // 2] else: return (a[len(a) // 2] + a[(len(a) // 2) - 1]) // 2 def profit(a, old_val): a.sort() med = median(a) sum_old = 0 sum_new = 0 for i in a: sum_old += abs(i - ...
456_C. 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 #!/usr/bin/env python3 # -*- coding: utf-8 -*- s=0 n = int(input()) dp=[0]*(10**5+1) sec = [int(x) for x in input().split()] ls = [0]*(10**5+1) for x in sec: ls[x]+=1 dp[1]=ls[1] for i in range(2,10**5+1): dp[i]=max(dp[i-1],dp[i-2]+ls[i]*i) print(dp[10**5]) ```
479_A. Expression
Petya studies in a school and he adores Maths. His class has been studying arithmetic expressions. On the last class the teacher wrote three positive integers a, b, c on the blackboard. The task was to insert signs of operations '+' and '*', and probably brackets between the numbers so that the value of the resulting e...
```python a1 = int(input()) a2 = int(input()) a3 = int(input()) listValue = [a1*a2*a3, a1*(a2+a3), a1*a2+a3, a1+a2*a3, (a1+a2)*a3, a1+a2+a3] maxValue = listValue[0] for x in listValue: if x > maxValue: maxValue = x print(maxValue) ```
501_A. Contest
Misha and Vasya participated in a Codeforces contest. Unfortunately, each of them solved only one problem, though successfully submitted it at the first attempt. Misha solved the problem that costs a points and Vasya solved the problem that costs b points. Besides, Misha submitted the problem c minutes after the contes...
```python a,b,c,d=map(int,input().split()) x=max((3*a//10),(a-(a//250*c))) y=max((3*b//10),(b-((b//250)*d))) # print(x,y) if y>x: print('Vasya') elif x>y: print('Misha') else: print('Tie') ```
552_B. Vanya and Books
Vanya got an important task — he should enumerate books in the library and label each book with its number. Each of the n books should be assigned with a number from 1 to n. Naturally, distinct books should be assigned distinct numbers. Vanya wants to know how many digits he will have to write down as he labels the bo...
```python n = input() s = len(n) ''' 9 - 1 1 1 1 1 1 1 1 1 90 - 11 11 11 11 11 11 11 11 11 11 ... 11 11 900 - 111 111 111 111 111 111 111 ... 111 111 9000 - 1111 1111 1111 ... 1111 1111 ''' q = 0 if s > 2: for c in range(s-1): v = int('9' + c*'0') q += v*(c+1) k = int(n) - (int('1' + (s-1)*'0') - 1) q...
579_B. Finding Team Member
There is a programing contest named SnakeUp, 2n people want to compete for it. In order to attend this contest, people need to form teams of exactly two people. You are given the strength of each possible combination of two people. All the values of the strengths are distinct. Every contestant hopes that he can find a...
```python def main(): mode="filee" if mode=="file":f=open("test.txt","r") if mode=="file":n=int(f.readline()) else:n=int(input()) w=[] for i in range(2,2*n+1): if mode=="file":g=[int(x) for x in f.readline().split()] else:g=[int(x) for x in input().split()] for j in rang...