name
stringlengths
9
112
description
stringlengths
29
13k
solutions
stringlengths
24
49.8k
p02770 AtCoder Beginner Contest 156 - Modularness
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}. Process the following q queries in order: * The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mo...
```python #!usr/bin/env python3 from collections import defaultdict,deque from heapq import heappush, heappop from itertools import permutations import sys import math import bisect 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 i...
p02905 AtCoder Grand Contest 038 - LCMs
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}. Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b): * \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j) Since the answer may be enormous, compute it modulo 998244353. Constraints * 1 \leq N \leq 200000 ...
```python N=int(input());A=list(map(int, input().split()));z=[0]*(max(A)+1);m=998244353;r=0 for a in A:z[a]+=a for i in range(1,len(z)): for j in range(2*i,len(z),i):z[i]+=z[j] for i in range(1,len(z)):z[i]*=z[i] for i in range(len(z)-1,0,-1): for j in range(2*i,len(z),i):z[i]-=z[j] for a in A:z[a]-=a**2 for i in r...
p03040 AtCoder Beginner Contest 127 - Absolute Minima
There is a function f(x), which is initially a constant function f(x) = 0. We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows: * An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x). ...
```python import heapq import sys # from matplotlib import pyplot as plt sys.setrecursionlimit(10000) INF = float('inf') Q = int(next(sys.stdin)) # def plot(fn): # x = np.arange(-10, 10, 1) # y = np.array([fn(xa) for xa in x]) # plt.plot(x, y) # plt.grid() # plt.show() # # # def g(fn, a, b): # ...
p03181 Educational DP Contest - Subtree
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i. Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices. You are given a p...
```python import sys from collections import deque stdin = sys.stdin def ni(): return int(ns()) def na(): return list(map(int, stdin.readline().split())) def naa(N): return [na() for _ in range(N)] def ns(): return stdin.readline().rstrip() # ignore trailing spaces def make_tree_0index(N): edge_dic = {} ...
p03329 AtCoder Beginner Contest 099 - Strange Bank
To make it difficult to withdraw money, a certain bank allows its customers to withdraw only one of the following amounts in one operation: * 1 yen (the currency of Japan) * 6 yen, 6^2(=36) yen, 6^3(=216) yen, ... * 9 yen, 9^2(=81) yen, 9^3(=729) yen, ... At least how many operations are required to withdraw exa...
```python n = int(input()) dp = [10**6]*(n+1) dp[0] = 0 l = [1, 6, 36, 216, 1296, 7776, 46656, 9, 81, 729, 6561, 59049] for i in range(1, n+1): for j in l: if i >= j: dp[i] = min(dp[i-j]+1, dp[i]) print(dp[-1]) ```
p03486 AtCoder Beginner Contest 082 - Two Anagrams
You are given strings s and t, consisting of lowercase English letters. You will create a string s' by freely rearranging the characters in s. You will also create a string t' by freely rearranging the characters in t. Determine whether it is possible to satisfy s' < t' for the lexicographic order. Constraints * The ...
```python s=sorted(list(input())) t=sorted(list(input()))[::-1] print('Yes') if s<t else print('No') ```
p03650 AtCoder Regular Contest 079 - Namori Grundy
There is a directed graph with N vertices and N edges. The vertices are numbered 1, 2, ..., N. The graph has the following N edges: (p_1, 1), (p_2, 2), ..., (p_N, N), and the graph is weakly connected. Here, an edge from Vertex u to Vertex v is denoted by (u, v), and a weakly connected graph is a graph which would be ...
```python import sys sys.setrecursionlimit(10**6) n = int(input()) p = list(map(int, input().split())) c = [[] for _ in range(n)] is_leaf = [True for _ in range(n)] for i in range(n): p[i] -= 1 c[p[i]].append(i) is_leaf[p[i]] = False if sum(is_leaf) == 0: if n%2 == 0: print("POSSIBLE") else: print("IMPOSSIBLE...
p03806 AtCoder Beginner Contest 054 - Mixing Experiment
Dolphin is planning to generate a small amount of a certain chemical substance C. In order to generate the substance C, he must prepare a solution which is a mixture of two substances A and B in the ratio of M_a:M_b. He does not have any stock of chemicals, however, so he will purchase some chemicals at a local pharmac...
```python #!python3 import copy LI = lambda: list(map(int, input().split())) # input N, Ma, Mb = LI() ABC = [LI() for _ in range(N)] INF = 10 ** 5 def main(): w = [[INF] * 401 for _ in range(401)] w[0][0] = 0 for a, b, c in ABC: l = copy.deepcopy(w) for j in range(a, 401): ...
p03974 CODE FESTIVAL 2016 qual B - Lexicographical disorder
There are N strings of lowercase alphabet only. The i-th string is S_i. Every string is unique. Provide answers for the Q queries below. The i-th query has the following format: Query: An integer k_i and a string p_{i,1}p_{i,2}...p_{i,26} that results from permuting {`a`,`b`,...,`z`} are given. Output the sequence of...
```python import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from collections import defaultdict """ ・trie木 ・各ノードから、アルファベットごとの子ノードの番号 ・親ノードの番号 """ N = int(readline()) data = tuple(read().split()) S = data[:N] Q = int(data[N]) query_target = list(map(in...
p00063 Palindrome
There is data of up to 100 characters per line, consisting of half-width alphabetic character strings. Some lines are symmetric (same whether read from the left edge or the right edge). Create a program that reads this data and outputs the number of symmetric strings in it. Note that lines consisting of only one charac...
```python # coding: utf-8 # Your code here! n = 0 while True: try: t = str(input()) if t == t[::-1]: n += 1 except EOFError: break print(n) ```
p00195 What is the Most Popular Shop in Tokaichi?
In Aizuwakamatsu City, there is a first city called "Tokaichi" on January 10th every year. This Tokaichi has a history of about 600 years and is the largest first city in the Aizu region. It is also well known that Okiagari-koboshi, a familiar lucky charm, is sold in the Aizu region. Okiagari-koboshi is a papier-mâché ...
```python while True: try: n = [[0,"A"],[0,"B"],[0,"C"],[0,"D"],[0,"E"]] for i in range(5): n[i][0] = sum(list(map(int,input().split()))) n.sort(reverse = True) print(n[0][1],n[0][0]) except: break ```
p00545 Walking in JOI Kingdom
problem The JOI country has one long enough road running east to west. The royal palace of JOI country is along the road, and the position along the road in JOI country is represented by the integer A. When A = 0, it represents the position of the royal palace. When A> 0, it indicates the position A meters east of the...
```python import sys readline = sys.stdin.readline write = sys.stdout.write N, T, Q = map(int, readline().split()) P = [list(map(int, readline().split())) for i in range(N)] QS = [P[int(readline())-1] for i in range(Q)] prv = 1 R = {} A = []; B = [] for x, t in P: if prv == t: if t == 1: A.appe...
p00709 Square Carpets
Mr. Frugal bought a new house. He feels deeply in love with his new house because it has a comfortable living room in which he can put himself completely at ease. He thinks his new house is a really good buy. But, to his disappointment, the floor of its living room has some scratches on it. The floor has a rectangle ...
```python def solve(): from itertools import combinations from sys import stdin file_input = stdin while True: W, H = map(int, file_input.readline().split()) if W == 0: break carpets = [] state = 0 # Largest Square algorithm ...
p00848 Sum of Different Primes
A positive integer may be expressed as a sum of different prime numbers (primes), in one way or another. Given two positive integers n and k, you should count the number of ways to express n as a sum of k different primes. Here, two ways are considered to be the same if they sum up the same set of the primes. For examp...
```python primes = [] flag = [0 for i in range(1121)] for i in range(2, 1121): if flag[i] == 0: primes.append(i) count = 2 while i * count < 1121: flag[i * count] = 1 count += 1 dp = [[0 for i in range(15)] for j in range(1121)] dp[0][0] = 1 for p in primes: for k in range(13,...
p00980 Estimating the Flood Risk
Estimating the Flood Risk Mr. Boat is the owner of a vast extent of land. As many typhoons have struck Japan this year, he became concerned of flood risk of his estate and he wants to know the average altitude of his land. The land is too vast to measure the altitude at many spots. As no steep slopes are in the estate...
```python #!/usr/bin/python3 import os import sys def main(): W, D, N = read_ints() M = [tuple(read_ints()) for _ in range(N)] ans = solve(W, D, N, M) if ans is None: print('No') else: print(ans) def solve(W, D, N, M): INF = 999 H = [[INF] * W for _ in range(D)] hma...
p01112 Playoff by all the teams
Playoff by all the teams The Minato Mirai Football Association hosts its annual championship as a single round-robin tournament, in which each team plays a single match against all the others. Unlike many other round-robin tournaments of football, matches never result in a draw in this tournament. When the regular tim...
```python from itertools import combinations as comb def main(): while True: n = int(input()) if n ==0:break m = int(input()) result = [[None] * n for _ in range(n)] for _ in range(m): x, y = map(int, input().split()) x -= 1 y -= 1 result[x][y] = True result[y][x] = ...
p01250 Pi is Three
π (spelled pi in English) is a mathematical constant representing the circumference of a circle whose di- ameter is one unit length. The name π is said to come from the first letter of the Greek words περιφέρεια (meaning periphery) and περίμετρος (perimeter). Recently, the government of some country decided to allow u...
```python from math import pi while 1: r=float(input()) if r==0:break n=d=1 while abs(n/d-pi)>r: if n/d<pi:n+=1 else: d+=1 print('%d/%d'%(n,d)) ```
p01411 Entangled with Lottery
Training is indispensable for achieving good results at ICPC. Rabbit wants to win at ICPC, so he decided to practice today as well. Today's training is to use the Amidakuji to improve luck by gaining the ability to read the future. Of course, not only relying on intuition, but also detailed probability calculation is ...
```python import sys readline = sys.stdin.readline write = sys.stdout.write def solve(): H, N, P, M, K = map(int, readline().split()) A = [0]*H for i in range(M): a, b = map(int, readline().split()) A[a-1] = b S = [[0]*N for i in range(K+1)] S[0][P-1] = 1 T = [[0]*N for i in ra...
p01865 Steelyard
Problem statement Jota made a scale as shown in the figure below using a stick with a length of $ 2L $. <image> The rods are evenly spaced with $ 2L + 1 $ holes, from left to right: $ -L, -L + 1, \ cdots, -1, 0, 1, \ cdots, L-1, L $. It is numbered. And the place of the hole of No. $ 0 $ is hung from the ceiling wit...
```python #!/usr/bin/env python3 # -*- coding: utf-8 -*- def solve(l, n, jota_weights): jota_torque = sum(x * w for x, w in jota_weights) if jota_torque == 0: return (0, []) else: max_w = 50000 sign = -1 if jota_torque > 0 else 1 ritsuko_weights = [] ritsuko_counter...
p02287 Complete Binary Tree
A complete binary tree is a binary tree in which every internal node has two children and all leaves have the same depth. A binary tree in which if last level is not completely filled but all nodes (leaves) are pushed across to the left, is also (nearly) a complete binary tree. A binary heap data structure is an array...
```python k,e=' key = ',', ' input() A=[0]+input().split() H=len(A) for i in range(1,H): print(f'node {i}: key = {A[i]}, {"parent"+k+A[i//2]+e if i>1 else""}{"left"+k+A[2*i]+e if 2*i<H else""}{"right"+k+A[2*i+1]+e if 2*i+1<H else""}') ```
p02434 Vector II
For $n$ dynamic arrays $A_i$ ($i = 0, 1, ..., n-1$), perform a sequence of the following operations: * pushBack($t$, $x$): Add element $x$ at the end of $A_t$. * dump($t$): Print all elements in $A_t$. * clear($t$): Clear $A_t$. If $A_t$ is empty, do nothing. $A_i$ is a 0-origin array and it is empty in the initial...
```python class Vector(): def __init__(self, num_vector): self.vector = [[] for i in range(0, num_vector)] def pushBack(self, t, x): self.vector[t].append(x) return self def dump(self, t): print(' '.join(map(str, self.vector[t]))) return self def clear(self, t)...
1012_C. Hills
Welcome to Innopolis city. Throughout the whole year, Innopolis citizens suffer from everlasting city construction. From the window in your room, you see the sequence of n hills, where i-th of them has height ai. The Innopolis administration wants to build some houses on the hills. However, for the sake of city appea...
```python ''' Hey stalker :) ''' INF = 10**10 def main(): #print = out.append ''' Cook your dish here! ''' n = get_int() li = get_list() high = [] high_li = [] for i in range(n): th = high[:] thli = high_li[:] for j in range((i)//2 + 1): k = 0 ...
1037_C. Equalize
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a: * Swap any two bits at indices i and j respectively (1 ≤ i, j ≤ n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. * Select any arbitrary index i (1 ...
```python def solve(n, a, b): ans = 0 i = 0 while i < n: if a[i] != b[i]: if i < n-1 and a[i+1] != b[i+1] and a[i+1] != a[i]: ans += 1 i += 2 else: ans += 1 i += 1 else: i += 1 return ans ...
1081_E. Missing Numbers
Chouti is working on a strange math problem. There was a sequence of n positive integers x_1, x_2, …, x_n, where n is even. The sequence was very special, namely for every integer t from 1 to n, x_1+x_2+...+x_t is a square of some integer number (that is, a [perfect square](https://en.wikipedia.org/wiki/Square_number)...
```python # ---------------------------iye ha aam zindegi--------------------------------------------- import math import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup------------------------...
1100_E. Andrew and Taxi
Andrew prefers taxi to other means of transport, but recently most taxi drivers have been acting inappropriately. In order to earn more money, taxi drivers started to drive in circles. Roads in Andrew's city are one-way, and people are not necessary able to travel from one part to another, but it pales in comparison to...
```python import sys from operator import itemgetter readline = sys.stdin.readline def topological_sort(E, D): D = D[:] n = len(E) Q = [i for i in range(n) if D[i] == 0] L = [] while Q: p = Q.pop() L.append(p) for vf in E[p]: D[vf] -= 1 if not D[vf]: ...
1129_B. Wrong Answer
Consider the following problem: given an array a containing n integers (indexed from 0 to n-1), find max_{0 ≤ l ≤ r ≤ n-1} ∑_{l ≤ i ≤ r} (r-l+1) ⋅ a_i. In this problem, 1 ≤ n ≤ 2 000 and |a_i| ≤ 10^6. In an attempt to solve the problem described, Alice quickly came up with a blazing-fast greedy algorithm and coded it....
```python def compute(): from sys import stdin [k] = list(map(int, stdin.readline().split())) MAXX = 1000000 MAXN = 2000 o = [-1] k += 1 while k>0: k += 1 if k > MAXX: tosub = MAXX else: tosub = k o.append(tosub) k -= tosu...
1189_B. Number Circle
You are given n numbers a_1, a_2, …, a_n. Is it possible to arrange them in a circle in such a way that every number is strictly less than the sum of its neighbors? For example, for the array [1, 4, 5, 6, 7, 8], the arrangement on the left is valid, while arrangement on the right is not, as 5≥ 4 + 1 and 8> 1 + 6. <im...
```python n = int(input()) arr = list(map(int, input().split())) arr.sort() if arr[-1] >= arr[-2] + arr[-3]: print("NO") else: print("YES") tmp = arr[-1] arr[-1] = arr[-2] arr[-2] = tmp print(' '.join([str(x) for x in arr])) ```
1208_B. Uniqueness
You are given an array a_{1}, a_{2}, …, a_{n}. You can remove at most one subsegment from it. The remaining elements should be pairwise distinct. In other words, at most one time you can choose two integers l and r (1 ≤ l ≤ r ≤ n) and delete integers a_l, a_{l+1}, …, a_r from the array. Remaining elements should be pa...
```python '''input 4 1 1 2 2 ''' from sys import stdin from copy import deepcopy def get_dict(arr, n): mydict = dict() for i in range(n): if arr[i] in mydict: mydict[arr[i]] += 1 else: mydict[arr[i]] = 1 more = 0 for i in mydict: if mydict[i] > 1: more += 1 return more, mydict # main starts n =...
1227_B. Box
Permutation p is a sequence of integers p=[p_1, p_2, ..., p_n], consisting of n distinct (unique) positive integers between 1 and n, inclusive. For example, the following sequences are permutations: [3, 4, 1, 2], [1], [1, 2]. The following sequences are not permutations: [0], [1, 2, 1], [2, 3], [0, 1, 2]. The importan...
```python t = int(input()) for _ in range(t): n = int(input()) l = list(map(int,input().split())) arr = [0 for j in range(n)] pos = 0 arr[l[0]-1] = 1 final = [l[0]] flag = 0 for j in range(1,n): if(l[j]!=l[j-1]): arr[l[j]-1] = 1 final.append(l[j]) ...
1269_C. Long Beautiful Integer
You are given an integer x of n digits a_1, a_2, …, a_n, which make up its decimal notation in order from left to right. Also, you are given a positive integer k < n. Let's call integer b_1, b_2, …, b_m beautiful if b_i = b_{i+k} for each i, such that 1 ≤ i ≤ m - k. You need to find the smallest beautiful integer y,...
```python import copy n,k = map(int, input().split()) li = list(map(int, input())) copyli = copy.copy(li) for y in range(k): for x in range(y,n,k): li[x] = li[y] print(n) if copyli > li : pos = k-1 while li[pos] == 9 and pos>0 : pos = pos-1 ele = li[pos]+1 for x in range(pos,n,k)...
1291_C. Mind Control
You and your n - 1 friends have found an array of integers a_1, a_2, ..., a_n. You have decided to share it in the following way: All n of you stand in a line in a particular order. Each minute, the person at the front of the line chooses either the first or the last element of the array, removes it, and keeps it for h...
```python t = int(input()) for _ in range(t): n, m, k = tuple(map(int, input().split())) l = list(map(int, input().split())) M = max(l) k = min(k, m-1) realp = m-k-1 ma = -1 for i in range(k+1): tmp = M for j in range(realp+1): tmp = min(tmp, max(l[i+j], l[i+j + ...
1311_D. Three Integers
You are given three integers a ≤ b ≤ c. In one move, you can add +1 or -1 to any of these integers (i.e. increase or decrease any number by one). You can perform such operation any (possibly, zero) number of times, you can even perform this operation several times with one number. Note that you cannot make non-positiv...
```python for _ in range(int(input())): a,b,c = list(map(int, input().split())) ans = None; dist = 1e10 for i in range(1, 2*a +1): for j in range(i, 2*b +1, i): for k in range(j, 2*c + 1, j): if abs(a-i)+abs(b-j)+abs(c-k) < dist: ans = [i, j, k] ...
1334_B. Middle Class
Many years ago Berland was a small country where only n people lived. Each person had some savings: the i-th one had a_i burles. The government considered a person as wealthy if he had at least x burles. To increase the number of wealthy people Berland decided to carry out several reforms. Each reform looked like that...
```python import sys input = sys.stdin.readline Q = int(input()) Query = [] for _ in range(Q): N, K = map(int, input().split()) A = list(map(int, input().split())) Query.append((N, K, A)) for N, K, A in Query: A.sort(reverse=True) n = 0 s = 0 for i, a in enumerate(A): s += a ...
1354_D. Multiset
Note that the memory limit is unusual. You are given a multiset consisting of n integers. You have to process queries of two types: * add integer k into the multiset; * find the k-th order statistics in the multiset and remove it. k-th order statistics in the multiset is the k-th element in the sorted list o...
```python from collections import Counter from collections import defaultdict from collections import deque import math import os import sys input = sys.stdin.readline ii = 0 _inp = b'' def getchar(): global ii, _inp if ii >= len(_inp): _inp = os.read(0, 4000) ii = 0 if not _inp: r...
1374_C. Move Brackets
You are given a bracket sequence s of length n, where n is even (divisible by two). The string s consists of n/2 opening brackets '(' and n/2 closing brackets ')'. In one move, you can choose exactly one bracket and move it to the beginning of the string or to the end of the string (i.e. you choose some index i, remov...
```python n = int(input()) arr = [] for i in range(n): a = int(input()) brackets = list(input()) k = 0 t = 0 j = 0 while j < len(brackets): if brackets[j] == '(': k += 1 else: k -= 1 if k < 0: t += 1 brackets.pop(j) ...
1397_D. Stoned Game
T is playing a game with his friend, HL. There are n piles of stones, the i-th pile initially has a_i stones. T and HL will take alternating turns, with T going first. In each turn, a player chooses a non-empty pile and then removes a single stone from it. However, one cannot choose a pile that has been chosen in th...
```python from collections import defaultdict from math import inf for _ in range(int(input())): n=int(input()) arr=list(map(int,input().split())) mi=min(arr) ans=0 su=0 res="T" for i in arr: ans+=i-mi su+=i if max(arr)>su-max(arr): print(res) else: if...
1420_E. Battle Lemmings
A lighthouse keeper Peter commands an army of n battle lemmings. He ordered his army to stand in a line and numbered the lemmings from 1 to n from left to right. Some of the lemmings hold shields. Each lemming cannot hold more than one shield. The more protected Peter's army is, the better. To calculate the protection...
```python # import numpy as npy # idx=sorted(idx,key=functools.cmp_to_key(cmpx)) import bisect import array import functools import math n=int(input()) a=array.array('i',map(int,input().split())) s=0 q=[] q.append(0) for i in range(n): if a[i]==1: q.append(i+1) s=s+1 q.append(n+1) m=n*(n-1)//2 f=[[...
1466_D. 13th Labour of Heracles
You've probably heard about the twelve labors of Heracles, but do you have any idea about the thirteenth? It is commonly assumed it took him a dozen years to complete the twelve feats, so on average, a year to accomplish every one of them. As time flows faster these days, you have minutes rather than months to solve th...
```python from sys import stdin import heapq t = int(input()) for _ in range(t): n = int(input()) weight = list(map(int,stdin.readline().split())) h = [] adjacent = [set() for i in range(n)] degree = [0]*n i=0 while(i<n-1): a,b = list(map(int,stdin.readline().split())) a-=1 ...
1490_E. Accidental Victory
A championship is held in Berland, in which n players participate. The player with the number i has a_i (a_i ≥ 1) tokens. The championship consists of n-1 games, which are played according to the following rules: * in each game, two random players with non-zero tokens are selected; * the player with more tokens ...
```python import sys import math input = sys.stdin.readline mod=10**9+7 ############ ---- Input Functions ---- ############ 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(map(int,input().split...
1513_A. Array and Peaks
A sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once. Given two integers n and k, construct a permutation a of numbers from 1 to n which has exactly k peaks. An index i of an array a of size n is said to be a peak if 1 < i < n and a_i \gt a_{i-1} and a_i \gt a_{i+1}. If...
```python a=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, ...
1540_A. Great Graphs
Farmer John has a farm that consists of n pastures connected by one-directional roads. Each road has a weight, representing the time it takes to go from the start to the end of the road. The roads could have negative weight, where the cows go so fast that they go back in time! However, Farmer John guarantees that it is...
```python t = int(input()) for _ in range(t): n = int(input()) a = list(map(int,input().split())) a = sorted(a) b = [] for i in range(1,n): b += [a[i] - a[i-1]] ans = 0 n = len(b) for i in range(n): ans -= (n-i)*(i+1)*(b[i]) print(ans + sum(b)) ```
235_B. Let's Play Osu!
You're playing a game called Osu! Here's a simplified version of it. There are n clicks in a game. For each click there are two outcomes: correct or bad. Let us denote correct as "O", bad as "X", then the whole play can be encoded as a sequence of n characters "O" and "X". Using the play sequence you can calculate the...
```python n,a,b=int(input()),0,0 for i in map(float,input().split()):a,b=a+i*(1+b*2),i*(b+1) print(a) ```
25_E. Test
Sometimes it is hard to prepare tests for programming problems. Now Bob is preparing tests to new problem about strings — input data to his problem is one string. Bob has 3 wrong solutions to this problem. The first gives the wrong answer if the input data contains the substring s1, the second enters an infinite loop i...
```python from itertools import permutations from sys import stdin from functools import lru_cache input = stdin.readline s1, s2, s3 = input().strip(), input().strip(), input().strip() @lru_cache(None) def findPattern(s): #print(s) slen = len(s) p = [0]*slen ci = 0 for i in range(1, slen): i...
354_C. Vasya and Beautiful Arrays
Vasya's got a birthday coming up and his mom decided to give him an array of positive integers a of length n. Vasya thinks that an array's beauty is the greatest common divisor of all its elements. His mom, of course, wants to give him as beautiful an array as possible (with largest possible beauty). Unfortunately, th...
```python n, k = map(int, input().split()) t = set(map(int, input().split())) y = x = min(t) t = list(t) while True: for i in t: if i % x > k: x = i // (i // x + 1) if y == x: break y = x print(y) # Made By Mostafa_Khaled ```
39_F. Pacifist frogs
Thumbelina has had an accident. She has found herself on a little island in the middle of a swamp and wants to get to the shore very much. One can get to the shore only by hills that are situated along a straight line that connects the little island with the shore. Let us assume that the hills are numbered from 1 to n...
```python n, m, k = map(int, input().split()) x, y = n, [] a = map(int, input().split()) b = list(map(int, input().split())) for i, d in enumerate(a): c = 0 for t in b: if 0 == t % d: c += 1 if c < x: x = c y = [i + 1] elif c == x: y += i + 1, print(len(y)) pr...
425_B. Sereja and Table
Sereja has an n × m rectangular table a, each cell of the table contains a zero or a number one. Sereja wants his table to meet the following requirement: each connected component of the same values forms a rectangle with sides parallel to the sides of the table. Rectangles should be filled with cells, that is, if a co...
```python from functools import * read_line = lambda: [int(i) for i in input().split()] n, m, k = read_line() a = [read_line() for i in range(n)] if n < m: n, m, a = m, n, zip(*a) xs = [reduce(lambda x, b: 2 * x + b, y) for y in a] minm = lambda a: min(a, m - a) work = lambda y: sum(minm(bin(x ^ y).count('1')) f...
494_B. Obsessive String
Hamed has recently found a string t and suddenly became quite fond of it. He spent several days trying to find all occurrences of t in other strings he had. Finally he became tired and started thinking about the following problem. Given a string s how many ways are there to extract k ≥ 1 non-overlapping substrings from...
```python s, t = input(), input() n, m = len(t), len(s) d = 10 ** 9 + 7 p = [0] * (n + 1) i, j = 0, 1 while j < n: if t[i] == t[j]: j += 1 i += 1 p[j] = i elif i: i = p[i] else: j += 1 i = j = 0 f = [0] * (m + 1) while j < m: if t[i] == s[j]: i += 1 j += 1 ...
518_F. Pasha and Pipe
On a certain meeting of a ruling party "A" minister Pavel suggested to improve the sewer system and to create a new pipe in the city. The city is an n × m rectangular squared field. Each square of the field is either empty (then the pipe can go in it), or occupied (the pipe cannot go in such square). Empty squares are...
```python n, m = [int(x) for x in input().split()] a = [[int(c == '.') for c in input()] for i in range(n)] def rotate(a): n = len(a) m = len(a[0]) b = [[0] * n for i in range(m)] for i in range(n): for j in range(m): b[j][n - 1 - i] = a[i][j] return b def calc(a): n = len(...
545_A. Toy Cars
Little Susie, thanks to her older brother, likes to play with cars. Today she decided to set up a tournament between them. The process of a tournament is described in the next paragraph. There are n toy cars. Each pair collides. The result of a collision can be one of the following: no car turned over, one car turned ...
```python n=int(input()) cars=[] win=[i for i in range(1,n+1)] for i in range(n): cars.append([int(j) for j in input().split()]) for i in range(n): for j in range(n): if cars[i][j]==-1: pass elif cars[i][j]==1 or cars[i][j]==3: try: win.remove(i+1) ...
593_A. 2Char
Andrew often reads articles in his favorite magazine 2Char. The main feature of these articles is that each of them uses at most two distinct letters. Andrew decided to send an article to the magazine, but as he hasn't written any article, he just decided to take a random one from magazine 26Char. However, before sendi...
```python n=int(input()) i=0 x=[] while i<n: x.append(str(input())) i+=1 i=25 r=0 while i: j=i while j: j-=1 t=0 k=n while k: k-=1 y=x[k] z=len(y) ok=1 while z: z-=1 if ord(y[z])-ord('a')!=i: if ord(y[z])-ord('a')!=j:ok=0 if ok:t+=len(y) if r<t:r=t i-=1 print(r) ```
614_D. Skills
Lesha plays the recently published new version of the legendary game hacknet. In this version character skill mechanism was introduced. Now, each player character has exactly n skills. Each skill is represented by a non-negative integer ai — the current skill level. All skills have the same maximum level A. Along with...
```python import bisect as bs import heapq as hq def force(cf, cm, f, m): return f*cf + m*cm # def perfect(sa, amax, m): # p = 0 # while sa[-p-1] == amax: # p += 1 # while sa[p] + m >= amax: # for _ in range(amax-sa[-p-1]): # yield p # m -= amax-sa[-p-1] # ...
634_A. Island Puzzle
A remote island chain contains n islands, labeled 1 through n. Bidirectional bridges connect the islands to form a simple cycle — a bridge connects islands 1 and 2, islands 2 and 3, and so on, and additionally a bridge connects islands n and 1. The center of each island contains an identical pedestal, and all but one o...
```python n = int(input()) s1 = list(input().strip().split()) s2 = list(input().strip().split()) s1.remove('0') s2.remove('0') s1 = ''.join(s1) s2 = ''.join(s2) s1 = s1+s1 if s2 in s1: print("YES") else: print("NO") ```
662_D. International Olympiad
International Abbreviation Olympiad takes place annually starting from 1989. Each year the competition receives an abbreviation of form IAO'y, where y stands for some number of consequent last digits of the current year. Organizers always pick an abbreviation with non-empty string y that has never been used before. Amo...
```python n=int(input()) lst=[] for i in range(n): n=input() lst.append(n[4:]) for i in lst: l=len(i) i=int(i) #print(i) g=0 p=10 c=1 while(c<l): g+=p p*=10 c+=1 #print(g,p) while(i<1989+g): i+=p print(i) ```
687_B. Remainders Game
Today Pari and Arya are playing a game called Remainders. Pari chooses two positive integer x and k, and tells Arya k but not x. Arya have to find the value <image>. There are n ancient numbers c1, c2, ..., cn and Pari has to tell Arya <image> if Arya wants. Given k and the ancient values, tell us if Arya has a winnin...
```python import sys input=sys.stdin.readline import math n, k = map(int, input().split()) a = 1; ar = list(map(int, input().split())) for c in ar: a *= math.gcd(k,c)//math.gcd(a,c) #print(a,c) if a==k: print("Yes") else: print("No") ```
70_A. Cookies
Fangy collects cookies. Once he decided to take a box and put cookies into it in some way. If we take a square k × k in size, divided into blocks 1 × 1 in size and paint there the main diagonal together with cells, which lie above it, then the painted area will be equal to the area occupied by one cookie k in size. Fan...
```python import math print(math.ceil(3**(int(input())-1))%1000003) ```
730_H. Delete Them
Polycarp is a beginner programmer. He is studying how to use a command line. Polycarp faced the following problem. There are n files in a directory and he needs to delete some of them. Polycarp wants to run a single delete command with filename pattern as an argument. All the files to be deleted should match the patte...
```python n,m=map(int,input().split()) a=[] b=[] for i in range(n): a.append(input()) t=list(map(int,input().split())) flag=0 x=len(a[t[0]-1]) for i in t: b.append(a[i-1]) if len(a[i-1])!=x: flag=1 break s='' if flag!=1: for i in range(x): l=b[0][i] abc=0 for j in range(m): if b[j][i]!=l: abc=1...
754_C. Vladik and chat
Recently Vladik discovered a new entertainment — coding bots for social networks. He would like to use machine learning in his bots so now he want to prepare some learning data for them. At first, he need to download t chats. Vladik coded a script which should have downloaded the chats, however, something went wrong. ...
```python import re import copy t = int(input()) for i in range(t): n = int(input()) senderList = [] for x in input().split(): senderList.append(x) m = int(input()) msg = [None] * m resSenders = [None] * m possibleSenders = [] for i in range(m): possibleSenders.append(copy.copy(senderList)) for i in ra...
774_L. Bars
Polycarp's workday lasts exactly n minutes. He loves chocolate bars and can eat one bar in one minute. Today Polycarp has k bars at the beginning of the workday. In some minutes of the workday Polycarp has important things to do and in such minutes he is not able to eat a chocolate bar. In other minutes he can either ...
```python n, k = map(int, input().split()) s = input() l, r = int(-1), int(n) while r - l > 1: m = (l+r)//2 c, p = 1, 0 cond = True while p < n and c < k: i = p + m + 1 while i >= p and (i >= n or s[i] == '1'): i = i - 1; if (i == p): break c = c ...
820_B. Mister B and Angle in Polygon
On one quiet day all of sudden Mister B decided to draw angle a on his field. Aliens have already visited his field and left many different geometric figures on it. One of the figures is regular convex n-gon (regular convex polygon with n sides). That's why Mister B decided to use this polygon. Now Mister B must find ...
```python n, a=map(int, input().split()) alp = 180*(n-2)/n minR=181 x=3 angle=0 for i in range (3, n+1): angle = (180*(i-2) - alp*(i-2))/2 if abs(angle-a)<minR: minR=abs(angle-a) x=i print("2 1", x) ```
846_C. Four Segments
You are given an array of n integer numbers. Let sum(l, r) be the sum of all numbers on positions from l to r non-inclusive (l-th element is counted, r-th element is not counted). For indices l and r holds 0 ≤ l ≤ r ≤ n. Indices in array are numbered from 0. For example, if a = [ - 5, 3, 9, 4], then sum(0, 1) = - 5, ...
```python n=int(input()) a=[5]+list(map(int,input().split())) dp=[[[i,0] for i in range(n+1)] for j in range(4)] end=n indx_a,indx_b,indx_c=0,0,0 for i in range(1,n+1): dp[0][i][1]=dp[0][i-1][1]+a[i] dp[1][i][1]=max(dp[0][i-1][1],dp[1][i-1][1])-a[i] dp[2][i][1]=max(dp[1][i-1][1],dp[2][i-1][1])+a[i] dp[3...
893_B. Beautiful Divisors
Recently Luba learned about a special kind of numbers that she calls beautiful numbers. The number is called beautiful iff its binary representation consists of k + 1 consecutive ones, and then k consecutive zeroes. Some examples of beautiful numbers: * 12 (110); * 1102 (610); * 11110002 (12010); * 111110...
```python a=[] for i in range (1,9): a.append((pow(2,i)-1)*pow(2,i-1)) #print(a) b= int(input()) c=1 for i in range(8): if(b%a[i] is 0): c=a[i] print(c) ```
937_E. Lock Puzzle
Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm! Of course, there is a code lock is installed on the safe. The lock...
```python n = int(input()) t = input()[:n] s = input()[:n] ops =[] def shift(k, cur): if k == 0: return cur return cur[:-k-1:-1] + cur [:-k] def move_to_front(k, curst): if k == n-1: ops.append(1) curst = curst[-1] +curst [:-1] else: ops.append(n-1) ops.appen...
990_C. Bracket Sequences Concatenation Problem
A bracket sequence is a string containing only characters "(" and ")". A regular bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()()", "(())" are reg...
```python n = int(input()) arr = [] for i in range(n): arr.append(input()) l ={} r = {} z=0 for i in arr: s = 0 g = 0 for j in i: if j =='(': s+=1 else: s-=1 if s <0: g+=1 s=0 if s==0 and g==0: z+=1 if s<=0 and g: ...
p02611 AIsing Programming Contest 2020 - Two Snuke
Given is an integer N. Snuke will choose integers s_1, s_2, n_1, n_2, u_1, u_2, k_1, k_2, e_1, and e_2 so that all of the following six conditions will be satisfied: * 0 \leq s_1 < s_2 * 0 \leq n_1 < n_2 * 0 \leq u_1 < u_2 * 0 \leq k_1 < k_2 * 0 \leq e_1 < e_2 * s_1 + s_2 + n_1 + n_2 + u_1 + u_2 + k_1 + k_2 + e_1 + e_...
```python def c(n,r): a = 1 for i in range(r): a *= (n-i) a %= mod return a*ifact[r]%mod mod = pow(10,9)+7 inv = [0,1] fact = [1,1] ifact = [1,1] for i in range(2,16): inv.append(inv[mod%i]*(mod-mod//i)%mod) fact.append(i*fact[-1]%mod) ifact.append(ifact[-1]*inv[i]%mod) t = int...
p02742 Panasonic Programming Contest 2020 - Bishop
We have a board with H horizontal rows and W vertical columns of squares. There is a bishop at the top-left square on this board. How many squares can this bishop reach by zero or more movements? Here the bishop can only move diagonally. More formally, the bishop can move from the square at the r_1-th row (from the to...
```python H,W=map(int,input().split()) print(1 if H==1 or W==1 else (H*W+1)//2) ```
p03011 AtCoder Beginner Contest 129 - Airplane
There are three airports A, B and C, and flights between each pair of airports in both directions. A one-way flight between airports A and B takes P hours, a one-way flight between airports B and C takes Q hours, and a one-way flight between airports C and A takes R hours. Consider a route where we start at one of th...
```python W = [int(i) for i in input().split()] print(sum(W) - max(W)) ```
p03151 KEYENCE Programming Contest 2019 - Exam and Wizard
A university student, Takahashi, has to take N examinations and pass all of them. Currently, his readiness for the i-th examination is A_{i}, and according to his investigation, it is known that he needs readiness of at least B_{i} in order to pass the i-th examination. Takahashi thinks that he may not be able to pass...
```python N = int(input()) A = list(map(int,input().split())) B = list(map(int,input().split())) OK = [] NG = 0 count = 0 for i in range(N): x = A[i] - B[i] if x < 0: NG -= x count += 1 else: OK.append(x) l = len(OK) OK.sort(reverse = True) i = 0 while NG > 0 and i < l: NG -= OK[...
p03295 AtCoder Beginner Contest 103 - Islands War
There are N islands lining up from west to east, connected by N-1 bridges. The i-th bridge connects the i-th island from the west and the (i+1)-th island from the west. One day, disputes took place between some islands, and there were M requests from the inhabitants of the islands: Request i: A dispute took place be...
```python N, M = map(int, input().split()) ab = [list(map(int, input().split())) for _ in range(M)] ab.sort(key=lambda x: x[1]) ans = 0 x = -9999999999 for a, b in ab: if x <= a: x = b ans += 1 print(ans) ```
p03453 AtCoder Regular Contest 090 - Avoiding Collision
We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki. The i-th edge connects Vertex U_i and Vertex V_i. The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki). Takahashi departs Vertex S and Aoki ...
```python from collections import defaultdict, deque from heapq import heappop, heappush def inpl(): return list(map(int, input().split())) N, M = inpl() S, T = inpl() G = [[] for _ in range(N+1)] MOD = 10**9 + 7 for _ in range(M): u, v, d = inpl() G[u].append((v, d)) G[v].append((u, d)) cost = [10**18]*(...
p03613 AtCoder Regular Contest 082 - Together
You are given an integer sequence of length N, a_1,a_2,...,a_N. For each 1≤i≤N, you have three choices: add 1 to a_i, subtract 1 from a_i or do nothing. After these operations, you select an integer X and count the number of i such that a_i=X. Maximize this count by making optimal choices. Constraints * 1≤N≤10^5 *...
```python n = int(input()) ar = [int(x) for x in input().split()] cnt = {} for x in ar: def add(x): if x in cnt: cnt[x] += 1 else: cnt[x] = 1 add(x-1) add(x) add(x+1) counts = map(lambda x: x[1], cnt.items(...
p00033 Ball
<image> There is a container that is bifurcated as shown in the figure. Drop 10 balls numbered from 1 to 10 through the opening A of the container and place the balls in the left cylinder B or the right cylinder C. Since plate D can rotate left and right around the fulcrum E, you can move plate D to decide whether to...
```python n=int(input()) i=1 while i<=n: ball=list(map(int,input().split())) left=[0] right=[0] m=0 while True: #終了条件 if m==10: print("YES") #print("left",left,"right",right) break #noの条件 if ball[m]<left[len(left)-1] and ball[m]<rig...
p00165 Lottery
The king of a country loves prime numbers and gambling. The unit of currency in this country is called prime. As of November 1, 2007, Prime's cross-yen rate was just prime at 9973, so the King is overjoyed. Subsidiary coins with 1/101 prime as one subprime are used in this country. The government of this country has d...
```python from itertools import accumulate MAX = 1000000 is_prime = [1] * MAX is_prime[0] = is_prime[1] = 0 for i in range(2, int(MAX ** (1 / 2)) + 1): if is_prime[i]: for j in range(i * i, MAX, i): is_prime[j] = 0 acc_prime = list(accumulate(is_prime)) while True: n = int(input()) if n == 0: break...
p00321 Related Products
On the Internet shopping site, on the same page as the product that the user is currently viewing, some other products that other users have bought in the past along with the product that they are currently viewing are displayed. It is believed that sales can be increased by presenting products that are considered to b...
```python N, F = map(int, input().split()) data = [] tmp = {} for i in range(N) : data.append(list(input().split())) for x in range(1, len(data[i]) - 1) : for y in range(x+1, len(data[i])) : a = data[i][x] b = data[i][y] a, b = min(a, b), max(a, b) if (a, ...
p00491 Pasta
problem You love pasta, and you make and eat pasta for dinner every day. You can make three types of pasta: tomato sauce, cream sauce, and basil sauce. I decided to plan a dinner for N days. Choose one of the three types of pasta each day. However, if the same pasta continues, you will get bored, so do not choose the...
```python def main(dp, n, menue): if menue == 0: m1, m2 = 1, 2 elif menue == 1: m1, m2 = 0, 2 elif menue == 2: m1, m2 = 0, 1 dp[n][menue][0] += sum(dp[n-1][m1]) + sum(dp[n-1][m2]) dp[n][menue][1] += dp[n-1][menue][0] def run(): N, K = map(int, input().split()) dp = [[[0]*2 for _ in range(3)] for n in ran...
p00677 Make KND So Fat
Problem KND is a student programmer at the University of Aizu. His neighbor is known to be very annoying. Neighbors find out that he is a sweet tooth and plan to add more sweetness than necessary to make him fat. To that end, your neighbor, you, was introduced to a sweets shop by a friend. However, the way products a...
```python def main(): while True: INF = 10 ** 10 s, d, m = map(int, input().split()) ws = [] ps = [] for _ in range(s): input() wplst = list(map(int, input().split())) ws.append(wplst[::2]) ps.append(wplst[1::2]) fs = list(map(int, input().split())) wlst = [] pl...
p01354 The Castle
The rabbit, who successfully defeated the ambushed enemy, succeeded in advancing the hero into the enemy's castle. When the hero released the cats trapped in the castle dungeon, some of them were the hero's. It will help me. According to the cats, to reach the Demon King in the back of the castle, you will have to go ...
```python import sys def solve(): readline = sys.stdin.buffer.readline write = sys.stdout.buffer.write M, N = map(int, readline().split()) P = [list(map(float, readline().split())) + [0] for i in range(M)] M2 = (1 << M) dp = [[0]*(N+1) for i in range(M2)] dp[0][N] = 1 for state in range(...
p02258 Maximum Profit
You can obtain profits from foreign exchange margin transactions. For example, if you buy 1000 dollar at a rate of 100 yen per dollar, and sell them at a rate of 108 yen per dollar, you can obtain (108 - 100) × 1000 = 8000 yen. Write a program which reads values of a currency $R_t$ at a certain time $t$ ($t = 0, 1, 2,...
```python n=int(input()) ans=-9999999999999 buy=int(input()) sell=buy for i in range(1,n): buy=min(sell,buy) sell=int(input()) if(ans < sell-buy): ans=sell-buy print(ans) ```
p02406 Structured Programming
In programming languages like C/C++, a goto statement provides an unconditional jump from the "goto" to a labeled statement. For example, a statement "goto CHECK_NUM;" is executed, control of the program jumps to CHECK_NUM. Using these constructs, you can implement, for example, loops. Note that use of goto statement ...
```python n = int(input()) for i in range (1,n+1): if i%3 == 0 or str(i).find("3") != -1: print(" %d" % (i),end="") print() ```
1013_D. Chemical table
Innopolis University scientists continue to investigate the periodic table. There are n·m known elements and they form a periodic table: a rectangle with n rows and m columns. Each element can be described by its coordinates (r, c) (1 ≤ r ≤ n, 1 ≤ c ≤ m) in the table. Recently scientists discovered that for every four...
```python class UnionFind: def __init__(self, n): self.par = [-1]*n self.rank = [0]*n def Find(self, x): if self.par[x] < 0: return x else: self.par[x] = self.Find(self.par[x]) return self.par[x] def Unite(self, x, y): x = self.Fi...
1038_B. Non-Coprime Partition
Find out if it is possible to partition the first n positive integers into two non-empty disjoint sets S_1 and S_2 such that: gcd(sum(S_1), sum(S_2)) > 1 Here sum(S) denotes the sum of all elements present in set S and gcd means the[greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). Ev...
```python """#N=int(input()) n,k=map(int,input().split()) s=input() L=[0]*26 #s=[int(x) for x in input().split()] for j in range(0,len(s)): L[ord(s[j])-65]=L[ord(s[j])-65]+1 ans=1000000007 for j in range(0,k): ans=min(ans,L[j]) ans=k*ans print(ans)""" import math pre=[] for i in range(0,45010): pre.append((...
1060_F. Shrinking Tree
Consider a tree T (that is, a connected graph without cycles) with n vertices labelled 1 through n. We start the following process with T: while T has more than one vertex, do the following: * choose a random edge of T equiprobably; * shrink the chosen edge: if the edge was connecting vertices v and u, erase both ...
```python maxn=50+10 g=[None]*maxn dp=[None]*maxn c=[None]*maxn size=[0]*maxn for i in range(0,maxn): c[i]=[0]*maxn c[i][0]=1 for j in range(1,i+1): c[i][j]=c[i-1][j-1]+c[i-1][j] n=int(input()) for i in range(1,n+1): g[i]=[] for i in range(1,n): u,v=input().split() u=int(u) v=int(v...
1082_D. Maximum Diameter Graph
Graph constructive problems are back! This time the graph you are asked to build should match the following properties. The graph is connected if and only if there exists a path between every pair of vertices. The diameter (aka "longest shortest path") of a connected undirected graph is the maximum number of edges in...
```python # -*- coding:utf-8 -*- """ created by shuangquan.huang at 12/3/18 """ N = int(input()) D = [int(x) for x in input().split()] if sum(D) < 2*(N-1): print("NO") else: D = [0] + D gt2 = [i for i in range(1, N+1) if D[i] > 1] gt1 = [i for i in range(1, N + 1) if D[i] == 1] ans = [] ...
112_D. Petya and Divisors
Little Petya loves looking for numbers' divisors. One day Petya came across the following problem: You are given n queries in the form "xi yi". For each query Petya should count how many divisors of number xi divide none of the numbers xi - yi, xi - yi + 1, ..., xi - 1. Help him. Input The first line contains an int...
```python import sys,collections as cc input = sys.stdin.readline I = lambda : list(map(int,input().split())) def div(b): an=[] for i in range(1,int(b**0.5)+1): if b%i==0: an.append(i) if i!=b//i: an.append(b//i) return an n,=I() ar=[] vis=[-1]*(10**5+2) for i in range(n): a,b=I() an=0 dv=div(a) #...
1172_A. Nauuo and Cards
Nauuo is a girl who loves playing cards. One day she was playing cards but found that the cards were mixed with some empty ones. There are n cards numbered from 1 to n, and they were mixed with another n empty cards. She piled up the 2n cards and drew n of them. The n cards in Nauuo's hands are given. The remaining n...
```python def index(l): for i in range(n): if l[i]>0: j=(i+1)-l[i] l1.append(j) return(l1) n=int(input()) hand=[int(g) for g in input().split()] deck=[int(g) for g in input().split()] if 1 in deck: index2=deck.index(1) l1=[] buffer=deck[:] buffer.sort() l2=index(deck) if len(...
118_B. Present from Lena
Vasya's birthday is approaching and Lena decided to sew a patterned handkerchief to him as a present. Lena chose digits from 0 to n as the pattern. The digits will form a rhombus. The largest digit n should be located in the centre. The digits should decrease as they approach the edges. For example, for n = 5 the handk...
```python a=int(input()) x=a w=[] while a>=0: b=[] b.append(a) for i in range(a): b.append(str(a-1-i)) b.insert(0,(a-1-i)) b.insert(0,' '*(2*(x-a))) w.append(b) w.insert(0,b) a=a-1 w.pop(x) for j in w: xx=str(j) xxx=xx.replace(',','') xxxx=xxx.replace("'",'') ...
1209_A. Paint the Numbers
You are given a sequence of integers a_1, a_2, ..., a_n. You need to paint elements in colors, so that: * If we consider any color, all elements of this color must be divisible by the minimal element of this color. * The number of used colors must be minimized. For example, it's fine to paint elements [40, 1...
```python n=int(input()) arr = list(map(int,input().split())) elem = {} arr.sort() for i in arr: f=0 for k in elem: if i%k == 0: elem[k]+=1 f=1 break if not f: elem[i] = 1 print(len(elem)) ```
1292_D. Chaotic V.
[Æsir - CHAOS](https://soundcloud.com/kivawu/aesir-chaos) [Æsir - V.](https://soundcloud.com/kivawu/aesir-v) "Everything has been planned out. No more hidden concerns. The condition of Cytus is also perfect. The time right now...... 00:01:12...... It's time." The emotion samples are now sufficient. After almost 3 ...
```python from sys import stdin, stdout prime = list() factor = list() count = list() dist = list() N = 0 def find_prime(): global prime for i in range(2, 5010): is_prime = True for j in prime: if i % j == 0: is_prime = False break if is_prim...
1312_E. Array Shrinking
You are given an array a_1, a_2, ..., a_n. You can perform the following operation any number of times: * Choose a pair of two neighboring equal elements a_i = a_{i + 1} (if there is at least one such pair). * Replace them by one element with value a_i + 1. After each such operation, the length of the array w...
```python # CLONED CPP SOLUTION def rr(): return input().rstrip() def rri(): return int(rr()) def rrm(): return list(map(int, rr().split())) from collections import defaultdict def mus(d=0): return defaultdict(defaultdict(d)) def ms(x, y, d=0): return [[d]*y for i in range(x)] def ar(x, d=0): return [d]*x def ppm(m, n=...
1335_B. Construct the String
You are given three positive integers n, a and b. You have to construct a string s of length n consisting of lowercase Latin letters such that each substring of length a has exactly b distinct letters. It is guaranteed that the answer exists. You have to answer t independent test cases. Recall that the substring s[l ...
```python import string def construct(n, a, b): return ((string.ascii_lowercase[:b] + "a" * (a - b)) * (n // a + 1))[:n] t = int(input()) for i in range(t): n, a, b = map(int, input().split()) print(construct(n, a, b)) ```
1355_D. Game With Array
Petya and Vasya are competing with each other in a new interesting game as they always do. At the beginning of the game Petya has to come up with an array of N positive integers. Sum of all elements in his array should be equal to S. Then Petya has to select an integer K such that 0 ≤ K ≤ S. In order to win, Vasya ha...
```python n,s=map(int,input().split()) if 2*n<=s: print("YES") p=s//n z=[] for i in range(n): z.append(p) q=s-sum(z) if q==0: pass else: z[-1]+=q print(*z) print(s-1) else: print("NO") ```
1375_C. Element Extermination
You are given an array a of length n, which initially is a permutation of numbers from 1 to n. In one operation, you can choose an index i (1 ≤ i < n) such that a_i < a_{i + 1}, and remove either a_i or a_{i + 1} from the array (after the removal, the remaining parts are concatenated). For example, if you have the ar...
```python from sys import stdin from math import ceil inp = lambda : stdin.readline().strip() t = int(inp()) for _ in range(t): n = int(inp()) a = [int(x) for x in inp().split()] if a[0]< a[-1]: print('YES') else: print('NO') ```
1398_F. Controversial Rounds
Alice and Bob play a game. The game consists of several sets, and each set consists of several rounds. Each round is won either by Alice or by Bob, and the set ends when one of the players has won x rounds in a row. For example, if Bob won five rounds in a row and x = 2, then two sets ends. You know that Alice and Bob...
```python class BalancingTree: def __init__(self, n): self.N = n self.root = self.node(1<<n, 1<<n) def append(self, v): v += 1 nd = self.root while True: if v == nd.value: return 0 else: mi, ma = min(v, nd.value), ...
1422_B. Nice Matrix
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds. Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb...
```python import sys def rs(): return sys.stdin.readline().rstrip() def ri(): return int(sys.stdin.readline()) def ria(): return list(map(int, sys.stdin.readline().split())) def ws(s): sys.stdout.write(s + '\n') def wi(n): sys.stdout.write(str(n) + '\n') def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n'...
1440_A. Buy the String
You are given four integers n, c_0, c_1 and h and a binary string s of length n. A binary string is a string consisting of characters 0 and 1. You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change. After some changes (possibly zero) ...
```python for _ in range(int(input())): n, c0, c1, h=map(int, input().split()) s=input() print(s.count('0')*min(c0,c1+h)+s.count('1')*min(c1,c0+h)) ```
1467_B. Hills And Valleys
You are given a sequence of n integers a_1, a_2, ..., a_n. Let us call an index j (2 ≤ j ≤ {{n-1}}) a hill if a_j > a_{{j+1}} and a_j > a_{{j-1}}; and let us call it a valley if a_j < a_{{j+1}} and a_j < a_{{j-1}}. Let us define the intimidation value of a sequence as the sum of the number of hills and the number of v...
```python # cook your dish here import sys import math input=sys.stdin.readline t=int(input()) while t>0 : n=int(input()) l=list(map(int,input().split())) b=0 m=0 pm=0 f=0 f2=0 p=-1 for i in range(1,n-1) : if l[i]>l[i-1] and l[i]>l[i+1] : if p==0 : ...
1491_E. Fib-tree
Let F_k denote the k-th term of Fibonacci sequence, defined as below: * F_0 = F_1 = 1 * for any integer n ≥ 0, F_{n+2} = F_{n+1} + F_n You are given a tree with n vertices. Recall that a tree is a connected undirected graph without cycles. We call a tree a Fib-tree, if its number of vertices equals F_k for som...
```python def main(): n = int(input()) graph = [[] for _ in range(n+1)] parent = [-1 for _ in range(n+1)] for _ in range(n-1): x,y = map(int, input().split(' ')) graph[x].append(y) graph[y].append(x) digraph = [[] for _ in range(n+1)] stack = [1] count_order = []...
1514_B. AND 0, Sum Big
Baby Badawy's first words were "AND 0 SUM BIG", so he decided to solve the following problem. Given two integers n and k, count the number of arrays of length n such that: * all its elements are integers between 0 and 2^k-1 (inclusive); * the [bitwise AND](https://en.wikipedia.org/wiki/Bitwise_operation#AND) of a...
```python mod=10**9+7 for _ in range(int(input())): n,k=map(int,input().split()) print((n**k)%(mod)) ```
1541_B. Pleasant Pairs
You are given an array a_1, a_2, ..., a_n consisting of n distinct integers. Count the number of pairs of indices (i, j) such that i < j and a_i ⋅ a_j = i + j. Input The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t cases follow. The first line of each test case contains one int...
```python # -*- coding: utf-8 -*- """ Created on Fri Jun 25 21:55:30 2021 @author: sukbhatt """ for _ in " "*int(input()): n = int(input()) result = 0 arr = list(map(int, input().split())) for i in range(n): for j in range(arr[i]-i-2,n,arr[i]): if j>i and arr[j]*arr[i] == i+...
169_A. Chores
Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do n chores. Each chore is characterized by a single parameter — its complexity. The complexity of the i-th chore equals hi. As Petya is older, he wants to take the chores with complexity larger...
```python n, a, b=map(int, input().split()) l=list(map(int, input().split())) l.sort() print(l[-a]-l[-a-1]) ```
261_B. Maxim and Restaurant
Maxim has opened his own restaurant! The restaurant has got a huge table, the table's length is p meters. Maxim has got a dinner party tonight, n guests will come to him. Let's index the guests of Maxim's restaurant from 1 to n. Maxim knows the sizes of all guests that are going to come to him. The i-th guest's size (...
```python import math n = int(input()) a = [int(x) for x in input().split()] p = int(input()) sum=0; for x in range(n): sum+=a[x] if(sum<=p): print(n) else: ans=0 for i in range(n): dp = [[[0 for z in range(55)] for y in range(55)] for x in range(55)] dp[-1][0][0]=1 for j in range(n): if(j==i): for ...