contestId
int64 0
1.01k
| name
stringlengths 2
54
| prompt
stringlengths 297
7.35k
| response
stringlengths 32
43.6k
|
---|---|---|---|
1,006 | Polycarp's Practice | Title: Polycarp's Practice
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp is practicing his problem solving skill. He has a list of $n$ problems with difficulties $a_1, a_2, \dots, a_n$, respectively. His plan is to practice for exactly $k$ days. Each day he has to solve at least one problem from his list. Polycarp solves the problems in the order they are given in his list, he cannot skip any problem from his list. He has to solve all $n$ problems in exactly $k$ days.
Thus, each day Polycarp solves a contiguous sequence of (consecutive) problems from the start of the list. He can't skip problems or solve them multiple times. As a result, in $k$ days he will solve all the $n$ problems.
The profit of the $j$-th day of Polycarp's practice is the maximum among all the difficulties of problems Polycarp solves during the $j$-th day (i.e. if he solves problems with indices from $l$ to $r$ during a day, then the profit of the day is $\max\limits_{l \le i \le r}a_i$). The total profit of his practice is the sum of the profits over all $k$ days of his practice.
You want to help Polycarp to get the maximum possible total profit over all valid ways to solve problems. Your task is to distribute all $n$ problems between $k$ days satisfying the conditions above in such a way, that the total profit is maximum.
For example, if $n = 8, k = 3$ and $a = [5, 4, 2, 6, 5, 1, 9, 2]$, one of the possible distributions with maximum total profit is: $[5, 4, 2], [6, 5], [1, 9, 2]$. Here the total profit equals $5 + 6 + 9 = 20$.
Input Specification:
The first line of the input contains two integers $n$ and $k$ ($1 \le k \le n \le 2000$) β the number of problems and the number of days, respectively.
The second line of the input contains $n$ integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 2000$) β difficulties of problems in Polycarp's list, in the order they are placed in the list (i.e. in the order Polycarp will solve them).
Output Specification:
In the first line of the output print the maximum possible total profit.
In the second line print exactly $k$ positive integers $t_1, t_2, \dots, t_k$ ($t_1 + t_2 + \dots + t_k$ must equal $n$), where $t_j$ means the number of problems Polycarp will solve during the $j$-th day in order to achieve the maximum possible total profit of his practice.
If there are many possible answers, you may print any of them.
Demo Input:
['8 3\n5 4 2 6 5 1 9 2\n', '5 1\n1 1 1 1 1\n', '4 2\n1 2000 2000 2\n']
Demo Output:
['20\n3 2 3', '1\n5\n', '4000\n2 2\n']
Note:
The first example is described in the problem statement.
In the second example there is only one possible distribution.
In the third example the best answer is to distribute problems in the following way: $[1, 2000], [2000, 2]$. The total profit of this distribution is $2000 + 2000 = 4000$. | ```python
n,k=map(int,input().split())
a=list(map(int,input().split()))
b=sorted(a,reverse=True)
b=b[:k]
c=k
print(sum(b))
j=0
for i in range(n):
if(a[i] in b and c!=1):
print(i+1-j,end=' ')
j=i+1
b.remove(a[i])
c-=1
if(c==1):
print(n-j)
break
``` |
702 | Cellular Network | Title: Cellular Network
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* points on the straight line β the positions (*x*-coordinates) of the cities and *m* points on the same line β the positions (*x*-coordinates) of the cellular towers. All towers work in the same way β they provide cellular network for all cities, which are located at the distance which is no more than *r* from this tower.
Your task is to find minimal *r* that each city has been provided by cellular network, i.e. for each city there is at least one cellular tower at the distance which is no more than *r*.
If *r*<==<=0 then a tower provides cellular network only for the point where it is located. One tower can provide cellular network for any number of cities, but all these cities must be at the distance which is no more than *r* from this tower.
Input Specification:
The first line contains two positive integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=105) β the number of cities and the number of cellular towers.
The second line contains a sequence of *n* integers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=β€<=*a**i*<=β€<=109) β the coordinates of cities. It is allowed that there are any number of cities in the same point. All coordinates *a**i* are given in non-decreasing order.
The third line contains a sequence of *m* integers *b*1,<=*b*2,<=...,<=*b**m* (<=-<=109<=β€<=*b**j*<=β€<=109) β the coordinates of cellular towers. It is allowed that there are any number of towers in the same point. All coordinates *b**j* are given in non-decreasing order.
Output Specification:
Print minimal *r* so that each city will be covered by cellular network.
Demo Input:
['3 2\n-2 2 4\n-3 0\n', '5 3\n1 5 10 14 17\n4 11 15\n']
Demo Output:
['4\n', '3\n']
Note:
none | ```python
R = lambda: map(int, input().split())
n, mm = R()
cts, tws = list(R()), list(R())
l, r = 0, 2 * 10 ** 9 + 7
while l < r:
m = (l + r) // 2
j = 0
for i in range(mm):
while j < n and tws[i] - m <= cts[j] <= tws[i] + m:
j += 1
if j != n:
l = m + 1
else:
r = m
print(l)
``` |
888 | Maximum Subsequence | Title: Maximum Subsequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* consisting of *n* integers, and additionally an integer *m*. You have to choose some sequence of indices *b*1,<=*b*2,<=...,<=*b**k* (1<=β€<=*b*1<=<<=*b*2<=<<=...<=<<=*b**k*<=β€<=*n*) in such a way that the value of is maximized. Chosen sequence can be empty.
Print the maximum possible value of .
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=35, 1<=β€<=*m*<=β€<=109).
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print the maximum possible value of .
Demo Input:
['4 4\n5 2 4 1\n', '3 20\n199 41 299\n']
Demo Output:
['3\n', '19\n']
Note:
In the first example you can choose a sequence *b*β=β{1,β2}, so the sum <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c856546022c2feee13d02a4ec9cd1d361ab3a756.png" style="max-width: 100.0%;max-height: 100.0%;"/> is equal to 7 (and that's 3 after taking it modulo 4).
In the second example you can choose a sequence *b*β=β{3}. | ```python
import bisect
n,M= tuple(map(int,input().split()))
nums = list(map(int,input().split()))
r1,r2 = [],[]
def dfs(index,last,sum,check):
if index == last:
if check == 1:
r1.append(sum)
else:
r2.append(sum)
return
dfs(index+1,last,sum,check)
dfs(index+1,last,(sum+nums[index])%M,check)
dfs(0,n//2,0,1)
dfs(n//2,n,0,2)
s1 = set()
s2 = set()
for i in r1:
s1.add(i)
for i in r2:
s2.add(i)
r1 = sorted(list(s1))
r2 = sorted(list(s2))
ans = 0
for x in r1:
p = bisect.bisect_left(r2,M-x)
ans = max(ans,x+r2[p-1])
print(ans)
``` |
926 | 2-3-numbers | Title: 2-3-numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A positive integer is called a 2-3-integer, if it is equal to 2*x*Β·3*y* for some non-negative integers *x* and *y*. In other words, these integers are such integers that only have 2 and 3 among their prime divisors. For example, integers 1, 6, 9, 16 and 108 β are 2-3 integers, while 5, 10, 21 and 120 are not.
Print the number of 2-3-integers on the given segment [*l*,<=*r*], i.Β e. the number of sich 2-3-integers *t* that *l*<=β€<=*t*<=β€<=*r*.
Input Specification:
The only line contains two integers *l* and *r* (1<=β€<=*l*<=β€<=*r*<=β€<=2Β·109).
Output Specification:
Print a single integer the number of 2-3-integers on the segment [*l*,<=*r*].
Demo Input:
['1 10\n', '100 200\n', '1 2000000000\n']
Demo Output:
['7\n', '5\n', '326\n']
Note:
In the first example the 2-3-integers are 1, 2, 3, 4, 6, 8 and 9.
In the second example the 2-3-integers are 108, 128, 144, 162 and 192. | ```python
def rec(x):
s=0
t=1
u=1
while(x>=(2**t)):
s+=1
t+=1
while(x>=(3**u)):
s+=1
u+=1
t=1
u=1
while(x>=(2**t)*(3**u)):
s+=1
v=u+1
while(x>=(2**t)*(3**v)):
s+=1
v+=1
t+=1
return s
l,r=map(int,input().split())
ans =0
if l == 1:
ans=1
ans +=rec(r)-rec(l-1)
print(ans)
``` |
803 | Magazine Ad | Title: Magazine Ad
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The main city magazine offers its readers an opportunity to publish their ads. The format of the ad should be like this:
There are space-separated non-empty words of lowercase and uppercase Latin letters.
There are hyphen characters '-' in some words, their positions set word wrapping points. Word can include more than one hyphen.
It is guaranteed that there are no adjacent spaces and no adjacent hyphens. No hyphen is adjacent to space. There are no spaces and no hyphens before the first word and after the last word.
When the word is wrapped, the part of the word before hyphen and the hyphen itself stay on current line and the next part of the word is put on the next line. You can also put line break between two words, in that case the space stays on current line. Check notes for better understanding.
The ad can occupy no more that *k* lines and should have minimal width. The width of the ad is the maximal length of string (letters, spaces and hyphens are counted) in it.
You should write a program that will find minimal width of the ad.
Input Specification:
The first line contains number *k* (1<=β€<=*k*<=β€<=105).
The second line contains the text of the ad β non-empty space-separated words of lowercase and uppercase Latin letters and hyphens. Total length of the ad don't exceed 106 characters.
Output Specification:
Output minimal width of the ad.
Demo Input:
['4\ngarage for sa-le\n', '4\nEdu-ca-tion-al Ro-unds are so fun\n']
Demo Output:
['7\n', '10\n']
Note:
Here all spaces are replaced with dots.
In the first example one of possible results after all word wraps looks like this:
The second example: | ```python
n = int(input())
a = input()
r=len(a)+1
a = a.replace(' ','- ').replace('-','- ').split()
l = max(map(lambda x: len(x),a))
while l < r:
m,lines,x = (r-l)//2+l,1,0
for b in a:
if x+len(b) > m:
x = len(b)
lines += 1
else:
x += len(b)
if lines > n:
l = m+1
else:
r = m
print(r)
``` |
825 | Multi-judge Solving | Title: Multi-judge Solving
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Makes solves problems on Decoforces and lots of other different online judges. Each problem is denoted by its difficulty β a positive integer number. Difficulties are measured the same across all the judges (the problem with difficulty *d* on Decoforces is as hard as the problem with difficulty *d* on any other judge).
Makes has chosen *n* problems to solve on Decoforces with difficulties *a*1,<=*a*2,<=...,<=*a**n*. He can solve these problems in arbitrary order. Though he can solve problem *i* with difficulty *a**i* only if he had already solved some problem with difficulty (no matter on what online judge was it).
Before starting this chosen list of problems, Makes has already solved problems with maximum difficulty *k*.
With given conditions it's easy to see that Makes sometimes can't solve all the chosen problems, no matter what order he chooses. So he wants to solve some problems on other judges to finish solving problems from his list.
For every positive integer *y* there exist some problem with difficulty *y* on at least one judge besides Decoforces.
Makes can solve problems on any judge at any time, it isn't necessary to do problems from the chosen list one right after another.
Makes doesn't have too much free time, so he asked you to calculate the minimum number of problems he should solve on other judges in order to solve all the chosen problems from Decoforces.
Input Specification:
The first line contains two integer numbers *n*, *k* (1<=β€<=*n*<=β€<=103, 1<=β€<=*k*<=β€<=109).
The second line contains *n* space-separated integer numbers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print minimum number of problems Makes should solve on other judges in order to solve all chosen problems on Decoforces.
Demo Input:
['3 3\n2 1 9\n', '4 20\n10 3 6 3\n']
Demo Output:
['1\n', '0\n']
Note:
In the first example Makes at first solves problems 1 and 2. Then in order to solve the problem with difficulty 9, he should solve problem with difficulty no less than 5. The only available are difficulties 5 and 6 on some other judge. Solving any of these will give Makes opportunity to solve problem 3.
In the second example he can solve every problem right from the start. | ```python
n,k=map(int,input().split())
a=list(map(int,input().split()))
a.sort()
jauap=0
for i in a:
while i>k*2:
jauap+=1
k=k*2
k=max(k,i)
print(jauap)
``` |
817 | Imbalanced Array | Title: Imbalanced Array
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* consisting of *n* elements. The imbalance value of some subsegment of this array is the difference between the maximum and minimum element from this segment. The imbalance value of the array is the sum of imbalance values of all subsegments of this array.
For example, the imbalance value of array [1,<=4,<=1] is 9, because there are 6 different subsegments of this array:
- [1] (from index 1 to index 1), imbalance value is 0; - [1,<=4] (from index 1 to index 2), imbalance value is 3; - [1,<=4,<=1] (from index 1 to index 3), imbalance value is 3; - [4] (from index 2 to index 2), imbalance value is 0; - [4,<=1] (from index 2 to index 3), imbalance value is 3; - [1] (from index 3 to index 3), imbalance value is 0;
You have to determine the imbalance value of the array *a*.
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=106) β size of the array *a*.
The second line contains *n* integers *a*1,<=*a*2... *a**n* (1<=β€<=*a**i*<=β€<=106) β elements of the array.
Output Specification:
Print one integer β the imbalance value of *a*.
Demo Input:
['3\n1 4 1\n']
Demo Output:
['9\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
stk = [(float('-inf'), int(-1))]
stk1 = [(float('inf'), int(-1))]
leftSmaller = []
leftGreater = []
for i, a in enumerate(A):
while stk[-1][0] > a:
stk.pop()
leftSmaller.append(stk[-1][1])
stk.append((a, i))
while stk1[-1][0] <= a:
stk1.pop()
leftGreater.append(stk1[-1][1])
stk1.append((a, i))
stk = [(float('-inf'), int(N))]
stk1 = [(float('inf'), int(N))]
rightSmaller = []
rightGreater = []
for i in range(N - 1, -1, -1):
a = A[i]
while stk[-1][0] >= a:
stk.pop()
rightSmaller.append(stk[-1][1])
stk.append((a, i))
while stk1[-1][0] < a:
stk1.pop()
rightGreater.append(stk1[-1][1])
stk1.append((a, i))
rightGreater.reverse()
rightSmaller.reverse()
ans = 0
for i, a in enumerate(A):
ans += a * ((rightGreater[i] - i) * (i - leftGreater[i]) - ((rightSmaller[i] - i) * (i - leftSmaller[i])))
print(ans)
``` |
762 | Two strings | Title: Two strings
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two strings *a* and *b*. You have to remove the minimum possible number of consecutive (standing one after another) characters from string *b* in such a way that it becomes a subsequence of string *a*. It can happen that you will not need to remove any characters at all, or maybe you will have to remove all of the characters from *b* and make it empty.
Subsequence of string *s* is any such string that can be obtained by erasing zero or more characters (not necessarily consecutive) from string *s*.
Input Specification:
The first line contains string *a*, and the second lineΒ β string *b*. Both of these strings are nonempty and consist of lowercase letters of English alphabet. The length of each string is no bigger than 105 characters.
Output Specification:
On the first line output a subsequence of string *a*, obtained from *b* by erasing the minimum number of consecutive characters.
If the answer consists of zero characters, output Β«-Β» (a minus sign).
Demo Input:
['hi\nbob\n', 'abca\naccepted\n', 'abacaba\nabcdcba\n']
Demo Output:
['-\n', 'ac\n', 'abcba\n']
Note:
In the first example strings *a* and *b* don't share any symbols, so the longest string that you can get is empty.
In the second example ac is a subsequence of *a*, and at the same time you can obtain it by erasing consecutive symbols cepted from string *b*. | ```python
def solve(s1,s2):
n=len(s1)
m=len(s2)
s1=' ' +s1 + ' '
s2=' ' +s2 + ' '
tmp=0
v1=[0]*100005
v2=[0]*100005
for i in range(1,n+1):
if s1[i]==s2[tmp+1]:
tmp+=1
v1[i]=tmp
tmp=m+1
v2[n+1]=tmp
for i in range(n,0,-1):
if s1[i]==s2[tmp-1]:
tmp-=1
v2[i]=tmp
b=0
mx=0
for i in range(n+1):
c=v1[i]+m-v2[i+1]+1
if c>mx:
mx=c
b=i
ans=[]
if mx>=m:
for i in range(1,m+1):
ans.append(s2[i])
else:
for i in range(1,v1[b]+1):
ans.append(s2[i])
for i in range(v2[b+1],m+1):
ans.append(s2[i])
while len(ans)>0 and ans[-1]==' ':
ans.pop()
if len(ans)==0:
ans="-"
return ''.join(ans)
s1=input()
s2=input()
print(solve(s1,s2))
``` |
690 | Brain Network (easy) | Title: Brain Network (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One particularly well-known fact about zombies is that they move and think terribly slowly. While we still don't know why their movements are so sluggish, the problem of laggy thinking has been recently resolved. It turns out that the reason is not (as previously suspected) any kind of brain defect β it's the opposite! Independent researchers confirmed that the nervous system of a zombie is highly complicated β it consists of *n* brains (much like a cow has several stomachs). They are interconnected by brain connectors, which are veins capable of transmitting thoughts between brains. There are two important properties such a brain network should have to function properly:
1. It should be possible to exchange thoughts between any two pairs of brains (perhaps indirectly, through other brains). 1. There should be no redundant brain connectors, that is, removing any brain connector would make property 1 false.
If both properties are satisfied, we say that the nervous system is valid. Unfortunately (?), if the system is not valid, the zombie stops thinking and becomes (even more) dead. Your task is to analyze a given nervous system of a zombie and find out whether it is valid.
Input Specification:
The first line of the input contains two space-separated integers *n* and *m* (1<=β€<=*n*,<=*m*<=β€<=1000) denoting the number of brains (which are conveniently numbered from 1 to *n*) and the number of brain connectors in the nervous system, respectively. In the next *m* lines, descriptions of brain connectors follow. Every connector is given as a pair of brains *a*β*b* it connects (1<=β€<=*a*,<=*b*<=β€<=*n*, *a*<=β <=*b*).
Output Specification:
The output consists of one line, containing either yes or no depending on whether the nervous system is valid.
Demo Input:
['4 4\n1 2\n2 3\n3 1\n4 1\n', '6 5\n1 2\n2 3\n3 4\n4 5\n3 6\n']
Demo Output:
['no\n', 'yes\n']
Note:
none | ```python
from collections import deque
n, m = [int(i) for i in input().split()]
graph = [[] for i in range(n)]
for i in range(m):
a, b = [int(i) for i in input().split()]
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
def bfs():
visited = [False] * n
queue = deque([0])
while queue:
vertex = queue.pop()
for i in graph[vertex]:
if not visited[i]:
visited[i] = True
queue.append(i)
return all(visited)
if m == n - 1 and bfs():
print('yes')
else:
print('no')
``` |
120 | Quiz League | Title: Quiz League
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number *k*.
Input Specification:
The first line contains two positive integers *n* and *k* (1<=β€<=*n*<=β€<=1000 and 1<=β€<=*k*<=β€<=*n*) β the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains *n* numbers: *a**i*<==<=0 if the question from sector *i* has already been asked and *a**i*<==<=1 if the question from sector *i* hasn't been asked yet (1<=β€<=*i*<=β€<=*n*). The sectors are given in the clockwise order, the first sector follows after the *n*-th one.
Output Specification:
Print the single number β the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
Demo Input:
['5 5\n0 1 0 1 0\n', '2 1\n1 1\n']
Demo Output:
['2\n', '1\n']
Note:
none | ```python
class CodeforcesTask120BSolution:
def __init__(self):
self.result = ''
self.n_k = []
self.questions = []
def read_input(self):
in_ = open("input.txt").read().split("\n")
self.n_k = [int(x) for x in in_[0].split(" ")]
self.questions = [int(x) for x in in_[1].split(" ")]
def process_task(self):
x = self.n_k[1]
while not self.questions[x - 1]:
x += 1
if x > self.n_k[0]:
x = 1
self.result = str(x)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask120BSolution()
Solution.read_input()
Solution.process_task()
open("output.txt", "w").write(Solution.get_result())
``` |
656 | Ace It! | Title: Ace It!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").
Output a single integer.
Input Specification:
The only line of the input is a string of 7 characters. The first character is letter A, followed by 6 digits. The input is guaranteed to be valid (for certain definition of "valid").
Output Specification:
Output a single integer.
Demo Input:
['A221033\n', 'A223635\n', 'A232726\n']
Demo Output:
['21\n', '22\n', '23\n']
Note:
none | ```python
a=str(input())
s=0
for i in range(len(a)):
if a[i]=='A':
s+=1
elif a[i]=='1':
s+=10
else:
s+=int(a[i])
print(s)
``` |
630 | Cracking the Code | Title: Cracking the Code
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The protection of a popular program developed by one of IT City companies is organized the following way. After installation it outputs a random five digit number which should be sent in SMS to a particular phone number. In response an SMS activation code arrives.
A young hacker Vasya disassembled the program and found the algorithm that transforms the shown number into the activation code. Note: it is clear that Vasya is a law-abiding hacker, and made it for a noble purpose β to show the developer the imperfection of their protection.
The found algorithm looks the following way. At first the digits of the number are shuffled in the following order <first digit><third digit><fifth digit><fourth digit><second digit>. For example the shuffle of 12345 should lead to 13542. On the second stage the number is raised to the fifth power. The result of the shuffle and exponentiation of the number 12345 is 455Β 422Β 043Β 125Β 550Β 171Β 232. The answer is the 5 last digits of this result. For the number 12345 the answer should be 71232.
Vasya is going to write a keygen program implementing this algorithm. Can you do the same?
Input Specification:
The only line of the input contains a positive integer five digit number for which the activation code should be found.
Output Specification:
Output exactly 5 digits without spaces between them β the found activation code of the program.
Demo Input:
['12345\n']
Demo Output:
['71232']
Note:
none | ```python
num = input()
answ = int("".join((num[i] for i in [0,2,4,3,1])))
answ = str(answ**5)
print(answ[-5:])# 1698156355.2098389
``` |
845 | Luba And The Ticket | Title: Luba And The Ticket
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luba has a ticket consisting of 6 digits. In one move she can choose digit in any position and replace it with arbitrary digit. She wants to know the minimum number of digits she needs to replace in order to make the ticket lucky.
The ticket is considered lucky if the sum of first three digits equals to the sum of last three digits.
Input Specification:
You are given a string consisting of 6 characters (all characters are digits from 0 to 9) β this string denotes Luba's ticket. The ticket can start with the digit 0.
Output Specification:
Print one number β the minimum possible number of digits Luba needs to replace to make the ticket lucky.
Demo Input:
['000000\n', '123456\n', '111000\n']
Demo Output:
['0\n', '2\n', '1\n']
Note:
In the first example the ticket is already lucky, so the answer is 0.
In the second example Luba can replace 4 and 5 with zeroes, and the ticket will become lucky. It's easy to see that at least two replacements are required.
In the third example Luba can replace any zero with 3. It's easy to see that at least one replacement is required. | ```python
x=int(input())
def s(a):
r=0
while a>0:
r+=a%10
a//=10
return r
def d(a,b):
r=0
for i in range(6):
if a%10!=b%10:
r += 1
a//=10
b//=10
return r
c=6
for i in range(1000000):
if s(i%1000)==s(i//1000):
c=min(c,d(x,i))
print(c)
``` |
1,005 | Polycarp and Div 3 | Title: Polycarp and Div 3
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp likes numbers that are divisible by 3.
He has a huge number $s$. Polycarp wants to cut from it the maximum number of numbers that are divisible by $3$. To do this, he makes an arbitrary number of vertical cuts between pairs of adjacent digits. As a result, after $m$ such cuts, there will be $m+1$ parts in total. Polycarp analyzes each of the obtained numbers and finds the number of those that are divisible by $3$.
For example, if the original number is $s=3121$, then Polycarp can cut it into three parts with two cuts: $3|1|21$. As a result, he will get two numbers that are divisible by $3$.
Polycarp can make an arbitrary number of vertical cuts, where each cut is made between a pair of adjacent digits. The resulting numbers cannot contain extra leading zeroes (that is, the number can begin with 0 if and only if this number is exactly one character '0'). For example, 007, 01 and 00099 are not valid numbers, but 90, 0 and 10001 are valid.
What is the maximum number of numbers divisible by $3$ that Polycarp can obtain?
Input Specification:
The first line of the input contains a positive integer $s$. The number of digits of the number $s$ is between $1$ and $2\cdot10^5$, inclusive. The first (leftmost) digit is not equal to 0.
Output Specification:
Print the maximum number of numbers divisible by $3$ that Polycarp can get by making vertical cuts in the given number $s$.
Demo Input:
['3121\n', '6\n', '1000000000000000000000000000000000\n', '201920181\n']
Demo Output:
['2\n', '1\n', '33\n', '4\n']
Note:
In the first example, an example set of optimal cuts on the number is 3|1|21.
In the second example, you do not need to make any cuts. The specified number 6 forms one number that is divisible by $3$.
In the third example, cuts must be made between each pair of digits. As a result, Polycarp gets one digit 1 and $33$ digits 0. Each of the $33$ digits 0 forms a number that is divisible by $3$.
In the fourth example, an example set of optimal cuts is 2|0|1|9|201|81. The numbers $0$, $9$, $201$ and $81$ are divisible by $3$. | ```python
# LUOGU_RID: 96253599
n = input()
a = [int(i) for i in n]
tmp = 0
cnt = 0
ans = 0
for i in a:
t = i % 3
tmp = (tmp + t) % 3
cnt += 1
if t == 0 or tmp == 0 or cnt == 3:
ans += 1
cnt = 0
tmp = 0
print(ans)
``` |
999 | Equalize the Remainders | Title: Equalize the Remainders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array consisting of $n$ integers $a_1, a_2, \dots, a_n$, and a positive integer $m$. It is guaranteed that $m$ is a divisor of $n$.
In a single move, you can choose any position $i$ between $1$ and $n$ and increase $a_i$ by $1$.
Let's calculate $c_r$ ($0 \le r \le m-1)$ β the number of elements having remainder $r$ when divided by $m$. In other words, for each remainder, let's find the number of corresponding elements in $a$ with that remainder.
Your task is to change the array in such a way that $c_0 = c_1 = \dots = c_{m-1} = \frac{n}{m}$.
Find the minimum number of moves to satisfy the above requirement.
Input Specification:
The first line of input contains two integers $n$ and $m$ ($1 \le n \le 2 \cdot 10^5, 1 \le m \le n$). It is guaranteed that $m$ is a divisor of $n$.
The second line of input contains $n$ integers $a_1, a_2, \dots, a_n$ ($0 \le a_i \le 10^9$), the elements of the array.
Output Specification:
In the first line, print a single integer β the minimum number of moves required to satisfy the following condition: for each remainder from $0$ to $m - 1$, the number of elements of the array having this remainder equals $\frac{n}{m}$.
In the second line, print any array satisfying the condition and can be obtained from the given array with the minimum number of moves. The values of the elements of the resulting array must not exceed $10^{18}$.
Demo Input:
['6 3\n3 2 0 6 10 12\n', '4 2\n0 1 2 3\n']
Demo Output:
['3\n3 2 0 7 10 14 \n', '0\n0 1 2 3 \n']
Note:
none | ```python
"""
-*- coding: utf-8 -*-
Created on Sat Jan 22 18:33:32 2022
@author: Tausif Khan Arnob
"""
n, m = map(int, input().split())
a = [*map(int, input().split())]
li = [[] for i in range(m)]
k, s, j = n // m, sum(a), 0
for i, val in enumerate(a):
li[val % m].append(i)
for i in range(m):
while len(li[i]) > k:
while j < i or len(li[j % m]) >= k:
j += 1
x = li[i].pop()
a[x] += (j - i) % m
li[j % m].append(x)
print(sum(a) - s)
print(*a)
``` |
915 | Coprime Arrays | Title: Coprime Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call an array *a* of size *n* coprime iff *gcd*(*a*1,<=*a*2,<=...,<=*a**n*)<==<=1, where *gcd* is the greatest common divisor of the arguments.
You are given two numbers *n* and *k*. For each *i* (1<=β€<=*i*<=β€<=*k*) you have to determine the number of coprime arrays *a* of size *n* such that for every *j* (1<=β€<=*j*<=β€<=*n*) 1<=β€<=*a**j*<=β€<=*i*. Since the answers can be very large, you have to calculate them modulo 109<=+<=7.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*n*,<=*k*<=β€<=2Β·106) β the size of the desired arrays and the maximum upper bound on elements, respectively.
Output Specification:
Since printing 2Β·106 numbers may take a lot of time, you have to output the answer in such a way:
Let *b**i* be the number of coprime arrays with elements in range [1,<=*i*], taken modulo 109<=+<=7. You have to print , taken modulo 109<=+<=7. Here denotes bitwise xor operation (^ in C++ or Java, xor in Pascal).
Demo Input:
['3 4\n', '2000000 8\n']
Demo Output:
['82\n', '339310063\n']
Note:
Explanation of the example:
Since the number of coprime arrays is large, we will list the arrays that are non-coprime, but contain only elements in range [1,β*i*]:
For *i*β=β1, the only array is coprime. *b*<sub class="lower-index">1</sub>β=β1.
For *i*β=β2, array [2,β2,β2] is not coprime. *b*<sub class="lower-index">2</sub>β=β7.
For *i*β=β3, arrays [2,β2,β2] and [3,β3,β3] are not coprime. *b*<sub class="lower-index">3</sub>β=β25.
For *i*β=β4, arrays [2,β2,β2], [3,β3,β3], [2,β2,β4], [2,β4,β2], [2,β4,β4], [4,β2,β2], [4,β2,β4], [4,β4,β2] and [4,β4,β4] are not coprime. *b*<sub class="lower-index">4</sub>β=β55. | ```python
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
mod = pow(10, 9) + 7
ans = 0
p2 = [pow(i, n, mod) for i in range(k + 1)]
dp0 = [1] * (k + 1)
dp = [0] * (k + 1)
cnt = 0
for i in range(2, k + 1):
dp0i = dp0[i]
dp[i] += dp0i
dp[i] %= mod
c = 2
for j in range(2 * i, k + 1, i):
dp0[j] -= dp0i
dp0[j] %= mod
dp[j] += (p2[c] - p2[c - 1]) % mod * dp0i % mod
dp[j] %= mod
c += 1
cnt += dp[i]
cnt %= mod
ans += ((p2[i] - cnt) % mod) ^ i
ans %= mod
print(ans)
``` |
846 | Random Query | Title: Random Query
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an array *a* consisting of *n* positive integers. You pick two integer numbers *l* and *r* from 1 to *n*, inclusive (numbers are picked randomly, equiprobably and independently). If *l*<=><=*r*, then you swap values of *l* and *r*. You have to calculate the expected value of the number of unique elements in segment of the array from index *l* to index *r*, inclusive (1-indexed).
Input Specification:
The first line contains one integer number *n* (1<=β€<=*n*<=β€<=106). The second line contains *n* integer numbers *a*1, *a*2, ... *a**n* (1<=β€<=*a**i*<=β€<=106) β elements of the array.
Output Specification:
Print one number β the expected number of unique elements in chosen segment.
Your answer will be considered correct if its absolute or relative error doesn't exceed 10<=-<=4 β formally, the answer is correct if , where *x* is jury's answer, and *y* is your answer.
Demo Input:
['2\n1 2\n', '2\n2 2\n']
Demo Output:
['1.500000\n', '1.000000\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
l = pow(10, 6)
c, c1, c2 = 0, 0, 0
y = [-1] * (l + 1)
mod = pow(10, 9) + 7
for i in range(n):
ai = a[i]
if y[ai] == -1:
c += 1
s = i - y[ai]
t = (s - 1) * (s - 2)
c1 += t % mod
c2 += t // mod
c1 += s - 1
if c1 >= mod:
c1 %= mod
c2 += 1
y[ai] = i
for i in range(1, l + 1):
if not y[i] == -1:
s = n - y[i]
t = (s - 1) * (s - 2)
c1 += t % mod
c2 += t // mod
c1 += s - 1
if c1 >= mod:
c1 %= mod
c2 += 1
ans = ((c * n * n) - (c1 + c2 * mod)) / (n * n)
print(ans)
``` |
888 | K-Dominant Character | Title: K-Dominant Character
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a string *s* consisting of lowercase Latin letters. Character *c* is called *k*-dominant iff each substring of *s* with length at least *k* contains this character *c*.
You have to find minimum *k* such that there exists at least one *k*-dominant character.
Input Specification:
The first line contains string *s* consisting of lowercase Latin letters (1<=β€<=|*s*|<=β€<=100000).
Output Specification:
Print one number β the minimum value of *k* such that there exists at least one *k*-dominant character.
Demo Input:
['abacaba\n', 'zzzzz\n', 'abcde\n']
Demo Output:
['2\n', '1\n', '3\n']
Note:
none | ```python
d=dict()
s=input()
for i in set(s):
a=s.index(i)
d[i]=[a+1,a]
p=0
for j in range(len(s)):
i=s[j]
d[i][0]=max(d[i][0],j-d[i][1])
d[i][1]=j
ans=len(s)
k=len(s)
for i in d.values():
if i[0]!=0:
ans=min(ans,max(i[0],k-i[1]))
print(ans)
``` |
245 | Restoring Table | Title: Restoring Table
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Polycarpus has learned the "bitwise AND" operation (which is also called "AND") of non-negative integers. Now he wants to demonstrate the school IT teacher his superb manipulation with the learned operation.
For that Polycarpus came to school a little earlier and wrote on the board a sequence of non-negative integers *a*1,<=*a*2,<=...,<=*a**n*. He also wrote a square matrix *b* of size *n*<=Γ<=*n*. The element of matrix *b* that sits in the *i*-th row in the *j*-th column (we'll denote it as *b**ij*) equals:
- the "bitwise AND" of numbers *a**i* and *a**j* (that is, *b**ij*<==<=*a**i*Β &Β *a**j*), if *i*<=β <=*j*; - -1, if *i*<==<=*j*.
Having written out matrix *b*, Polycarpus got very happy and wiped *a* off the blackboard. But the thing is, the teacher will want this sequence to check whether Polycarpus' calculations were correct. Polycarus urgently needs to restore the removed sequence of integers, or else he won't prove that he can count correctly.
Help Polycarpus, given matrix *b*, restore the sequence of numbers *a*1,<=*a*2,<=...,<=*a**n*, that he has removed from the board. Polycarpus doesn't like large numbers, so any number in the restored sequence mustn't exceed 109.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the size of square matrix *b*. Next *n* lines contain matrix *b*. The *i*-th of these lines contains *n* space-separated integers: the *j*-th number represents the element of matrix *b**ij*. It is guaranteed, that for all *i* (1<=β€<=*i*<=β€<=*n*) the following condition fulfills: *b**ii* = -1. It is guaranteed that for all *i*,<=*j* (1<=β€<=*i*,<=*j*<=β€<=*n*;Β *i*<=β <=*j*) the following condition fulfills: 0<=β€<=*b**ij*<=β€<=109, *b**ij*<==<=*b**ji*.
Output Specification:
Print *n* non-negative integers *a*1,<=*a*2,<=...,<=*a**n* (0<=β€<=*a**i*<=β€<=109) β the sequence that Polycarpus wiped off the board. Separate the numbers by whitespaces.
It is guaranteed that there is sequence *a* that satisfies the problem conditions. If there are multiple such sequences, you are allowed to print any of them.
Demo Input:
['1\n-1\n', '3\n-1 18 0\n18 -1 0\n0 0 -1\n', '4\n-1 128 128 128\n128 -1 148 160\n128 148 -1 128\n128 160 128 -1\n']
Demo Output:
['0 ', '18 18 0 ', '128 180 148 160 ']
Note:
If you do not know what is the "bitwise AND" operation please read: http://en.wikipedia.org/wiki/Bitwise_operation. | ```python
n=int(input())
l=[]
for _ in range(n):
q=0
for i in map(int,input().split()):
if i!=-1:q|=i
l+=[q]
print(*l)
``` |
730 | Car Repair Shop | Title: Car Repair Shop
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp starts his own business. Tomorrow will be the first working day of his car repair shop. For now the car repair shop is very small and only one car can be repaired at a given time.
Polycarp is good at marketing, so he has already collected *n* requests from clients. The requests are numbered from 1 to *n* in order they came.
The *i*-th request is characterized by two values: *s**i* β the day when a client wants to start the repair of his car, *d**i* β duration (in days) to repair the car. The days are enumerated from 1, the first day is tomorrow, the second day is the day after tomorrow and so on.
Polycarp is making schedule by processing requests in the order from the first to the *n*-th request. He schedules the *i*-th request as follows:
- If the car repair shop is idle for *d**i* days starting from *s**i* (*s**i*,<=*s**i*<=+<=1,<=...,<=*s**i*<=+<=*d**i*<=-<=1), then these days are used to repair a car of the *i*-th client. - Otherwise, Polycarp finds the first day *x* (from 1 and further) that there are *d**i* subsequent days when no repair is scheduled starting from *x*. In other words he chooses the smallest positive *x* that all days *x*,<=*x*<=+<=1,<=...,<=*x*<=+<=*d**i*<=-<=1 are not scheduled for repair of any car. So, the car of the *i*-th client will be repaired in the range [*x*,<=*x*<=+<=*d**i*<=-<=1]. It is possible that the day *x* when repair is scheduled to start will be less than *s**i*.
Given *n* requests, you are asked to help Polycarp schedule all of them according to the rules above.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=200) β the number of requests from clients.
The following *n* lines contain requests, one request per line. The *i*-th request is given as the pair of integers *s**i*,<=*d**i* (1<=β€<=*s**i*<=β€<=109, 1<=β€<=*d**i*<=β€<=5Β·106), where *s**i* is the preferred time to start repairing the *i*-th car, *d**i* is the number of days to repair the *i*-th car.
The requests should be processed in the order they are given in the input.
Output Specification:
Print *n* lines. The *i*-th line should contain two integers β the start day to repair the *i*-th car and the finish day to repair the *i*-th car.
Demo Input:
['3\n9 2\n7 3\n2 4\n', '4\n1000000000 1000000\n1000000000 1000000\n100000000 1000000\n1000000000 1000000\n']
Demo Output:
['9 10\n1 3\n4 7\n', '1000000000 1000999999\n1 1000000\n100000000 100999999\n1000001 2000000\n']
Note:
none | ```python
n = int(input())
l, r = [0] * n, [0] * n
f = lambda x, y: all(x > r[j] or y < l[j] for j in range(i))
for i in range(n):
x, d = map(int, input().split())
y = x + d - 1
if not f(x, y):
k = min(r[j] for j in range(i + 1) if f(r[j] + 1, r[j] + d))
x, y = k + 1, k + d
l[i], r[i] = x, y
print(x, y)
``` |
954 | Matrix Walk | Title: Matrix Walk
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is a matrix *A* of size *x*<=Γ<=*y* filled with integers. For every , *A**i*,<=*j*<==<=*y*(*i*<=-<=1)<=+<=*j*. Obviously, every integer from [1..*xy*] occurs exactly once in this matrix.
You have traversed some path in this matrix. Your path can be described as a sequence of visited cells *a*1, *a*2, ..., *a**n* denoting that you started in the cell containing the number *a*1, then moved to the cell with the number *a*2, and so on.
From the cell located in *i*-th line and *j*-th column (we denote this cell as (*i*,<=*j*)) you can move into one of the following cells:
1. (*i*<=+<=1,<=*j*) β only if *i*<=<<=*x*; 1. (*i*,<=*j*<=+<=1) β only if *j*<=<<=*y*; 1. (*i*<=-<=1,<=*j*) β only if *i*<=><=1; 1. (*i*,<=*j*<=-<=1) β only if *j*<=><=1.
Notice that making a move requires you to go to an adjacent cell. It is not allowed to stay in the same cell. You don't know *x* and *y* exactly, but you have to find any possible values for these numbers such that you could start in the cell containing the integer *a*1, then move to the cell containing *a*2 (in one step), then move to the cell containing *a*3 (also in one step) and so on. Can you choose *x* and *y* so that they don't contradict with your sequence of moves?
Input Specification:
The first line contains one integer number *n* (1<=β€<=*n*<=β€<=200000) β the number of cells you visited on your path (if some cell is visited twice, then it's listed twice).
The second line contains *n* integers *a*1, *a*2, ..., *a**n* (1<=β€<=*a**i*<=β€<=109) β the integers in the cells on your path.
Output Specification:
If all possible values of *x* and *y* such that 1<=β€<=*x*,<=*y*<=β€<=109 contradict with the information about your path, print NO.
Otherwise, print YES in the first line, and in the second line print the values *x* and *y* such that your path was possible with such number of lines and columns in the matrix. Remember that they must be positive integers not exceeding 109.
Demo Input:
['8\n1 2 3 6 9 8 5 2\n', '6\n1 2 1 2 5 3\n', '2\n1 10\n']
Demo Output:
['YES\n3 3\n', 'NO\n', 'YES\n4 9\n']
Note:
The matrix and the path on it in the first test looks like this:
Also there exist multiple correct answers for both the first and the third examples. | ```python
q=int(input())
l=list(map(int,input().split()))
w=set()
for i in range(1,q):
w.add(abs(l[i]-l[i-1]))
f=1
s=1000000000
if q==1:
print('YES')
print(s,f)
exit()
if 1 in w:
w.remove(1)
if len(w)>1:
print('NO')
exit()
elif 0 in w:
print('NO')
exit()
if len(w)==0:
print('YES')
print(s,f)
exit()
f=list(w)[0]
for i in range(1,q):
if l[i]-l[i-1]==1:
if l[i-1]%f==0:
print('NO')
exit()
elif l[i]-l[i-1]==-1:
if l[i-1]%f==1:
print('NO')
exit()
print('YES')
print(s,f)
``` |
883 | Field of Wonders | Title: Field of Wonders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarpus takes part in the "Field of Wonders" TV show. The participants of the show have to guess a hidden word as fast as possible. Initially all the letters of the word are hidden.
The game consists of several turns. At each turn the participant tells a letter and the TV show host responds if there is such letter in the word or not. If there is such letter then the host reveals all such letters. For example, if the hidden word is "abacaba" and the player tells the letter "a", the host will reveal letters at all positions, occupied by "a": 1, 3, 5 and 7 (positions are numbered from left to right starting from 1).
Polycarpus knows *m* words of exactly the same length as the hidden word. The hidden word is also known to him and appears as one of these *m* words.
At current moment a number of turns have already been made and some letters (possibly zero) of the hidden word are already revealed. Previously Polycarp has told exactly the letters which are currently revealed.
It is Polycarpus' turn. He wants to tell a letter in such a way, that the TV show host will assuredly reveal at least one more letter. Polycarpus cannot tell the letters, which are already revealed.
Your task is to help Polycarpus and find out the number of letters he can tell so that the show host will assuredly reveal at least one of the remaining letters.
Input Specification:
The first line contains one integer *n* (1<=β€<=*n*<=β€<=50) β the length of the hidden word.
The following line describes already revealed letters. It contains the string of length *n*, which consists of lowercase Latin letters and symbols "*". If there is a letter at some position, then this letter was already revealed. If the position contains symbol "*", then the letter at this position has not been revealed yet. It is guaranteed, that at least one letter is still closed.
The third line contains an integer *m* (1<=β€<=*m*<=β€<=1000) β the number of words of length *n*, which Polycarpus knows. The following *m* lines contain the words themselves β *n*-letter strings of lowercase Latin letters. All words are distinct.
It is guaranteed that the hidden word appears as one of the given *m* words. Before the current move Polycarp has told exactly the letters which are currently revealed.
Output Specification:
Output the single integer β the number of letters Polycarpus can tell so that the TV show host definitely reveals at least one more letter. It is possible that this number is zero.
Demo Input:
['4\na**d\n2\nabcd\nacbd\n', '5\nlo*er\n2\nlover\nloser\n', '3\na*a\n2\naaa\naba\n']
Demo Output:
['2\n', '0\n', '1\n']
Note:
In the first example Polycarpus can tell letters "b" and "c", which assuredly will be revealed.
The second example contains no letters which can be told as it is not clear, which of the letters "v" or "s" is located at the third position of the hidden word.
In the third example Polycarpus exactly knows that the hidden word is "aba", because in case it was "aaa", then the second letter "a" would have already been revealed in one of previous turns. | ```python
n = int(input())
s = input()
already = set()
for i in s:
if i != '*':
already.add(i)
ans = [chr(ord('a') + i) for i in range(26)]
ans = set(ans)
for i in range(int(input())):
cur = input()
can = True
clos = set() #should be closed
for j in range(n):
if s[j] == '*':
clos.add(cur[j])
elif s[j] != cur[j]:
can = False
break
if can:
if (already & clos) != set():
can = False
if can:
ans = (ans & clos)
print(len(ans))
``` |
985 | Chess Placing | Title: Chess Placing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a chessboard of size 1<=Γ<=*n*. It is guaranteed that *n* is even. The chessboard is painted like this: "BWBW...BW".
Some cells of the board are occupied by the chess pieces. Each cell contains no more than one chess piece. It is known that the total number of pieces equals to .
In one step you can move one of the pieces one cell to the left or to the right. You cannot move pieces beyond the borders of the board. You also cannot move pieces to the cells that are already occupied.
Your task is to place all the pieces in the cells of the same color using the minimum number of moves (all the pieces must occupy only the black cells or only the white cells after all the moves are made).
Input Specification:
The first line of the input contains one integer *n* (2<=β€<=*n*<=β€<=100, *n* is even) β the size of the chessboard.
The second line of the input contains integer numbers (1<=β€<=*p**i*<=β€<=*n*) β initial positions of the pieces. It is guaranteed that all the positions are distinct.
Output Specification:
Print one integer β the minimum number of moves you have to make to place all the pieces in the cells of the same color.
Demo Input:
['6\n1 2 6\n', '10\n1 2 3 4 5\n']
Demo Output:
['2\n', '10\n']
Note:
In the first example the only possible strategy is to move the piece at the position 6 to the position 5 and move the piece at the position 2 to the position 3. Notice that if you decide to place the pieces in the white cells the minimum number of moves will be 3.
In the second example the possible strategy is to move <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/e1e06f6a15cce30628c7a2360c4ffa57a8ba0ebd.png" style="max-width: 100.0%;max-height: 100.0%;"/> in 4 moves, then <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/c84dfbe0c6a917b45fc3f69467c256c4ac460eeb.png" style="max-width: 100.0%;max-height: 100.0%;"/> in 3 moves, <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/598731d81393332209d914cb0bbe97d8566c887d.png" style="max-width: 100.0%;max-height: 100.0%;"/> in 2 moves and <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/29f71c065c3536e88b54429c734103ad3604f68b.png" style="max-width: 100.0%;max-height: 100.0%;"/> in 1 move. | ```python
i1=int(input())
ar=list(map(int,input().split()))
sm1=0
sm2=0
ar.sort()
for i in range(1,i1,2):
sm2+=abs(i-ar[int(i/2)])
ar.sort(reverse=True)
for i in range(0,i1,2):
sm1+=abs(i1-i-ar[int(i/2)])
print(min(sm1,sm2))
``` |
838 | Airplane Arrangements | Title: Airplane Arrangements
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is an airplane which has *n* rows from front to back. There will be *m* people boarding this airplane.
This airplane has an entrance at the very front and very back of the plane.
Each person has some assigned seat. It is possible for multiple people to have the same assigned seat. The people will then board the plane one by one starting with person 1. Each person can independently choose either the front entrance or back entrance to enter the plane.
When a person walks into the plane, they walk directly to their assigned seat and will try to sit in it. If it is occupied, they will continue walking in the direction they walked in until they are at empty seat - they will take the earliest empty seat that they can find. If they get to the end of the row without finding a seat, they will be angry.
Find the number of ways to assign tickets to the passengers and board the plane without anyone getting angry. Two ways are different if there exists a passenger who chose a different entrance in both ways, or the assigned seat is different. Print this count modulo 109<=+<=7.
Input Specification:
The first line of input will contain two integers *n*,<=*m* (1<=β€<=*m*<=β€<=*n*<=β€<=1<=000<=000), the number of seats, and the number of passengers, respectively.
Output Specification:
Print a single number, the number of ways, modulo 109<=+<=7.
Demo Input:
['3 3\n']
Demo Output:
['128\n']
Note:
Here, we will denote a passenger by which seat they were assigned, and which side they came from (either "F" or "B" for front or back, respectively).
For example, one valid way is 3B, 3B, 3B (i.e. all passengers were assigned seat 3 and came from the back entrance). Another valid way would be 2F, 1B, 3F.
One invalid way would be 2B, 2B, 2B, since the third passenger would get to the front without finding a seat. | ```python
MOD = 10 ** 9 + 7
n, m = input().split(' ')
n = int(n)
m = int(m)
ans = pow(2 * (n + 1), m, MOD)
ans = (ans * (n + 1 - m)) % MOD
ans = (ans * pow(n + 1, MOD - 2, MOD)) % MOD
print(ans)
``` |
962 | Students in Railway Carriage | Title: Students in Railway Carriage
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ consecutive seat places in a railway carriage. Each place is either empty or occupied by a passenger.
The university team for the Olympiad consists of $a$ student-programmers and $b$ student-athletes. Determine the largest number of students from all $a+b$ students, which you can put in the railway carriage so that:
- no student-programmer is sitting next to the student-programmer; - and no student-athlete is sitting next to the student-athlete.
In the other words, there should not be two consecutive (adjacent) places where two student-athletes or two student-programmers are sitting.
Consider that initially occupied seat places are occupied by jury members (who obviously are not students at all).
Input Specification:
The first line contain three integers $n$, $a$ and $b$ ($1 \le n \le 2\cdot10^{5}$, $0 \le a, b \le 2\cdot10^{5}$, $a + b > 0$) β total number of seat places in the railway carriage, the number of student-programmers and the number of student-athletes.
The second line contains a string with length $n$, consisting of characters "." and "*". The dot means that the corresponding place is empty. The asterisk means that the corresponding place is occupied by the jury member.
Output Specification:
Print the largest number of students, which you can put in the railway carriage so that no student-programmer is sitting next to a student-programmer and no student-athlete is sitting next to a student-athlete.
Demo Input:
['5 1 1\n*...*\n', '6 2 3\n*...*.\n', '11 3 10\n.*....**.*.\n', '3 2 3\n***\n']
Demo Output:
['2\n', '4\n', '7\n', '0\n']
Note:
In the first example you can put all student, for example, in the following way: *.AB*
In the second example you can put four students, for example, in the following way: *BAB*B
In the third example you can put seven students, for example, in the following way: B*ABAB**A*B
The letter A means a student-programmer, and the letter B β student-athlete. | ```python
def main():
n, a, b = map(int, input().split())
line = input()
spaces = [len(e) for e in line.split('*') if e]
ca, cb = a, b
for e in spaces:
if e % 2 != 0:
if ca > cb:
cb -= e // 2
ca -= e - e // 2
else:
ca -= e // 2
cb -= e - e // 2
else:
ca -= e // 2
cb -= e // 2
ca = max(0, ca)
cb = max(0, cb)
print(a - ca + b - cb)
if __name__ == '__main__':
main()
``` |
797 | Minimal string | Title: Minimal string
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya recieved a gift of a string *s* with length up to 105 characters for his birthday. He took two more empty strings *t* and *u* and decided to play a game. This game has two possible moves:
- Extract the first character of *s* and append *t* with this character. - Extract the last character of *t* and append *u* with this character.
Petya wants to get strings *s* and *t* empty and string *u* lexicographically minimal.
You should write a program that will help Petya win the game.
Input Specification:
First line contains non-empty string *s* (1<=β€<=|*s*|<=β€<=105), consisting of lowercase English letters.
Output Specification:
Print resulting string *u*.
Demo Input:
['cab\n', 'acdb\n']
Demo Output:
['abc\n', 'abdc\n']
Note:
none | ```python
import math
import bisect
def getList(method=int):
return list(map(method, input().split()))
def getInt():
return int(input())
def hasGreater(c):
global mp
for k, v in mp.items():
if c > k and v:
return True
return False
s = [v for v in input()]
t = []
ans = ''
n = len(s)
mp = {chr(ord('a') + i): 0 for i in range(26)}
for v in s:
mp[v] += 1
for v in s:
if len(t):
while len(t) and not hasGreater(t[-1]):
ans += t.pop()
t.append(v)
mp[v] -= 1
while len(t):
ans += t.pop()
print(ans)
``` |
999 | Cards and Joy | Title: Cards and Joy
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ players sitting at the card table. Each player has a favorite number. The favorite number of the $j$-th player is $f_j$.
There are $k \cdot n$ cards on the table. Each card contains a single integer: the $i$-th card contains number $c_i$. Also, you are given a sequence $h_1, h_2, \dots, h_k$. Its meaning will be explained below.
The players have to distribute all the cards in such a way that each of them will hold exactly $k$ cards. After all the cards are distributed, each player counts the number of cards he has that contains his favorite number. The joy level of a player equals $h_t$ if the player holds $t$ cards containing his favorite number. If a player gets no cards with his favorite number (i.e., $t=0$), his joy level is $0$.
Print the maximum possible total joy levels of the players after the cards are distributed. Note that the sequence $h_1, \dots, h_k$ is the same for all the players.
Input Specification:
The first line of input contains two integers $n$ and $k$ ($1 \le n \le 500, 1 \le k \le 10$) β the number of players and the number of cards each player will get.
The second line contains $k \cdot n$ integers $c_1, c_2, \dots, c_{k \cdot n}$ ($1 \le c_i \le 10^5$) β the numbers written on the cards.
The third line contains $n$ integers $f_1, f_2, \dots, f_n$ ($1 \le f_j \le 10^5$) β the favorite numbers of the players.
The fourth line contains $k$ integers $h_1, h_2, \dots, h_k$ ($1 \le h_t \le 10^5$), where $h_t$ is the joy level of a player if he gets exactly $t$ cards with his favorite number written on them. It is guaranteed that the condition $h_{t - 1} < h_t$ holds for each $t \in [2..k]$.
Output Specification:
Print one integer β the maximum possible total joy levels of the players among all possible card distributions.
Demo Input:
['4 3\n1 3 2 8 5 5 8 2 2 8 5 2\n1 2 2 5\n2 6 7\n', '3 3\n9 9 9 9 9 9 9 9 9\n1 2 3\n1 2 3\n']
Demo Output:
['21\n', '0\n']
Note:
In the first example, one possible optimal card distribution is the following:
- Player $1$ gets cards with numbers $[1, 3, 8]$; - Player $2$ gets cards with numbers $[2, 2, 8]$; - Player $3$ gets cards with numbers $[2, 2, 8]$; - Player $4$ gets cards with numbers $[5, 5, 5]$.
Thus, the answer is $2 + 6 + 6 + 7 = 21$.
In the second example, no player can get a card with his favorite number. Thus, the answer is $0$. | ```python
def Solucion(n,k,c,f,h):
# La alegrΓa de no tener cartas favoritas es0
h = [0]+h
# Contamos la cantidad de veces que una carta es favorita por los jugadores
count_fav = {}
# Guardamos el mΓ‘ximo nΓΊmero de veces que se repite un nΓΊmero en los favoritos
max_count_fav = 0
for i in f:
if i in count_fav:
count_fav[i] += 1
else:
count_fav[i] = 1
if max_count_fav < count_fav[i]:
max_count_fav = count_fav[i]
# Contamos la cantidad de veces que la carta se encuentra en c
count_num = {}
# Guardamos el mΓ‘ximo nΓΊmero de veces que se repite un nΓΊmero en c
max_count_num = 0
for i in c:
# Si no es una de las posibles cartas favoritas no nos interesa
if i in f:
if i in count_num:
count_num[i] += 1
else:
count_num[i] = 1
if max_count_num < count_num[i]:
max_count_num = count_num[i]
# La idea es tener una matriz dp donde para dp[i][j] sea la mayor cantidad de alegrΓa que
# se obtiene de repartir j cartas favoritas a i jugadores con la misma carta favorita
# Los lΓmites de la matriz en las filas es
# la mΓ‘xima cantidad de cartas de un nΓΊmero que se puede repatir + 1
# y en las columnas la mΓ‘xima cantidad de jugadores a los que hay que repertirle la misma carta favorita + 1
dp = [[0]*(max_count_num+1) for _ in range(max_count_fav+1)]
for jugador in range(max_count_fav):
for card in range(max_count_num):
for repartir in range(k+1):
if card+repartir > max_count_num:
# no tiene sentido repartir mΓ‘s cartas de la cantidad mΓ‘xima a repartir
continue
# Se guarda para i(jugador+1) jugadores(1<max_count_fav) y la cantidad de cartas ya repartidas(card) +
# las que se reparte al jugador i(repartir) el mΓ‘ximo entre lo calculado hasta el momento y repartir
# a i-1 jugadores las cartas ya repartidas(card) mΓ‘s repartir las cartas(repartir) al jugador i
dp[jugador+1][card+repartir] = max(dp[jugador+1][card+repartir], dp[jugador][card] + h[repartir])
# Terminado de construir dp se procede a calcular la alegrΓa sabiendo que dp[i][j] sea la
# mayor cantidad de alegrΓa que se obtiene de repartir j cartas favoritas a i jugadores con
# la misma carta favorita, la suma de todas las alegrΓas para los grupos de jugadores que
# prefieren cartas diferentes es la alegrΓa mΓ‘xima
joy = 0
for i in count_num:
# Siempre sumamos la cantidad mΓ‘xima de repartir j cartas a i jugadores
joy += dp[count_fav[i]][count_num[i]]
return joy
# recogemos la entrada
n, k = map(int,input().split())
c = list(map(int,input().split()))
f = list(map(int,input().split()))
h = list(map(int,input().split()))
#imprimimos la soluciΓ³n
print(Solucion(n,k,c,f,h))
``` |
792 | New Bus Route | Title: New Bus Route
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* cities situated along the main road of Berland. Cities are represented by their coordinates β integer numbers *a*1,<=*a*2,<=...,<=*a**n*. All coordinates are pairwise distinct.
It is possible to get from one city to another only by bus. But all buses and roads are very old, so the Minister of Transport decided to build a new bus route. The Minister doesn't want to spend large amounts of money β he wants to choose two cities in such a way that the distance between them is minimal possible. The distance between two cities is equal to the absolute value of the difference between their coordinates.
It is possible that there are multiple pairs of cities with minimal possible distance, so the Minister wants to know the quantity of such pairs.
Your task is to write a program that will calculate the minimal possible distance between two pairs of cities and the quantity of pairs which have this distance.
Input Specification:
The first line contains one integer number *n* (2<=β€<=*n*<=β€<=2Β·105).
The second line contains *n* integer numbers *a*1,<=*a*2,<=...,<=*a**n* (<=-<=109<=β€<=*a**i*<=β€<=109). All numbers *a**i* are pairwise distinct.
Output Specification:
Print two integer numbers β the minimal distance and the quantity of pairs with this distance.
Demo Input:
['4\n6 -3 0 4\n', '3\n-2 0 2\n']
Demo Output:
['2 1\n', '2 2\n']
Note:
In the first example the distance between the first city and the fourth city is |4β-β6|β=β2, and it is the only pair with this distance. | ```python
n = int(input())
ar = list(map(int,input().split()))
ar.sort()
l = [abs(ar[i+1] - ar[i]) for i in range(0,n-1)]
k = min(l)
print(k,l.count(k),sep = ' ')
``` |
977 | Two-gram | Title: Two-gram
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" β three distinct two-grams.
You are given a string $s$ consisting of $n$ capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of the string) maximal number of times. For example, for string $s$ = "BBAABBBA" the answer is two-gram "BB", which contained in $s$ three times. In other words, find any most frequent two-gram.
Note that occurrences of the two-gram can overlap with each other.
Input Specification:
The first line of the input contains integer number $n$ ($2 \le n \le 100$) β the length of string $s$. The second line of the input contains the string $s$ consisting of $n$ capital Latin letters.
Output Specification:
Print the only line containing exactly two capital Latin letters β any two-gram contained in the given string $s$ as a substring (i.e. two consecutive characters of the string) maximal number of times.
Demo Input:
['7\nABACABA\n', '5\nZZZAA\n']
Demo Output:
['AB\n', 'ZZ\n']
Note:
In the first example "BA" is also valid answer.
In the second example the only two-gram "ZZ" can be printed because it contained in the string "ZZZAA" two times. | ```python
n = int(input())
s = input()
ans = 0
Find = ""
for i in range(n - 1):
c = 0
for j in range(n - 1):
if s[i] == s[j] and s[i + 1] == s[j + 1]:
c += 1
if ans < c:
ans = max(ans, c)
Find = s[i:i+2]
print(Find)
``` |
978 | Mentors | Title: Mentors
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
In BerSoft $n$ programmers work, the programmer $i$ is characterized by a skill $r_i$.
A programmer $a$ can be a mentor of a programmer $b$ if and only if the skill of the programmer $a$ is strictly greater than the skill of the programmer $b$ $(r_a > r_b)$ and programmers $a$ and $b$ are not in a quarrel.
You are given the skills of each programmers and a list of $k$ pairs of the programmers, which are in a quarrel (pairs are unordered). For each programmer $i$, find the number of programmers, for which the programmer $i$ can be a mentor.
Input Specification:
The first line contains two integers $n$ and $k$ $(2 \le n \le 2 \cdot 10^5$, $0 \le k \le \min(2 \cdot 10^5, \frac{n \cdot (n - 1)}{2}))$ β total number of programmers and number of pairs of programmers which are in a quarrel.
The second line contains a sequence of integers $r_1, r_2, \dots, r_n$ $(1 \le r_i \le 10^{9})$, where $r_i$ equals to the skill of the $i$-th programmer.
Each of the following $k$ lines contains two distinct integers $x$, $y$ $(1 \le x, y \le n$, $x \ne y)$ β pair of programmers in a quarrel. The pairs are unordered, it means that if $x$ is in a quarrel with $y$ then $y$ is in a quarrel with $x$. Guaranteed, that for each pair $(x, y)$ there are no other pairs $(x, y)$ and $(y, x)$ in the input.
Output Specification:
Print $n$ integers, the $i$-th number should be equal to the number of programmers, for which the $i$-th programmer can be a mentor. Programmers are numbered in the same order that their skills are given in the input.
Demo Input:
['4 2\n10 4 10 15\n1 2\n4 3\n', '10 4\n5 4 1 5 4 3 7 1 2 5\n4 6\n2 1\n10 8\n3 5\n']
Demo Output:
['0 0 1 2 \n', '5 4 0 5 3 3 9 0 2 5 \n']
Note:
In the first example, the first programmer can not be mentor of any other (because only the second programmer has a skill, lower than first programmer skill, but they are in a quarrel). The second programmer can not be mentor of any other programmer, because his skill is minimal among others. The third programmer can be a mentor of the second programmer. The fourth programmer can be a mentor of the first and of the second programmers. He can not be a mentor of the third programmer, because they are in a quarrel. | ```python
import sys
input = lambda: sys.stdin.readline().rstrip()
from bisect import *
N,K = map(int, input().split())
R = list(map(int, input().split()))
A = sorted(R)
P = [[] for _ in range(N)]
for _ in range(K):
u,v = map(int, input().split())
u-=1;v-=1
P[u].append(R[v])
P[v].append(R[u])
ans = []
for i in range(N):
p = P[i]
p.sort()
idx = bisect_left(p, R[i])
tmp = bisect_left(A, R[i])
ans.append(tmp-idx)
print(*ans)
``` |
846 | Chemistry in Berland | Title: Chemistry in Berland
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Igor is a post-graduate student of chemistry faculty in Berland State University (BerSU). He needs to conduct a complicated experiment to write his thesis, but laboratory of BerSU doesn't contain all the materials required for this experiment.
Fortunately, chemical laws allow material transformations (yes, chemistry in Berland differs from ours). But the rules of transformation are a bit strange.
Berland chemists are aware of *n* materials, numbered in the order they were discovered. Each material can be transformed into some other material (or vice versa). Formally, for each *i* (2<=β€<=*i*<=β€<=*n*) there exist two numbers *x**i* and *k**i* that denote a possible transformation: *k**i* kilograms of material *x**i* can be transformed into 1 kilogram of material *i*, and 1 kilogram of material *i* can be transformed into 1 kilogram of material *x**i*. Chemical processing equipment in BerSU allows only such transformation that the amount of resulting material is always an integer number of kilograms.
For each *i* (1<=β€<=*i*<=β€<=*n*) Igor knows that the experiment requires *a**i* kilograms of material *i*, and the laboratory contains *b**i* kilograms of this material. Is it possible to conduct an experiment after transforming some materials (or none)?
Input Specification:
The first line contains one integer number *n* (1<=β€<=*n*<=β€<=105) β the number of materials discovered by Berland chemists.
The second line contains *n* integer numbers *b*1,<=*b*2... *b**n* (1<=β€<=*b**i*<=β€<=1012) β supplies of BerSU laboratory.
The third line contains *n* integer numbers *a*1,<=*a*2... *a**n* (1<=β€<=*a**i*<=β€<=1012) β the amounts required for the experiment.
Then *n*<=-<=1 lines follow. *j*-th of them contains two numbers *x**j*<=+<=1 and *k**j*<=+<=1 that denote transformation of (*j*<=+<=1)-th material (1<=β€<=*x**j*<=+<=1<=β€<=*j*,<=1<=β€<=*k**j*<=+<=1<=β€<=109).
Output Specification:
Print YES if it is possible to conduct an experiment. Otherwise print NO.
Demo Input:
['3\n1 2 3\n3 2 1\n1 1\n1 1\n', '3\n3 2 1\n1 2 3\n1 1\n1 2\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
import sys
input = sys.stdin.readline
n = int(input())
b = [0] + list(map(int, input().split()))
a = [0] + list(map(int, input().split()))
G = [[] for _ in range(n + 1)]
x0, k0 = [0] * (n + 1), [0] * (n + 1)
for y in range(2, n + 1):
x, k = map(int, input().split())
G[x].append((y, k))
x0[y] = x
k0[y] = k
dp = [0] * (n + 1)
inf = pow(2, 63)
for i in range(n, 0, -1):
c = b[i] - a[i]
s = 0
for j, k in G[i]:
s += k * dp[j]
if s > inf:
ans = "NO"
print(ans)
exit()
c0 = max(0, min(c, s))
s -= c0
b[i] -= c0
dp[i] = s + max(a[i] - b[i], 0)
c = b[i] - a[i]
if c > 0 and i > 1:
b[x0[i]] += c
ans = "YES" if not dp[1] else "NO"
print(ans)
``` |
958 | Maximum Control (easy) | Title: Maximum Control (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Resistance is trying to take control over all planets in a particular solar system. This solar system is shaped like a tree. More precisely, some planets are connected by bidirectional hyperspace tunnels in such a way that there is a path between every pair of the planets, but removing any tunnel would disconnect some of them.
The Resistance already has measures in place that will, when the time is right, enable them to control every planet that is not remote. A planet is considered to be remote if it is connected to the rest of the planets only via a single hyperspace tunnel.
How much work is there left to be done: that is, how many remote planets are there?
Input Specification:
The first line of the input contains an integer *N* (2<=β€<=*N*<=β€<=1000) β the number of planets in the galaxy.
The next *N*<=-<=1 lines describe the hyperspace tunnels between the planets. Each of the *N*<=-<=1 lines contains two space-separated integers *u* and *v* (1<=β€<=*u*,<=*v*<=β€<=*N*) indicating that there is a bidirectional hyperspace tunnel between the planets *u* and *v*. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output Specification:
A single integer denoting the number of remote planets.
Demo Input:
['5\n4 1\n4 2\n1 3\n1 5\n', '4\n1 2\n4 3\n1 4\n']
Demo Output:
['3\n', '2\n']
Note:
In the first example, only planets 2, 3 and 5 are connected by a single tunnel.
In the second example, the remote planets are 2 and 3.
Note that this problem has only two versions β easy and medium. | ```python
n = int(input())
counter = 0
a = [[0 for j in range(n)] for i in range(n)]
for i in range(n - 1):
i, j = map(int, input().split())
a[i - 1][j - 1] = 1
a[j - 1][i - 1] = 1
for element in a:
if element.count(1) == 1:
counter += 1
print(counter)
``` |
656 | You're a Professional | Title: You're a Professional
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A simple recommendation system would recommend a user things liked by a certain number of their friends. In this problem you will implement part of such a system.
You are given user's friends' opinions about a list of items. You are also given a threshold *T* β the minimal number of "likes" necessary for an item to be recommended to the user.
Output the number of items in the list liked by at least *T* of user's friends.
Input Specification:
The first line of the input will contain three space-separated integers: the number of friends *F* (1<=β€<=*F*<=β€<=10), the number of items *I* (1<=β€<=*I*<=β€<=10) and the threshold *T* (1<=β€<=*T*<=β€<=*F*).
The following *F* lines of input contain user's friends' opinions. *j*-th character of *i*-th line is 'Y' if *i*-th friend likes *j*-th item, and 'N' otherwise.
Output Specification:
Output an integer β the number of items liked by at least *T* of user's friends.
Demo Input:
['3 3 2\nYYY\nNNN\nYNY\n', '4 4 1\nNNNY\nNNYN\nNYNN\nYNNN\n']
Demo Output:
['2\n', '4\n']
Note:
none | ```python
n,kitten,t= map(int, input().split())
a=[str(input()) for i in range(n)]
q=0
for i in range(kitten):
l=0
for j in range(n):
if (a[j][i]=="Y"):
l+=1
if (l >= t):
q+=1
print(q)
``` |
632 | Alice, Bob, Two Teams | Title: Alice, Bob, Two Teams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice and Bob are playing a game. The game involves splitting up game pieces into two teams. There are *n* pieces, and the *i*-th piece has a strength *p**i*.
The way to split up game pieces is split into several steps:
1. First, Alice will split the pieces into two different groups *A* and *B*. This can be seen as writing the assignment of teams of a piece in an *n* character string, where each character is *A* or *B*. 1. Bob will then choose an arbitrary prefix or suffix of the string, and flip each character in that suffix (i.e. change *A* to *B* and *B* to *A*). He can do this step at most once. 1. Alice will get all the pieces marked *A* and Bob will get all the pieces marked *B*.
The strength of a player is then the sum of strengths of the pieces in the group.
Given Alice's initial split into two teams, help Bob determine an optimal strategy. Return the maximum strength he can achieve.
Input Specification:
The first line contains integer *n* (1<=β€<=*n*<=β€<=5Β·105) β the number of game pieces.
The second line contains *n* integers *p**i* (1<=β€<=*p**i*<=β€<=109) β the strength of the *i*-th piece.
The third line contains *n* characters *A* or *B* β the assignment of teams after the first step (after Alice's step).
Output Specification:
Print the only integer *a* β the maximum strength Bob can achieve.
Demo Input:
['5\n1 2 3 4 5\nABABA\n', '5\n1 2 3 4 5\nAAAAA\n', '1\n1\nB\n']
Demo Output:
['11\n', '15\n', '1\n']
Note:
In the first sample Bob should flip the suffix of length one.
In the second sample Bob should flip the prefix or the suffix (here it is the same) of length 5.
In the third sample Bob should do nothing. | ```python
n, p = int( input() ) + 1, [0] + list( map( int, input().split() ) )
s = '_' + input()
ans = sum( p[i] for i in range(n) if s[i] == 'B' )
f1 = [0]
for i in range(1, n):
f1.append(f1[-1] + ( 0 if s[i] == 'A' else p[i] ))
f1 += [0]
f2 = [0]
for i in reversed(range(1, n)):
f2.append(f2[-1] + ( 0 if s[i] == 'A' else p[i] ) )
f2 += [0]
f2.reverse()
ac = 0
for i in range(1, n):
if s[i] == 'A': ac += p[i]
ans = max(ans, ac + f2[i + 1])
ac = 0
for i in reversed( range(1, n) ):
if s[i] == 'A': ac += p[i]
ans = max(ans, ac + f1[i - 1])
print(ans)
``` |
171 | MYSTERIOUS LANGUAGE | Title: MYSTERIOUS LANGUAGE
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a mysterious language (codenamed "Secret") available in "Custom Test" tab. Find out what this language is and write a program which outputs its name. Note that the program must be written in this language.
Input Specification:
This program has only one test, and it's empty (it doesn't give your program anything to read).
Output Specification:
Output the name of the mysterious language.
Note:
none | ```python
print("INTERCAL");
``` |
863 | Turn Off The TV | Title: Turn Off The TV
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luba needs your help again! Luba has *n* TV sets. She knows that *i*-th TV set will be working from moment of time *l**i* till moment *r**i*, inclusive.
Luba wants to switch off one of TV sets in order to free the socket. Let's call some TV set redundant if after switching it off the number of integer moments of time when at least one of TV sets is working won't decrease. Luba will be very upset if she has to switch off a non-redundant TV set.
Help Luba by telling her the index of some redundant TV set. If there is no any, print -1.
Input Specification:
The first line contains one integer number *n*Β (1<=β€<=*n*<=β€<=2Β·105) β the number of TV sets.
Then *n* lines follow, each of them containing two integer numbers *l**i*,<=*r**i*Β (0<=β€<=*l**i*<=β€<=*r**i*<=β€<=109) denoting the working time of *i*-th TV set.
Output Specification:
If there is no any redundant TV set, print -1. Otherwise print the index of any redundant TV set (TV sets are indexed from 1 to *n*).
If there are multiple answers, print any of them.
Demo Input:
['3\n1 3\n4 6\n1 7\n', '2\n0 10\n0 10\n', '3\n1 2\n3 4\n6 8\n', '3\n1 2\n2 3\n3 4\n']
Demo Output:
['1\n', '1\n', '-1\n', '2\n']
Note:
Consider the first sample. Initially all integer moments of time such that at least one TV set is working are from the segment [1;7]. It's easy to see that this segment won't change if we switch off the first TV set (or the second one).
Note that in the fourth sample you can switch off the second TV set, since even without it all integer moments such that any of the TV sets is working denote the segment [1;4]. | ```python
n = int(input())
lis = []
for i in range(n):
a, b = map(int, input().split())
lis.append([a, b, i+1])
lis.sort()
i = 1
ans = -1
#Turn off the TV
while i<n:
if lis[i][1]<=lis[i-1][1]:
ans = lis[i][2]
print(ans)
exit(0)
elif( lis[i][0] <= lis[i-1][0] and lis[i][1] >= lis[i-1][1]):
ans = lis[i-1][2]
print(ans)
exit(0)
lis[i][0] = max( lis[i][0], lis[i-1][1] + 1)
i+=1
print(ans)
``` |
915 | Browser | Title: Browser
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Luba is surfing the Internet. She currently has *n* opened tabs in her browser, indexed from 1 to *n* from left to right. The mouse cursor is currently located at the *pos*-th tab. Luba needs to use the tabs with indices from *l* to *r* (inclusive) for her studies, and she wants to close all the tabs that don't belong to this segment as fast as possible.
Each second Luba can either try moving the cursor to the left or to the right (if the cursor is currently at the tab *i*, then she can move it to the tab *max*(*i*<=-<=1,<=*a*) or to the tab *min*(*i*<=+<=1,<=*b*)) or try closing all the tabs to the left or to the right of the cursor (if the cursor is currently at the tab *i*, she can close all the tabs with indices from segment [*a*,<=*i*<=-<=1] or from segment [*i*<=+<=1,<=*b*]). In the aforementioned expressions *a* and *b* denote the minimum and maximum index of an unclosed tab, respectively. For example, if there were 7 tabs initially and tabs 1, 2 and 7 are closed, then *a*<==<=3, *b*<==<=6.
What is the minimum number of seconds Luba has to spend in order to leave only the tabs with initial indices from *l* to *r* inclusive opened?
Input Specification:
The only line of input contains four integer numbers *n*, *pos*, *l*, *r* (1<=β€<=*n*<=β€<=100, 1<=β€<=*pos*<=β€<=*n*, 1<=β€<=*l*<=β€<=*r*<=β€<=*n*) β the number of the tabs, the cursor position and the segment which Luba needs to leave opened.
Output Specification:
Print one integer equal to the minimum number of seconds required to close all the tabs outside the segment [*l*,<=*r*].
Demo Input:
['6 3 2 4\n', '6 3 1 3\n', '5 2 1 5\n']
Demo Output:
['5\n', '1\n', '0\n']
Note:
In the first test Luba can do the following operations: shift the mouse cursor to the tab 2, close all the tabs to the left of it, shift the mouse cursor to the tab 3, then to the tab 4, and then close all the tabs to the right of it.
In the second test she only needs to close all the tabs to the right of the current position of the cursor.
In the third test Luba doesn't need to do anything. | ```python
n,pos,l,r=[int(i) for i in input().split()]
if l==1 and r==n:
print(0)
elif l==1 and r!=n:
print(abs(pos-r)+1)
elif l!=1 and r==n:
print(abs(pos-l)+1)
else:
print(r-l+min(abs(pos-l),abs(pos-r))+2)
``` |
710 | Magic Odd Square | Title: Magic Odd Square
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Find an *n*<=Γ<=*n* matrix with different numbers from 1 to *n*2, so the sum in each row, column and both main diagonals are odd.
Input Specification:
The only line contains odd integer *n* (1<=β€<=*n*<=β€<=49).
Output Specification:
Print *n* lines with *n* integers. All the integers should be different and from 1 to *n*2. The sum in each row, column and both main diagonals should be odd.
Demo Input:
['1\n', '3\n']
Demo Output:
['1\n', '2 1 4\n3 5 7\n6 9 8\n']
Note:
none | ```python
n = int(input())
c, o, e = n // 2, 1, 2
for i in range(n):
for j in range(n):
if abs(i - c) + abs(j - c) <= c:
print(o, end=" ")
o += 2
else:
print(e, end=" ")
e += 2
print("")
``` |
863 | Almost Permutation | Title: Almost Permutation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Recently Ivan noticed an array *a* while debugging his code. Now Ivan can't remember this array, but the bug he was trying to fix didn't go away, so Ivan thinks that the data from this array might help him to reproduce the bug.
Ivan clearly remembers that there were *n* elements in the array, and each element was not less than 1 and not greater than *n*. Also he remembers *q* facts about the array. There are two types of facts that Ivan remembers:
- 1 *l**i* *r**i* *v**i* β for each *x* such that *l**i*<=β€<=*x*<=β€<=*r**i* *a**x*<=β₯<=*v**i*; - 2 *l**i* *r**i* *v**i* β for each *x* such that *l**i*<=β€<=*x*<=β€<=*r**i* *a**x*<=β€<=*v**i*.
Also Ivan thinks that this array was a permutation, but he is not so sure about it. He wants to restore some array that corresponds to the *q* facts that he remembers and is very similar to permutation. Formally, Ivan has denoted the *cost* of array as follows:
, where *cnt*(*i*) is the number of occurences of *i* in the array.
Help Ivan to determine minimum possible *cost* of the array that corresponds to the facts!
Input Specification:
The first line contains two integer numbers *n* and *q* (1<=β€<=*n*<=β€<=50, 0<=β€<=*q*<=β€<=100).
Then *q* lines follow, each representing a fact about the array. *i*-th line contains the numbers *t**i*, *l**i*, *r**i* and *v**i* for *i*-th fact (1<=β€<=*t**i*<=β€<=2, 1<=β€<=*l**i*<=β€<=*r**i*<=β€<=*n*, 1<=β€<=*v**i*<=β€<=*n*, *t**i* denotes the type of the fact).
Output Specification:
If the facts are controversial and there is no array that corresponds to them, print -1. Otherwise, print minimum possible *cost* of the array.
Demo Input:
['3 0\n', '3 1\n1 1 3 2\n', '3 2\n1 1 3 2\n2 1 3 2\n', '3 2\n1 1 3 2\n2 1 3 1\n']
Demo Output:
['3\n', '5\n', '9\n', '-1\n']
Note:
none | ```python
#~ # MAGIC CODEFORCES PYTHON FAST IO
import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
#~ # END OF MAGIC CODEFORCES PYTHON FAST IO
class Arista():
def __init__(self,salida,llegada,capacidad,flujo,costo,indice):
self.salida = salida
self.llegada = llegada
self.capacidad = capacidad
self.flujo = flujo
self.costo = costo
self.indice = indice
def __str__(self):
s = ""
s = s + "salida =" + str(self.salida) + "\n"
s = s + "llegada =" + str(self.llegada) + "\n"
s = s + "capacidad =" + str(self.capacidad) + "\n"
s = s + "flujo =" + str(self.flujo) + "\n"
s = s + "costo =" + str(self.costo) + "\n"
s = s + "indice =" + str(self.indice) + "\n"
s = s + "------------"
return s
class Red():
## Representacion de una Red de flujo ##
def __init__(self,s,t): # Crea una red vacio
self.lista_aristas = []
self.lista_adyacencia = {}
self.vertices = set()
self.fuente = s
self.sumidero = t
def agregar_vertice(self,vertice):
self.vertices.add(vertice)
def agregar_arista(self,arista):
self.vertices.add(arista.salida)
self.vertices.add(arista.llegada)
self.lista_aristas.append(arista)
if arista.salida not in self.lista_adyacencia:
self.lista_adyacencia[arista.salida] = set()
self.lista_adyacencia[arista.salida].add(arista.indice)
def agregar_lista_aristas(self,lista_aristas):
for arista in lista_aristas:
self.agregar_arista(arista)
def cantidad_de_vertices(self):
return len(self.vertices)
def vecinos(self,vertice):
if vertice not in self.lista_adyacencia:
return set()
else:
return self.lista_adyacencia[vertice]
def buscar_valor_critico(self,padre):
INFINITO = 1000000000
valor_critico = INFINITO
actual = self.sumidero
while actual != self.fuente:
arista_camino = self.lista_aristas[padre[actual]]
valor_critico = min(valor_critico,arista_camino.capacidad - arista_camino.flujo)
actual = arista_camino.salida
return valor_critico
def actualizar_camino(self,padre,valor_critico):
actual = self.sumidero
costo_actual = 0
while actual != self.fuente:
self.lista_aristas[padre[actual]].flujo += valor_critico
self.lista_aristas[padre[actual]^1].flujo -= valor_critico
costo_actual += valor_critico*self.lista_aristas[padre[actual]].costo
actual = self.lista_aristas[padre[actual]].salida
return costo_actual,True
def camino_de_aumento(self):
INFINITO = 1000000000
distancia = {v:INFINITO for v in self.vertices}
padre = {v:-1 for v in self.vertices}
distancia[self.fuente] = 0
#~ for iteracion in range(len(self.vertices)-1):
#~ for arista in self.lista_aristas:
#~ if arista.flujo < arista.capacidad and distancia[arista.salida] + arista.costo < distancia[arista.llegada]:
#~ distancia[arista.llegada] = distancia[arista.salida] + arista.costo
#~ padre[arista.llegada] = arista.indice
capa_actual,capa_nueva = set([self.fuente]),set()
while capa_actual:
for v in capa_actual:
for arista_indice in self.vecinos(v):
arista = self.lista_aristas[arista_indice]
if arista.flujo < arista.capacidad and distancia[arista.salida] + arista.costo < distancia[arista.llegada]:
distancia[arista.llegada] = distancia[arista.salida] + arista.costo
padre[arista.llegada] = arista.indice
capa_nueva.add(arista.llegada)
capa_actual = set()
capa_actual,capa_nueva = capa_nueva,capa_actual
if distancia[self.sumidero] < INFINITO:
valor_critico = self.buscar_valor_critico(padre)
costo_actual,hay_camino = self.actualizar_camino(padre,valor_critico)
return valor_critico,costo_actual,hay_camino
else:
return -1,-1,False
def max_flow_min_cost(self):
flujo_total = 0
costo_total = 0
hay_camino = True
while hay_camino:
#~ for x in self.lista_aristas:
#~ print(x)
flujo_actual,costo_actual,hay_camino = self.camino_de_aumento()
if hay_camino:
flujo_total += flujo_actual
costo_total += costo_actual
return flujo_total,costo_total
INFINITO = 10000000000000
n,q = map(int,input().split())
maxi = [n for i in range(n)]
mini = [1 for i in range(n)]
R = Red(0,2*n+1)
prohibidos = {i:set() for i in range(n)}
for i in range(n):
for k in range(n+1):
R.agregar_arista(Arista(R.fuente,i+1,1,0,2*k+1,len(R.lista_aristas)))
R.agregar_arista(Arista(i+1,R.fuente,0,0,-2*k-1,len(R.lista_aristas)))
for j in range(n):
R.agregar_arista(Arista(n+j+1,R.sumidero,1,0,0,len(R.lista_aristas)))
R.agregar_arista(Arista(R.sumidero,n+j+1,0,0,0,len(R.lista_aristas)))
for z in range(q):
t,l,r,v = map(int,input().split())
if t == 1:
for i in range(v-1):
for j in range(l,r+1):
prohibidos[i].add(j)
else:
for i in range(v,n):
for j in range(l,r+1):
prohibidos[i].add(j)
for i in range(n):
for j in range(mini[i],maxi[i]+1):
if j not in prohibidos[i]:
R.agregar_arista(Arista(i+1,n+j,1,0,0,len(R.lista_aristas)))
R.agregar_arista(Arista(n+j,i+1,0,0,0,len(R.lista_aristas)))
flujo_total,costo_total = R.max_flow_min_cost()
#~ print(flujo_total,costo_total)
if flujo_total < n:
print("-1")
else:
print(costo_total)
``` |
1,006 | Two Strings Swaps | Title: Two Strings Swaps
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two strings $a$ and $b$ consisting of lowercase English letters, both of length $n$. The characters of both strings have indices from $1$ to $n$, inclusive.
You are allowed to do the following changes:
- Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $b_i$; - Choose any index $i$ ($1 \le i \le n$) and swap characters $a_i$ and $a_{n - i + 1}$; - Choose any index $i$ ($1 \le i \le n$) and swap characters $b_i$ and $b_{n - i + 1}$.
Note that if $n$ is odd, you are formally allowed to swap $a_{\lceil\frac{n}{2}\rceil}$ with $a_{\lceil\frac{n}{2}\rceil}$ (and the same with the string $b$) but this move is useless. Also you can swap two equal characters but this operation is useless as well.
You have to make these strings equal by applying any number of changes described above, in any order. But it is obvious that it may be impossible to make two strings equal by these swaps.
In one preprocess move you can replace a character in $a$ with another character. In other words, in a single preprocess move you can choose any index $i$ ($1 \le i \le n$), any character $c$ and set $a_i := c$.
Your task is to find the minimum number of preprocess moves to apply in such a way that after them you can make strings $a$ and $b$ equal by applying some number of changes described in the list above.
Note that the number of changes you make after the preprocess moves does not matter. Also note that you cannot apply preprocess moves to the string $b$ or make any preprocess moves after the first change is made.
Input Specification:
The first line of the input contains one integer $n$ ($1 \le n \le 10^5$) β the length of strings $a$ and $b$.
The second line contains the string $a$ consisting of exactly $n$ lowercase English letters.
The third line contains the string $b$ consisting of exactly $n$ lowercase English letters.
Output Specification:
Print a single integer β the minimum number of preprocess moves to apply before changes, so that it is possible to make the string $a$ equal to string $b$ with a sequence of changes from the list above.
Demo Input:
['7\nabacaba\nbacabaa\n', '5\nzcabd\ndbacz\n']
Demo Output:
['4\n', '0\n']
Note:
In the first example preprocess moves are as follows: $a_1 := $'b', $a_3 := $'c', $a_4 := $'a' and $a_5:=$'b'. Afterwards, $a = $"bbcabba". Then we can obtain equal strings by the following sequence of changes: $swap(a_2, b_2)$ and $swap(a_2, a_6)$. There is no way to use fewer than $4$ preprocess moves before a sequence of changes to make string equal, so the answer in this example is $4$.
In the second example no preprocess moves are required. We can use the following sequence of changes to make $a$ and $b$ equal: $swap(b_1, b_5)$, $swap(a_2, a_4)$. | ```python
n=int(input())
a=input()
b=input()
ans=0
for i in range(n//2):
seen=set()
if b[i]==b[n-i-1]:
if a[i]==a[n-i-1]:
ans+=0
else:
ans+=1
else :
seen.add(b[i])
if b[n-i-1] in seen:
seen.remove(b[n-i-1])
else :
seen.add(b[n-i-1])
if a[i] in seen:
seen.remove(a[i])
else :
ans+=1
if a[n-1-i] in seen:
seen.remove(a[n-i-1])
else :
ans+=1
if n%2:
if a[n//2]!=b[n//2]:
ans+=1
print(ans)
``` |
4 | Before an Exam | Title: Before an Exam
Time Limit: 0 seconds
Memory Limit: 64 megabytes
Problem Description:
Tomorrow Peter has a Biology exam. He does not like this subject much, but *d* days ago he learnt that he would have to take this exam. Peter's strict parents made him prepare for the exam immediately, for this purpose he has to study not less than *minTime**i* and not more than *maxTime**i* hours per each *i*-th day. Moreover, they warned Peter that a day before the exam they would check how he has followed their instructions.
So, today is the day when Peter's parents ask him to show the timetable of his preparatory studies. But the boy has counted only the sum of hours *sumTime* spent him on preparation, and now he wants to know if he can show his parents a timetable *sΡhedule* with *d* numbers, where each number *sΡhedule**i* stands for the time in hours spent by Peter each *i*-th day on biology studies, and satisfying the limitations imposed by his parents, and at the same time the sum total of all *schedule**i* should equal to *sumTime*.
Input Specification:
The first input line contains two integer numbers *d*,<=*sumTime* (1<=β€<=*d*<=β€<=30,<=0<=β€<=*sumTime*<=β€<=240) β the amount of days, during which Peter studied, and the total amount of hours, spent on preparation. Each of the following *d* lines contains two integer numbers *minTime**i*,<=*maxTime**i* (0<=β€<=*minTime**i*<=β€<=*maxTime**i*<=β€<=8), separated by a space β minimum and maximum amount of hours that Peter could spent in the *i*-th day.
Output Specification:
In the first line print YES, and in the second line print *d* numbers (separated by a space), each of the numbers β amount of hours, spent by Peter on preparation in the corresponding day, if he followed his parents' instructions; or print NO in the unique line. If there are many solutions, print any of them.
Demo Input:
['1 48\n5 7\n', '2 5\n0 1\n3 5\n']
Demo Output:
['NO\n', 'YES\n1 4 ']
Note:
none | ```python
d, time = map(int, input().split())
minTime = []
maxTime = []
for i in range(d):
mn, mx = map(int, input().split())
minTime.append(mn)
maxTime.append(mx)
minSum = sum(minTime)
maxSum = sum(maxTime)
if minSum <= time <= maxSum:
print("YES")
for i in range(d):
temp = min(minTime[i] + time - minSum, maxTime[i])
print(temp, end = " " if i < d - 1 else "\n")
time -= (temp - minTime[i])
else:
print("NO")
``` |
774 | Stepan and Vowels | Title: Stepan and Vowels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Stepan likes to repeat vowel letters when he writes words. For example, instead of the word "pobeda" he can write "pobeeeedaaaaa".
Sergey does not like such behavior, so he wants to write a program to format the words written by Stepan. This program must combine all consecutive equal vowels to a single vowel. The vowel letters are "a", "e", "i", "o", "u" and "y".
There are exceptions: if letters "e" or "o" repeat in a row exactly 2 times, like in words "feet" and "foot", the program must skip them and do not transform in one vowel. For example, the word "iiiimpleeemeentatiioon" must be converted to the word "implemeentatioon".
Sergey is very busy and asks you to help him and write the required program.
Input Specification:
The first line contains the integer *n* (1<=β€<=*n*<=β€<=100<=000) β the number of letters in the word written by Stepan.
The second line contains the string *s* which has length that equals to *n* and contains only lowercase English letters β the word written by Stepan.
Output Specification:
Print the single string β the word written by Stepan converted according to the rules described in the statement.
Demo Input:
['13\npobeeeedaaaaa\n', '22\niiiimpleeemeentatiioon\n', '18\naeiouyaaeeiioouuyy\n', '24\naaaoooiiiuuuyyyeeeggghhh\n']
Demo Output:
['pobeda\n', 'implemeentatioon\n', 'aeiouyaeeioouy\n', 'aoiuyeggghhh\n']
Note:
none | ```python
n = int(input())
st = input()
last = '-'
ans = ""
k = 0
st += '+';
for it in st:
if it != last:
if last == 'a' or last == 'i' or last == 'u' or last == 'y':
ans += last;
elif last == 'e' or last == 'o':
if k == 2:
ans += last + last
else:
ans += last
elif last != '-':
for j in range(k):
ans += last
last = it
k = 1
else:
k += 1
print(ans)
``` |
792 | Paths in a Complete Binary Tree | Title: Paths in a Complete Binary Tree
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*T* is a complete binary tree consisting of *n* vertices. It means that exactly one vertex is a root, and each vertex is either a leaf (and doesn't have children) or an inner node (and has exactly two children). All leaves of a complete binary tree have the same depth (distance from the root). So *n* is a number such that *n*<=+<=1 is a power of 2.
In the picture you can see a complete binary tree with *n*<==<=15.
Vertices are numbered from 1 to *n* in a special recursive way: we recursively assign numbers to all vertices from the left subtree (if current vertex is not a leaf), then assign a number to the current vertex, and then recursively assign numbers to all vertices from the right subtree (if it exists). In the picture vertices are numbered exactly using this algorithm. It is clear that for each size of a complete binary tree exists exactly one way to give numbers to all vertices. This way of numbering is called symmetric.
You have to write a program that for given *n* answers *q* queries to the tree.
Each query consists of an integer number *u**i* (1<=β€<=*u**i*<=β€<=*n*) and a string *s**i*, where *u**i* is the number of vertex, and *s**i* represents the path starting from this vertex. String *s**i* doesn't contain any characters other than 'L', 'R' and 'U', which mean traverse to the left child, to the right child and to the parent, respectively. Characters from *s**i* have to be processed from left to right, considering that *u**i* is the vertex where the path starts. If it's impossible to process a character (for example, to go to the left child of a leaf), then you have to skip it. The answer is the number of vertex where the path represented by *s**i* ends.
For example, if *u**i*<==<=4 and *s**i*<==<=Β«UURLΒ», then the answer is 10.
Input Specification:
The first line contains two integer numbers *n* and *q* (1<=β€<=*n*<=β€<=1018, *q*<=β₯<=1). *n* is such that *n*<=+<=1 is a power of 2.
The next 2*q* lines represent queries; each query consists of two consecutive lines. The first of these two lines contains *u**i* (1<=β€<=*u**i*<=β€<=*n*), the second contains non-empty string *s**i*. *s**i* doesn't contain any characters other than 'L', 'R' and 'U'.
It is guaranteed that the sum of lengths of *s**i* (for each *i* such that 1<=β€<=*i*<=β€<=*q*) doesn't exceed 105.
Output Specification:
Print *q* numbers, *i*-th number must be the answer to the *i*-th query.
Demo Input:
['15 2\n4\nUURL\n8\nLRLLLLLLLL\n']
Demo Output:
['10\n5\n']
Note:
none | ```python
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
def hgt(x):
if x == 0: return -1
h = 0
while x&1 != 1:
h += 1
x = x>>1
return h
def up(x):
h = hgt(x)
g = x + (1<<h)
if g > 0 and g < N and hgt(g) == h+1:
return g
g = x - (1<<h)
if g > 0 and g < N and hgt(g) == h+1:
return g
return x
def left(x):
h = hgt(x)
if h == 0:
return x
g = x - (1<<(h-1))
if g > 0:
return g
return x
def right(x):
h = hgt(x)
if h == 0:
return x
g = x + (1<<(h-1))
if g < N:
return g
return x
N, q = map(int, input().split())
N += 1
for _ in range(q):
p = int(input())
for c in input():
if c == 'U':
p = up(p)
elif c == 'R':
p = right(p)
else:
p = left(p)
print(p)
``` |
825 | Minimal Labels | Title: Minimal Labels
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given a directed acyclic graph with *n* vertices and *m* edges. There are no self-loops or multiple edges between any pair of vertices. Graph can be disconnected.
You should assign labels to all vertices in such a way that:
- Labels form a valid permutation of length *n* β an integer sequence such that each integer from 1 to *n* appears exactly once in it. - If there exists an edge from vertex *v* to vertex *u* then *label**v* should be smaller than *label**u*. - Permutation should be lexicographically smallest among all suitable.
Find such sequence of labels to satisfy all the conditions.
Input Specification:
The first line contains two integer numbers *n*, *m* (2<=β€<=*n*<=β€<=105,<=1<=β€<=*m*<=β€<=105).
Next *m* lines contain two integer numbers *v* and *u* (1<=β€<=*v*,<=*u*<=β€<=*n*,<=*v*<=β <=*u*) β edges of the graph. Edges are directed, graph doesn't contain loops or multiple edges.
Output Specification:
Print *n* numbers β lexicographically smallest correct permutation of labels of vertices.
Demo Input:
['3 3\n1 2\n1 3\n3 2\n', '4 5\n3 1\n4 1\n2 3\n3 4\n2 4\n', '5 4\n3 1\n2 1\n2 3\n4 5\n']
Demo Output:
['1 3 2 \n', '4 1 2 3 \n', '3 1 2 4 5 \n']
Note:
none | ```python
import sys
import math
import collections
from heapq import heappush, heappop
input = sys.stdin.readline
ints = lambda: list(map(int, input().split()))
n, m = ints()
g = [[] for _ in range(n)]
deg = [0] * n
for _ in range(m):
u, v = ints()
u -= 1
v -= 1
g[u].append((v, 0))
g[v].append((u, 1))
deg[u] += 1
res = [0] * n
hp = []
for i in range(n):
if deg[i] == 0: heappush(hp, -i)
cnt = n
while hp:
i = -heappop(hp)
res[i] = cnt
for u, t in g[i]:
if t == 1:
deg[u] -= 1
if deg[u] == 0:
heappush(hp, -u)
cnt -= 1
print(*res)
``` |
600 | Extract Numbers | Title: Extract Numbers
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given string *s*. Let's call word any largest sequence of consecutive symbols without symbols ',' (comma) and ';' (semicolon). For example, there are four words in string "aba,123;1a;0": "aba", "123", "1a", "0". A word can be empty: for example, the string *s*=";;" contains three empty words separated by ';'.
You should find all words in the given string that are nonnegative INTEGER numbers without leading zeroes and build by them new string *a*. String *a* should contain all words that are numbers separating them by ',' (the order of numbers should remain the same as in the string *s*). By all other words you should build string *b* in the same way (the order of numbers should remain the same as in the string *s*).
Here strings "101", "0" are INTEGER numbers, but "01" and "1.0" are not.
For example, for the string aba,123;1a;0 the string *a* would be equal to "123,0" and string *b* would be equal to "aba,1a".
Input Specification:
The only line of input contains the string *s* (1<=β€<=|*s*|<=β€<=105). The string contains only symbols '.' (ASCII 46), ',' (ASCII 44), ';' (ASCII 59), digits, lowercase and uppercase latin letters.
Output Specification:
Print the string *a* to the first line and string *b* to the second line. Each string should be surrounded by quotes (ASCII 34).
If there are no words that are numbers print dash (ASCII 45) on the first line. If all words are numbers print dash on the second line.
Demo Input:
['aba,123;1a;0\n', '1;;01,a0,\n', '1\n', 'a\n']
Demo Output:
['"123,0"\n"aba,1a"\n', '"1"\n",01,a0,"\n', '"1"\n-\n', '-\n"a"\n']
Note:
In the second example the string *s* contains five words: "1", "", "01", "a0", "". | ```python
import re
str = input()
lst = re.split('[,;]', str)
ans1 = []
ans2 = []
for s in lst:
if s.isdigit() and (s == '0' or s[0] != '0') and s[0] != '-':
ans1.append(s)
else:
ans2.append(s)
if len(ans1) == 0:
print('-')
else:
print("\"", end="")
print(','.join(ans1), end="")
print("\"")
if len(ans2) == 0:
print('-')
else:
print("\"", end="")
print(','.join(ans2), end="")
print("\"")
``` |
952 | 2 + 2 != 4 | Title: 2 + 2 != 4
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One very experienced problem writer decided to prepare a problem for April Fools Day contest. The task was very simple - given an arithmetic expression, return the result of evaluating this expression. However, looks like there is a bug in the reference solution...
Input Specification:
The only line of input data contains the arithmetic expression. The expression will contain between 2 and 10 operands, separated with arithmetic signs plus and/or minus. Each operand will be an integer between 0 and 255, inclusive.
Output Specification:
Reproduce the output of the reference solution, including the bug.
Demo Input:
['8-7+6-5+4-3+2-1-0\n', '2+2\n', '112-37\n']
Demo Output:
['4\n', '-46\n', '375\n']
Note:
none | ```python
# LUOGU_RID: 101738980
s = input()
ans = eval(s)
for i in range(len(s)):
if s[i] == '+':
x = -5
j = i + 1
while j < len(s) and s[j] not in '+-':
x *= 10
j += 1
ans += x
if s[i] == '-':
x = 3
j = i + 1
while j < len(s) and s[j] not in '+-':
x *= 10
j += 1
ans += x
print(ans)
``` |
598 | Igor In the Museum | Title: Igor In the Museum
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Igor is in the museum and he wants to see as many pictures as possible.
Museum can be represented as a rectangular field of *n*<=Γ<=*m* cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassable) are divided by a wall containing one picture.
At the beginning Igor is in some empty cell. At every moment he can move to any empty cell that share a side with the current one.
For several starting positions you should calculate the maximum number of pictures that Igor can see. Igor is able to see the picture only if he is in the cell adjacent to the wall with this picture. Igor have a lot of time, so he will examine every picture he can see.
Input Specification:
First line of the input contains three integers *n*, *m* and *k* (3<=β€<=*n*,<=*m*<=β€<=1000,<=1<=β€<=*k*<=β€<=*min*(*n*Β·*m*,<=100<=000))Β β the museum dimensions and the number of starting positions to process.
Each of the next *n* lines contains *m* symbols '.', '*' β the description of the museum. It is guaranteed that all border cells are impassable, so Igor can't go out from the museum.
Each of the last *k* lines contains two integers *x* and *y* (1<=β€<=*x*<=β€<=*n*,<=1<=β€<=*y*<=β€<=*m*)Β β the row and the column of one of Igor's starting positions respectively. Rows are numbered from top to bottom, columns β from left to right. It is guaranteed that all starting positions are empty cells.
Output Specification:
Print *k* integersΒ β the maximum number of pictures, that Igor can see if he starts in corresponding position.
Demo Input:
['5 6 3\n******\n*..*.*\n******\n*....*\n******\n2 2\n2 5\n4 3\n', '4 4 1\n****\n*..*\n*.**\n****\n3 2\n']
Demo Output:
['6\n4\n10\n', '8\n']
Note:
none | ```python
import sys
from collections import deque
# import itertools
# import math
# import os
# import random
# from bisect import bisect, bisect_left
# from collections import *
# from functools import reduce
# from heapq import heapify, heappop, heappush
# from io import BytesIO, IOBase
# from string import *
# region fastio
input = lambda: sys.stdin.readline().rstrip()
sint = lambda: int(input())
mint = lambda: map(int, input().split())
ints = lambda: list(map(int, input().split()))
# print = lambda d: sys.stdout.write(str(d) + "\n")
# endregion fastio
# # region interactive
# def printQry(a, b) -> None:
# sa = str(a)
# sb = str(b)
# print(f"? {sa} {sb}", flush = True)
# def printAns(ans) -> None:
# s = str(ans)
# print(f"! {s}", flush = True)
# # endregion interactive
# # region dfsconvert
# from types import GeneratorType
# def bootstrap(f, stack=[]):
# def wrappedfunc(*args, **kwargs):
# if stack:
# return f(*args, **kwargs)
# else:
# to = f(*args, **kwargs)
# while True:
# if type(to) is GeneratorType:
# stack.append(to)
# to = next(to)
# else:
# stack.pop()
# if not stack:
# break
# to = stack[-1].send(to)
# return to
# return wrappedfunc
# # endregion dfsconvert
# MOD = 998244353
# MOD = 10 ** 9 + 7
DIR = ((-1, 0), (0, 1), (1, 0), (0, -1))
def solve() -> None:
n, m, k = mint()
fa = list(range(n * m))
def find(x: int):
cur = x
while x != fa[x]:
x = fa[x]
while fa[cur] != x:
fa[cur], cur = x, fa[cur]
return x
def union(x: int, y: int) -> bool:
x, y = find(x), find(y)
if x == y: return False
fa[y] = x
return True
cnt = [0] * (n * m)
g = []
for _ in range(n):
g.append(input())
for i in range(n):
for j in range(m):
if g[i][j] != '.': continue
x = find(i * m + j)
if cnt[x]: continue
q = deque([(i, j)])
while q:
r, c = q.popleft()
cur = 0
for dr, dc in DIR:
nr, nc = r + dr, c + dc
if g[nr][nc] != '.':
cur += 1
continue
y = find(nr * m + nc)
if y == x: continue
union(x, y)
q.append((nr, nc))
cnt[x] += cur
for _ in range(k):
x, y = mint()
print(cnt[find((x - 1) * m + y - 1)])
solve()
``` |
818 | Permutation Game | Title: Permutation Game
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
*n* children are standing in a circle and playing a game. Children's numbers in clockwise order form a permutation *a*1,<=*a*2,<=...,<=*a**n* of length *n*. It is an integer sequence such that each integer from 1 to *n* appears exactly once in it.
The game consists of *m* steps. On each step the current leader with index *i* counts out *a**i* people in clockwise order, starting from the next person. The last one to be pointed at by the leader becomes the new leader.
You are given numbers *l*1,<=*l*2,<=...,<=*l**m* β indices of leaders in the beginning of each step. Child with number *l*1 is the first leader in the game.
Write a program which will restore a possible permutation *a*1,<=*a*2,<=...,<=*a**n*. If there are multiple solutions then print any of them. If there is no solution then print -1.
Input Specification:
The first line contains two integer numbers *n*, *m* (1<=β€<=*n*,<=*m*<=β€<=100).
The second line contains *m* integer numbers *l*1,<=*l*2,<=...,<=*l**m* (1<=β€<=*l**i*<=β€<=*n*) β indices of leaders in the beginning of each step.
Output Specification:
Print such permutation of *n* numbers *a*1,<=*a*2,<=...,<=*a**n* that leaders in the game will be exactly *l*1,<=*l*2,<=...,<=*l**m* if all the rules are followed. If there are multiple solutions print any of them.
If there is no permutation which satisfies all described conditions print -1.
Demo Input:
['4 5\n2 3 1 4 4\n', '3 3\n3 1 2\n']
Demo Output:
['3 1 2 4 \n', '-1\n']
Note:
Let's follow leadership in the first example:
- Child 2 starts. - Leadership goes from 2 to 2β+β*a*<sub class="lower-index">2</sub>β=β3. - Leadership goes from 3 to 3β+β*a*<sub class="lower-index">3</sub>β=β5. As it's greater than 4, it's going in a circle to 1. - Leadership goes from 1 to 1β+β*a*<sub class="lower-index">1</sub>β=β4. - Leadership goes from 4 to 4β+β*a*<sub class="lower-index">4</sub>β=β8. Thus in circle it still remains at 4. | ```python
n,m=map(int,input().split())
l=[]
l=list(map(int,input().split()))
a=[-1]*(n+1)
s=set()
sorry = False
for i in range(1,n+1):
s.add(i)
for i in range(m-1):
temp = (l[i+1] + n - l[i])%n
if(temp == 0):
temp = n
#print(temp)
if(a[l[i]] == -1 and temp in s):
a[l[i]] = temp
s.remove(temp)
elif(a[l[i]] == temp):
continue
else:
sorry=True
break
if(sorry):
print(-1)
else:
ss = list(s)
x=0
for i in range(1,len(a)):
if(a[i] == -1):
a[i] = ss[x]
x+=1
print(a[i],"",end='')
``` |
1,003 | Intense Heat | Title: Intense Heat
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The heat during the last few days has been really intense. Scientists from all over the Berland study how the temperatures and weather change, and they claim that this summer is abnormally hot. But any scientific claim sounds a lot more reasonable if there are some numbers involved, so they have decided to actually calculate some value which would represent how high the temperatures are.
Mathematicians of Berland State University came up with a special heat intensity value. This value is calculated as follows:
Suppose we want to analyze the segment of $n$ consecutive days. We have measured the temperatures during these $n$ days; the temperature during $i$-th day equals $a_i$.
We denote the average temperature of a segment of some consecutive days as the arithmetic mean of the temperature measures during this segment of days. So, if we want to analyze the average temperature from day $x$ to day $y$, we calculate it as $\frac{\sum \limits_{i = x}^{y} a_i}{y - x + 1}$ (note that division is performed without any rounding). The heat intensity value is the maximum of average temperatures over all segments of not less than $k$ consecutive days. For example, if analyzing the measures $[3, 4, 1, 2]$ and $k = 3$, we are interested in segments $[3, 4, 1]$, $[4, 1, 2]$ and $[3, 4, 1, 2]$ (we want to find the maximum value of average temperature over these segments).
You have been hired by Berland State University to write a program that would compute the heat intensity value of a given period of days. Are you up to this task?
Input Specification:
The first line contains two integers $n$ and $k$ ($1 \le k \le n \le 5000$) β the number of days in the given period, and the minimum number of days in a segment we consider when calculating heat intensity value, respectively.
The second line contains $n$ integers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_i \le 5000$) β the temperature measures during given $n$ days.
Output Specification:
Print one real number β the heat intensity value, i. e., the maximum of average temperatures over all segments of not less than $k$ consecutive days.
Your answer will be considered correct if the following condition holds: $|res - res_0| < 10^{-6}$, where $res$ is your answer, and $res_0$ is the answer given by the jury's solution.
Demo Input:
['4 3\n3 4 1 2\n']
Demo Output:
['2.666666666666667\n']
Note:
none | ```python
from sys import stdin,stdout
n,k = map(int,stdin.readline().split())
#Nhap du lieu
a = list(map(int,stdin.readline().split()))
pref = [0]*(n+5)
pref[0] = a[0];
for i in range(1,n):
pref[i] = pref[i-1] + a[i]
#pref[i] la tong cua day a[1 -> i]
#Xu li
#Xet tat ca cac day a[i -> j] (j-i+1 >= k and j <= n)
# k <= n - i + 1 <=> i <= n - k +1
# j >= k+i - 1
ans = 0
for i in range(0,n-k+1):
for j in range(i+k-1,n):
sum = pref[j] - pref[i] + a[i];
ans = max(ans, sum/(j-i+1))
stdout.write(str(ans))
``` |
690 | Collective Mindsets (easy) | Title: Collective Mindsets (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.
They will be *N* guests tonight: *N*<=-<=1 real zombies and a fake one, our Heidi. The living-dead love hierarchies as much as they love brains: each one has a unique rank in the range 1 to *N*<=-<=1, and Heidi, who still appears slightly different from the others, is attributed the highest rank, *N*. Tonight there will be a chest with brains on display and every attendee sees how many there are. These will then be split among the attendees according to the following procedure:
The zombie of the highest rank makes a suggestion on who gets how many brains (every brain is an indivisible entity). A vote follows. If at least half of the attendees accept the offer, the brains are shared in the suggested way and the feast begins. But if majority is not reached, then the highest-ranked zombie is killed, and the next zombie in hierarchy has to make a suggestion. If he is killed too, then the third highest-ranked makes one, etc. (It's enough to have exactly half of the votes β in case of a tie, the vote of the highest-ranked alive zombie counts twice, and he will of course vote in favor of his own suggestion in order to stay alive.)
You should know that zombies are very greedy and sly, and they know this too β basically all zombie brains are alike. Consequently, a zombie will never accept an offer which is suboptimal for him. That is, if an offer is not strictly better than a potential later offer, he will vote against it. And make no mistake: while zombies may normally seem rather dull, tonight their intellects are perfect. Each zombie's priorities for tonight are, in descending order:
1. survive the event (they experienced death already once and know it is no fun), 1. get as many brains as possible.
Heidi goes first and must make an offer which at least half of the attendees will accept, and which allocates at least one brain for Heidi herself.
What is the smallest number of brains that have to be in the chest for this to be possible?
Input Specification:
The only line of input contains one integer: *N*, the number of attendees (1<=β€<=*N*<=β€<=109).
Output Specification:
Output one integer: the smallest number of brains in the chest which allows Heidi to take one brain home.
Demo Input:
['1\n', '4\n']
Demo Output:
['1\n', '2\n']
| ```python
# LUOGU_RID: 101268054
n = int(input())
if n % 2:
print(n // 2 +1)
else:
print(n // 2)
``` |
852 | Casinos and travel | Title: Casinos and travel
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
John has just bought a new car and is planning a journey around the country. Country has *N* cities, some of which are connected by bidirectional roads. There are *N*<=-<=1 roads and every city is reachable from any other city. Cities are labeled from 1 to *N*.
John first has to select from which city he will start his journey. After that, he spends one day in a city and then travels to a randomly choosen city which is directly connected to his current one and which he has not yet visited. He does this until he can't continue obeying these rules.
To select the starting city, he calls his friend Jack for advice. Jack is also starting a big casino business and wants to open casinos in some of the cities (max 1 per city, maybe nowhere). Jack knows John well and he knows that if he visits a city with a casino, he will gamble exactly once before continuing his journey.
He also knows that if John enters a casino in a good mood, he will leave it in a bad mood and vice versa. Since he is John's friend, he wants him to be in a good mood at the moment when he finishes his journey. John is in a good mood before starting the journey.
In how many ways can Jack select a starting city for John and cities where he will build casinos such that no matter how John travels, he will be in a good mood at the end? Print answer modulo 109<=+<=7.
Input Specification:
In the first line, a positive integer *N* (1<=β€<=*N*<=β€<=100000), the number of cities.
In the next *N*<=-<=1 lines, two numbers *a*,<= *b* (1<=β€<=*a*,<=*b*<=β€<=*N*) separated by a single space meaning that cities *a* and *b* are connected by a bidirectional road.
Output Specification:
Output one number, the answer to the problem modulo 109<=+<=7.
Demo Input:
['2\n1 2\n', '3\n1 2\n2 3\n']
Demo Output:
['4\n', '10\n']
Note:
Example 1: If Jack selects city 1 as John's starting city, he can either build 0 casinos, so John will be happy all the time, or build a casino in both cities, so John would visit a casino in city 1, become unhappy, then go to city 2, visit a casino there and become happy and his journey ends there because he can't go back to city 1. If Jack selects city 2 for start, everything is symmetrical, so the answer is 4.
Example 2: If Jack tells John to start from city 1, he can either build casinos in 0 or 2 cities (total 4 possibilities). If he tells him to start from city 2, then John's journey will either contain cities 2 and 1 or 2 and 3. Therefore, Jack will either have to build no casinos, or build them in all three cities. With other options, he risks John ending his journey unhappy. Starting from 3 is symmetric to starting from 1, so in total we have 4β+β2β+β4β=β10 options. | ```python
n=int(input())
a = [0]*(n+1)
for i in range(n-1):
for i in input().split():
a[int(i)]+=1
l = a.count(1)
print ((l*2**(n-l+1)+(n-l)*(2**(n-l)))%(10**9+7))
``` |
803 | Roma and Poker | Title: Roma and Poker
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Each evening Roma plays online poker on his favourite website. The rules of poker on this website are a bit strange: there are always two players in a hand, there are no bets, and the winner takes 1 virtual bourle from the loser.
Last evening Roma started to play poker. He decided to spend no more than *k* virtual bourles β he will stop immediately if the number of his loses exceeds the number of his wins by *k*. Also Roma will leave the game if he wins enough money for the evening, i.e. if the number of wins exceeds the number of loses by *k*.
Next morning Roma found a piece of paper with a sequence on it representing his results. Roma doesn't remember the results exactly, and some characters in the sequence are written in a way such that it's impossible to recognize this character, so Roma can't recall whether he won *k* bourles or he lost.
The sequence written by Roma is a string *s* consisting of characters W (Roma won the corresponding hand), L (Roma lost), D (draw) and ? (unknown result). Roma wants to restore any valid sequence by changing all ? characters to W, L or D. The sequence is called valid if all these conditions are met:
- In the end the absolute difference between the number of wins and loses is equal to *k*; - There is no hand such that the absolute difference before this hand was equal to *k*.
Help Roma to restore any such sequence.
Input Specification:
The first line contains two numbers *n* (the length of Roma's sequence) and *k* (1<=β€<=*n*,<=*k*<=β€<=1000).
The second line contains the sequence *s* consisting of characters W, L, D and ?. There are exactly *n* characters in this sequence.
Output Specification:
If there is no valid sequence that can be obtained from *s* by replacing all ? characters by W, L or D, print NO.
Otherwise print this sequence. If there are multiple answers, print any of them.
Demo Input:
['3 2\nL??\n', '3 1\nW??\n', '20 5\n?LLLLLWWWWW?????????\n']
Demo Output:
['LDL\n', 'NO\n', 'WLLLLLWWWWWWWWLWLWDW\n']
Note:
none | ```python
N,k=list(map(int,input().strip().split(' ')))
S=input()
# num of W-num of L=j, j>k means k-j
dp=[[0 for j in range(2*k+1)]for i in range(N)]
#print(dp)
for i in range(len(S)):
if i==0:
if S[0]=='W':
dp[0][1]='W'
elif S[0]=='L':
dp[0][-1]='L'
elif S[0]=='D':
dp[0][0]='D'
else:
dp[0][1]='W'
dp[0][-1]='L'
dp[0][0]='D'
elif i!=len(S)-1:
if S[i]=='W':
for j in range(0,k):
if j==0:
if dp[i-1][-1]!=0:
dp[i][0]='W'
else:
if dp[i-1][j-1]!=0:
dp[i][j]='W'
for j in range(1,k):
if j!=k-1:
if dp[i-1][-j-1]!=0:
dp[i][-j]='W'
elif S[i]=='L':
for j in range(0,k):
if dp[i-1][j+1]!=0:
dp[i][j]='L'
for j in range(1,k):
if j==1:
if dp[i-1][0]!=0:
dp[i][-1]='L'
else:
if dp[i-1][-j+1]!=0:
dp[i][-j]='L'
elif S[i]=='D':
for j in range(0,2*k+1):
if dp[i-1][j]!=0:
dp[i][j]='D'
else:
for j in range(0,k):
if j==0:
if dp[i-1][-1]!=0:
dp[i][j]='W'
elif dp[i-1][1]!=0:
dp[i][j]='L'
elif dp[i-1][0]!=0:
dp[i][j]='D'
else:
if dp[i-1][j-1]!=0:
dp[i][j]='W'
elif dp[i-1][j+1]!=0:
dp[i][j]='L'
elif dp[i-1][j]!=0:
dp[i][j]='D'
for j in range(1,k):
if j==1:
if dp[i-1][0]!=0:
dp[i][-1]='L'
elif dp[i-1][-1]!=0:
dp[i][-1]='D'
elif dp[i-1][-2]!=0:
dp[i][-1]='W'
else:
if dp[i-1][-(j-1)]!=0:
dp[i][-j]='L'
elif dp[i-1][-j]!=0:
dp[i][-j]='D'
elif dp[i-1][-(j+1)]!=0:
dp[i][-j]='W'
else:
if S[i]=='W':
if dp[i-1][k-1]!=0:
dp[i][k]='W'
elif S[i]=='L':
if dp[i-1][-(k-1)]!=0:
dp[i][-k]='L'
elif S[i]=='D':
1
else:
if dp[i-1][k-1]!=0:
dp[i][k]='W'
elif dp[i-1][-(k-1)]!=0:
dp[i][-k]='L'
#print(dp)
if k>1 and N>=k:
if dp[len(S)-1][k]==0 and dp[len(S)-1][-k]==0:
print('NO')
else:
if dp[len(S)-1][k]!=0:
ans=''
cur=k
for j in range(1,len(S)+1):
temp=dp[len(S)-j][cur]
if temp=='W':
ans+=temp
cur-=1
elif temp=='D':
ans+=temp
elif temp=='L':
ans+=temp
cur+=1
elif dp[len(S)-1][-k]!=0:
ans=''
cur=-k
for j in range(1,len(S)+1):
temp=dp[len(S)-j][cur]
if temp=='W':
ans+=temp
cur-=1
elif temp=='D':
ans+=temp
elif temp=='L':
ans+=temp
cur+=1
ans=ans[::-1]
print(ans)
elif N<k:
print('NO')
elif k==1:
shit=0
for i in range(len(S)):
if i<len(S)-1:
if S[i]!='?':
shit=1
break
if shit==1:
print('NO')
else:
temp=''
for i in range(len(S)-1):
temp+='D'
if S[-1]=='D':
print('NO')
elif S[-1]=='L':
temp+='L'
print(temp)
else:
temp+='W'
print(temp)
``` |
630 | Indivisibility | Title: Indivisibility
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
IT City company developing computer games decided to upgrade its way to reward its employees. Now it looks the following way. After a new game release users start buying it actively, and the company tracks the number of sales with precision to each transaction. Every time when the next number of sales is not divisible by any number from 2 to 10 every developer of this game gets a small bonus.
A game designer Petya knows that the company is just about to release a new game that was partly developed by him. On the basis of his experience he predicts that *n* people will buy the game during the first month. Now Petya wants to determine how many times he will get the bonus. Help him to know it.
Input Specification:
The only line of the input contains one integer *n* (1<=β€<=*n*<=β€<=1018) β the prediction on the number of people who will buy the game.
Output Specification:
Output one integer showing how many numbers from 1 to *n* are not divisible by any number from 2 to 10.
Demo Input:
['12\n']
Demo Output:
['2']
Note:
none | ```python
n = int(input())
print(n-n//2-n//3-n//5-n//7+n//6+n//10+n//14+n//15+n//21+n//35-n//30-n//42-n//70-n//105+n//210)
``` |
171 | Star | Title: Star
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains a single integer *a* (1<=β€<=*a*<=β€<=18257).
Output Specification:
Print a single integer *output* (1<=β€<=*output*<=β€<=2Β·109).
Demo Input:
['2\n']
Demo Output:
['13']
Note:
none | ```python
n = int(input())
print (6*n*(n-1)+1)
``` |
784 | Touchy-Feely Palindromes | Title: Touchy-Feely Palindromes
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.
Output "Yes" or "No".
Input Specification:
The only line of the input contains a string of digits. The length of the string is between 1 and 10, inclusive.
Output Specification:
Output "Yes" or "No".
Demo Input:
['373\n', '121\n', '436\n']
Demo Output:
['Yes\n', 'No\n', 'Yes\n']
Note:
none | ```python
import sys
input = lambda: sys.stdin.readline().strip()
s2 = str(input())
if "1" in s2 or "2" in s2:
print("No")
else:
an = ""
s = list(s2)
for i in range(len(s)):
if s2[i] == "4":
s[i] = "6"
elif s2[i] == "5":
s[i] = "9"
elif s2[i] == "8":
s[i] = "0"
for i in range(len(s)):
an += s[i]
if len(an) == 1:
if an[0] == "3" or an[0] == "7":
print("Yes")
else:
print("No")
else:
print("Yes" if an == an[::-1] else "No")
``` |
290 | QR code | Title: QR code
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Input Specification:
The input contains two integers *a*1,<=*a*2 (0<=β€<=*a**i*<=β€<=32), separated by a single space.
Output Specification:
Output a single integer.
Demo Input:
['1 1\n', '3 7\n', '13 10\n']
Demo Output:
['0\n', '0\n', '1\n']
Note:
none | ```python
b,c=map(int,input().split())
a='111111101010101111100101001111111 100000100000000001010110001000001 101110100110110000011010001011101 101110101011001001111101001011101 101110101100011000111100101011101 100000101010101011010000101000001 111111101010101010101010101111111 000000001111101111100111100000000 100010111100100001011110111111001 110111001111111100100001000101100 011100111010000101000111010001010 011110000110001111110101100000011 111111111111111000111001001011000 111000010111010011010011010100100 101010100010110010110101010000010 101100000101010001111101000000000 000010100011001101000111101011010 101001001111101111000101010001110 101101111111000100100001110001000 000010011000100110000011010000010 001101101001101110010010011011000 011101011010001000111101010100110 111010100110011101001101000001110 110001010010101111000101111111000 001000111011100001010110111110000 000000001110010110100010100010110 111111101000101111000110101011010 100000100111010101111100100011011 101110101001010000101000111111000 101110100011010010010111111011010 101110100100011011110110101110000 100000100110011001111100111100000 111111101101000101001101110010001'.split()
print(a[b][c])
``` |
847 | Load Testing | Title: Load Testing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp plans to conduct a load testing of its new project Fakebook. He already agreed with his friends that at certain points in time they will send requests to Fakebook. The load testing will last *n* minutes and in the *i*-th minute friends will send *a**i* requests.
Polycarp plans to test Fakebook under a special kind of load. In case the information about Fakebook gets into the mass media, Polycarp hopes for a monotone increase of the load, followed by a monotone decrease of the interest to the service. Polycarp wants to test this form of load.
Your task is to determine how many requests Polycarp must add so that before some moment the load on the server strictly increases and after that moment strictly decreases. Both the increasing part and the decreasing part can be empty (i. e. absent). The decrease should immediately follow the increase. In particular, the load with two equal neigbouring values is unacceptable.
For example, if the load is described with one of the arrays [1, 2, 8, 4, 3], [1, 3, 5] or [10], then such load satisfies Polycarp (in each of the cases there is an increasing part, immediately followed with a decreasing part). If the load is described with one of the arrays [1, 2, 2, 1], [2, 1, 2] or [10, 10], then such load does not satisfy Polycarp.
Help Polycarp to make the minimum number of additional requests, so that the resulting load satisfies Polycarp. He can make any number of additional requests at any minute from 1 to *n*.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100<=000) β the duration of the load testing.
The second line contains *n* integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109), where *a**i* is the number of requests from friends in the *i*-th minute of the load testing.
Output Specification:
Print the minimum number of additional requests from Polycarp that would make the load strictly increasing in the beginning and then strictly decreasing afterwards.
Demo Input:
['5\n1 4 3 2 5\n', '5\n1 2 2 2 1\n', '7\n10 20 40 50 70 90 30\n']
Demo Output:
['6\n', '1\n', '0\n']
Note:
In the first example Polycarp must make two additional requests in the third minute and four additional requests in the fourth minute. So the resulting load will look like: [1, 4, 5, 6, 5]. In total, Polycarp will make 6 additional requests.
In the second example it is enough to make one additional request in the third minute, so the answer is 1.
In the third example the load already satisfies all conditions described in the statement, so the answer is 0. | ```python
s, l, r = 0, 0, int(input()) - 1
t = list(map(int, input().split()))
while 1:
while l < r and t[l] < t[l + 1]: l += 1
while l < r and t[r] < t[r - 1]: r -= 1
if l == r: break
if t[l] < t[r]:
s += t[l] - t[l + 1] + 1
t[l + 1] = t[l] + 1
else:
s += t[r] - t[r - 1] + 1
t[r - 1] = t[r] + 1
print(s)
``` |
612 | Replace To Make Regular Bracket Sequence | Title: Replace To Make Regular Bracket Sequence
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given string *s* consists of opening and closing brackets of four kinds <>, {}, [], (). There are two types of brackets: opening and closing. You can replace any bracket by another of the same type. For example, you can replace < by the bracket {, but you can't replace it by ) or >.
The following definition of a regular bracket sequence is well-known, so you can be familiar with it.
Let's define a regular bracket sequence (RBS). Empty string is RBS. Let *s*1 and *s*2 be a RBS then the strings <*s*1>*s*2, {*s*1}*s*2, [*s*1]*s*2, (*s*1)*s*2 are also RBS.
For example the string "[[(){}]<>]" is RBS, but the strings "[)()" and "][()()" are not.
Determine the least number of replaces to make the string *s* RBS.
Input Specification:
The only line contains a non empty string *s*, consisting of only opening and closing brackets of four kinds. The length of *s* does not exceed 106.
Output Specification:
If it's impossible to get RBS from *s* print Impossible.
Otherwise print the least number of replaces needed to get RBS from *s*.
Demo Input:
['[<}){}\n', '{()}[]\n', ']]\n']
Demo Output:
['2', '0', 'Impossible']
Note:
none | ```python
s = input()
op = '{[(<'
cl = {'{':'}', '[':']', '(':')', '<':'>'}
cnt = 0
flag = False
for elem in s:
if elem in op:
cnt += 1
else:
cnt -= 1
if cnt < 0:
flag = True
break
if cnt != 0 or flag:
print('Impossible')
else:
last = []
cnt = 0
for elem in s:
if elem in op:
last.append(elem)
else:
curr = last.pop()
if cl[curr] != elem:
cnt += 1
print(cnt)
``` |
76 | Mice | Title: Mice
Time Limit: 0 seconds
Memory Limit: 256 megabytes
Problem Description:
Modern researches has shown that a flock of hungry mice searching for a piece of cheese acts as follows: if there are several pieces of cheese then each mouse chooses the closest one. After that all mice start moving towards the chosen piece of cheese. When a mouse or several mice achieve the destination point and there is still a piece of cheese in it, they eat it and become well-fed. Each mice that reaches this point after that remains hungry. Moving speeds of all mice are equal.
If there are several ways to choose closest pieces then mice will choose it in a way that would minimize the number of hungry mice. To check this theory scientists decided to conduct an experiment. They located *N* mice and *M* pieces of cheese on a cartesian plane where all mice are located on the line *y*<==<=*Y*0 and all pieces of cheese β on another line *y*<==<=*Y*1. To check the results of the experiment the scientists need a program which simulates the behavior of a flock of hungry mice.
Write a program that computes the minimal number of mice which will remain hungry, i.e. without cheese.
Input Specification:
The first line of the input contains four integer numbers *N* (1<=β€<=*N*<=β€<=105), *M* (0<=β€<=*M*<=β€<=105), *Y*0 (0<=β€<=*Y*0<=β€<=107), *Y*1 (0<=β€<=*Y*1<=β€<=107, *Y*0<=β <=*Y*1). The second line contains a strictly increasing sequence of *N* numbers β *x* coordinates of mice. Third line contains a strictly increasing sequence of *M* numbers β *x* coordinates of cheese. All coordinates are integers and do not exceed 107 by absolute value.
Output Specification:
The only line of output should contain one number β the minimal number of mice which will remain without cheese.
Demo Input:
['3 2 0 2\n0 1 3\n2 5\n']
Demo Output:
['1\n']
Note:
All the three mice will choose the first piece of cheese. Second and third mice will eat this piece. The first one will remain hungry, because it was running towards the same piece, but it was late. The second piece of cheese will remain uneaten. | ```python
def distance(x, y):
return abs(x - y)
n, m, y0, y1 = map(int, input().split())
mouse = list(map(int, input().split()))
cheeses = list(map(int, input().split()))
i = 0
j = 0
res = 0
mouse.append(float("inf"))
cheeses.append(float("inf"))
prevJ = -1
for i in range(n):
while distance(mouse[i], cheeses[j]) > distance(mouse[i], cheeses[j + 1]):
j += 1
if prevJ < j or (0 < i and distance(mouse[i - 1], cheeses[j]) == distance(mouse[i], cheeses[j])):
res += 1
elif j + 1 < m and distance(mouse[i], cheeses[j + 1]) == distance(mouse[i], cheeses[j]):
res += 1
j += 1
prevJ = j
print(n - res)
``` |
171 | Broken checker | Title: Broken checker
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
"This problem is rubbish! There is not statement, and there are only 5 test cases. The problemsetter took liberties with this problem!" β people complained in the comments to one round on Codeforces. And even more... No, wait, the checker for the problem was alright, that's a mercy.
Input Specification:
The only line of the input contains an integer between 1 and 5, inclusive. All tests for this problem are different. The contents of the test case doesn't need to be equal to its index.
Output Specification:
The only line of the output contains an integer between 1 and 3, inclusive.
Note:
This problem has no samples, since there so few test cases. | ```python
#!/usr/bin/env python
# coding=utf-8
'''
Author: Deean
Date: 2021-11-29 23:39:34
LastEditTime: 2021-11-29 23:40:38
Description: Broken checker
FilePath: CF171D.py
'''
def func():
n = int(input())
print(n % 5 % 3 + 1)
if __name__ == '__main__':
func()
``` |
893 | Counting Arrays | Title: Counting Arrays
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given two positive integer numbers *x* and *y*. An array *F* is called an *y*-factorization of *x* iff the following conditions are met:
- There are *y* elements in *F*, and all of them are integer numbers; - .
You have to count the number of pairwise distinct arrays that are *y*-factorizations of *x*. Two arrays *A* and *B* are considered different iff there exists at least one index *i* (1<=β€<=*i*<=β€<=*y*) such that *A**i*<=β <=*B**i*. Since the answer can be very large, print it modulo 109<=+<=7.
Input Specification:
The first line contains one integer *q* (1<=β€<=*q*<=β€<=105) β the number of testcases to solve.
Then *q* lines follow, each containing two integers *x**i* and *y**i* (1<=β€<=*x**i*,<=*y**i*<=β€<=106). Each of these lines represents a testcase.
Output Specification:
Print *q* integers. *i*-th integer has to be equal to the number of *y**i*-factorizations of *x**i* modulo 109<=+<=7.
Demo Input:
['2\n6 3\n4 2\n']
Demo Output:
['36\n6\n']
Note:
In the second testcase of the example there are six *y*-factorizations:
- {β-β4,ββ-β1}; - {β-β2,ββ-β2}; - {β-β1,ββ-β4}; - {1,β4}; - {2,β2}; - {4,β1}. | ```python
from collections import defaultdict
import sys
input = sys.stdin.readline
def fast_prime_factorization(n):
d = [(i + 1) % 2 * 2 for i in range(n + 1)]
d[0], d[1] = 0, 1
for i in range(3, n + 1):
if d[i]:
continue
for j in range(i, n + 1, 2 * i):
if not d[j]:
d[j] = i
return d
l = pow(10, 6) + 100
mod = pow(10, 9) + 7
fact = [1] * (l + 1)
for i in range(1, l + 1):
fact[i] = i * fact[i - 1] % mod
inv = [1] * (l + 1)
inv[l] = pow(fact[l], mod - 2, mod)
for i in range(l - 1, -1, -1):
inv[i] = (i + 1) * inv[i + 1] % mod
def comb(n, r):
return fact[n] * inv[r] * inv[n - r] % mod if n >= r >= 0 else 0
d = fast_prime_factorization(l)
pow2 = [1]
for _ in range(l):
pow2.append(2 * pow2[-1] % mod)
q = int(input())
for _ in range(q):
x, y = map(int, input().split())
cnt = defaultdict(lambda : 0)
while x ^ d[x]:
cnt[d[x]] += 1
x //= d[x]
if x > 1:
cnt[x] += 1
ans = 1
for i in cnt.values():
ans *= comb(y + i - 1, i)
ans %= mod
ans *= pow2[y - 1]
ans %= mod
print(ans)
``` |
600 | Make Palindrome | Title: Make Palindrome
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.
You are given string *s* consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in *s*. Then you can permute the order of letters as you want. Permutation doesn't count as changes.
You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.
Input Specification:
The only line contains string *s* (1<=β€<=|*s*|<=β€<=2Β·105) consisting of only lowercase Latin letters.
Output Specification:
Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.
Demo Input:
['aabc\n', 'aabcd\n']
Demo Output:
['abba\n', 'abcba\n']
Note:
none | ```python
import collections
s = collections.Counter(sorted(list(input())))
odds = [c for c in s if s[c] % 2]
length = len(odds)
for i in range(length // 2):
s[odds[i]] += 1
s[odds[length - i - 1]] -= 1
infix = odds[length // 2] if length % 2 else ""
prefix = "".join([c * (s[c] // 2) for c in s])
print(prefix + infix + prefix[::-1])
``` |
702 | Road to Post Office | Title: Road to Post Office
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasiliy has a car and he wants to get from home to the post office. The distance which he needs to pass equals to *d* kilometers.
Vasiliy's car is not new β it breaks after driven every *k* kilometers and Vasiliy needs *t* seconds to repair it. After repairing his car Vasiliy can drive again (but after *k* kilometers it will break again, and so on). In the beginning of the trip the car is just from repair station.
To drive one kilometer on car Vasiliy spends *a* seconds, to walk one kilometer on foot he needs *b* seconds (*a*<=<<=*b*).
Your task is to find minimal time after which Vasiliy will be able to reach the post office. Consider that in every moment of time Vasiliy can left his car and start to go on foot.
Input Specification:
The first line contains 5 positive integers *d*,<=*k*,<=*a*,<=*b*,<=*t* (1<=β€<=*d*<=β€<=1012; 1<=β€<=*k*,<=*a*,<=*b*,<=*t*<=β€<=106; *a*<=<<=*b*), where:
- *d* β the distance from home to the post office; - *k* β the distance, which car is able to drive before breaking; - *a* β the time, which Vasiliy spends to drive 1 kilometer on his car; - *b* β the time, which Vasiliy spends to walk 1 kilometer on foot; - *t* β the time, which Vasiliy spends to repair his car.
Output Specification:
Print the minimal time after which Vasiliy will be able to reach the post office.
Demo Input:
['5 2 1 4 10\n', '5 2 1 4 5\n']
Demo Output:
['14\n', '13\n']
Note:
In the first example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds) and then to walk on foot 3 kilometers (in 12 seconds). So the answer equals to 14 seconds.
In the second example Vasiliy needs to drive the first 2 kilometers on the car (in 2 seconds), then repair his car (in 5 seconds) and drive 2 kilometers more on the car (in 2 seconds). After that he needs to walk on foot 1 kilometer (in 4 seconds). So the answer equals to 13 seconds. | ```python
d,k,a,b,t=map(int,input().split())
def calc(mid):
x=min(d,k+mid*k)
return x*a+(d-x)*b+t*mid
# k+n*k<=d
# n<=(d-k)//k
L,R=-1,(d-k)//k+1
while L+2<R:
c1=L+(R-L)//3
c2=R-(R-L)//3
if calc(c1)<calc(c2):
R=c2
else:
L=c1
ans=9*10**18
for i in range(max(0,L),min(R,d)+1):
ans=min(ans,calc(i))
print(ans)
``` |
171 | Mysterious numbers - 2 | Title: Mysterious numbers - 2
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The only line of input contains three integers *a*1,<=*a*2,<=*a*3 (1<=β€<=*a*1,<=*a*2,<=*a*3<=β€<=20), separated by spaces.
Output a single integer.
Input Specification:
The only line of input contains three integers *a*1,<=*a*2,<=*a*3 (1<=β€<=*a*1,<=*a*2,<=*a*3<=β€<=20), separated by spaces.
Output Specification:
Output a single integer.
Demo Input:
['2 3 2\n', '13 14 1\n', '14 5 9\n', '17 18 3\n']
Demo Output:
['5\n', '14\n', '464\n', '53\n']
Note:
none | ```python
a,b,c=eval(input().replace(' ',','))
def func(x):
if x==0:
return a
if x==1:
return b
return func(x-1)+func(x-2)
print(func(c))
``` |
702 | Powers of Two | Title: Powers of Two
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* integers *a*1,<=*a*2,<=...,<=*a**n*. Find the number of pairs of indexes *i*,<=*j* (*i*<=<<=*j*) that *a**i*<=+<=*a**j* is a power of 2 (i. e. some integer *x* exists so that *a**i*<=+<=*a**j*<==<=2*x*).
Input Specification:
The first line contains the single positive integer *n* (1<=β€<=*n*<=β€<=105) β the number of integers.
The second line contains *n* positive integers *a*1,<=*a*2,<=...,<=*a**n* (1<=β€<=*a**i*<=β€<=109).
Output Specification:
Print the number of pairs of indexes *i*,<=*j* (*i*<=<<=*j*) that *a**i*<=+<=*a**j* is a power of 2.
Demo Input:
['4\n7 3 2 1\n', '3\n1 1 1\n']
Demo Output:
['2\n', '3\n']
Note:
In the first example the following pairs of indexes include in answer: (1,β4) and (2,β4).
In the second example all pairs of indexes (*i*,β*j*) (where *i*β<β*j*) include in answer. | ```python
import sys
input = sys.stdin.readline
from collections import Counter
n = int(input())
w = Counter(map(int, input().split()))
d = []
c = 0
for i in range(31):
d.append(2**i)
for i in w:
for j in d:
if j > i:
x = j-i
if x == i:
c += w[i]*(w[i]-1)
elif x in w:
c += w[x]*w[i]
print(c//2)
``` |
920 | Connected Components? | Title: Connected Components?
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph consisting of *n* vertices and edges. Instead of giving you the edges that exist in the graph, we give you *m* unordered pairs (*x*,<=*y*) such that there is no edge between *x* and *y*, and if some pair of vertices is not listed in the input, then there is an edge between these vertices.
You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices *X* such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to *X* violates this rule.
Input Specification:
The first line contains two integers *n* and *m* (1<=β€<=*n*<=β€<=200000, ).
Then *m* lines follow, each containing a pair of integers *x* and *y* (1<=β€<=*x*,<=*y*<=β€<=*n*, *x*<=β <=*y*) denoting that there is no edge between *x* and *y*. Each pair is listed at most once; (*x*,<=*y*) and (*y*,<=*x*) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices.
Output Specification:
Firstly print *k* β the number of connected components in this graph.
Then print *k* integers β the sizes of components. You should output these integers in non-descending order.
Demo Input:
['5 5\n1 2\n3 4\n3 2\n4 2\n2 5\n']
Demo Output:
['2\n1 4 ']
Note:
none | ```python
import sys
import math
import string
def solve(s, l, a):
c = 0
v = l[0]
l.pop(0)
rem = list(s)
for i in rem:
if((min(i,v), max(i,v)) not in a):
c += 1
l.append(i)
s.remove(i)
for i in l:
c += solve(s, [i], a)
return c
if __name__ == "__main__":
input = sys.stdin.readline
print = sys.stdout.write
n, m = map(int, input().split())
arr = set()
for _ in range(m):
x, y = map(int, input().split())
arr.add((min(x - 1, y - 1), max(x - 1, y - 1)))
s = set()
for i in range(n):
s.add(i)
total = []
while(len(s) != 0):
leaders = []
leaders.append(next(iter(s)))
s.remove(leaders[0])
total.append(solve(s, leaders, arr) + 1)
total = sorted(total)
print(str(len(total)) + "\n")
for i in total:
print(str(i) + " ")
``` |
926 | Choose Place | Title: Choose Place
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A classroom in a school has six rows with 3 desks in each row. Two people can use the same desk: one sitting on the left and one sitting on the right.
Some places are already occupied, and some places are vacant. Petya has just entered the class and wants to occupy the most convenient place. The conveniences of the places are shown on the picture:
Here, the desks in the top row are the closest to the blackboard, while the desks in the bottom row are the furthest from the blackboard.
You are given a plan of the class, where '*' denotes an occupied place, '.' denotes a vacant place, and the aisles are denoted by '-'.
Find any of the most convenient vacant places for Petya.
Input Specification:
The input consists of 6 lines. Each line describes one row of desks, starting from the closest to the blackboard. Each line is given in the following format: two characters, each is '*' or '.' β the description of the left desk in the current row; a character '-' β the aisle; two characters, each is '*' or '.' β the description of the center desk in the current row; a character '-' β the aisle; two characters, each is '*' or '.' β the description of the right desk in the current row. So, the length of each of the six lines is 8.
It is guaranteed that there is at least one vacant place in the classroom.
Output Specification:
Print the plan of the classroom after Petya takes one of the most convenient for him places. Mark this place with the letter 'P'. There should be exactly one letter 'P' in the plan. Petya can only take a vacant place. In all other places the output should coincide with the input.
If there are multiple answers, print any.
Demo Input:
['..-**-..\n..-**-..\n..-..-..\n..-..-..\n..-..-..\n..-..-..\n', '**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-..-..\n..-**-..\n', '**-**-*.\n*.-*.-**\n**-**-**\n**-**-**\n..-..-..\n..-**-..\n']
Demo Output:
['..-**-..\n..-**-..\n..-..-..\n..-P.-..\n..-..-..\n..-..-..\n', '**-**-**\n**-**-**\n..-**-.*\n**-**-**\n..-P.-..\n..-**-..\n', '**-**-*.\n*.-*P-**\n**-**-**\n**-**-**\n..-..-..\n..-**-..\n']
Note:
In the first example the maximum convenience is 3.
In the second example the maximum convenience is 2.
In the third example the maximum convenience is 4. | ```python
l = [[],[],[],[],[],[]];
y = [[3, 3, 4, 4, 3, 3],
[3, 3, 4, 4, 3, 3],
[2, 2, 3, 3, 2, 2],
[2, 2, 3, 3, 2, 2],
[1, 1, 2, 2, 1, 1],
[1, 1, 2, 2, 1, 1]]
for i in range(6):
s = input()
for j in s:
if (j != '-'):
l[i].append(j)
maxm = 0
maxi = 0
maxj = 0
for i in range(6):
for j in range(6):
if (l[i][j] == '.'):
if (y[i][j] > maxm):
maxm = y[i][j]
maxi = i
maxj = j
l[maxi][maxj] = 'P'
for i in range(6):
print(l[i][0], l[i][1], '-', l[i][2], l[i][3], '-',l[i][4], l[i][5], sep = '')
``` |
873 | Strange Game On Matrix | Title: Strange Game On Matrix
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan is playing a strange game.
He has a matrix *a* with *n* rows and *m* columns. Each element of the matrix is equal to either 0 or 1. Rows and columns are 1-indexed. Ivan can replace any number of ones in this matrix with zeroes. After that, his score in the game will be calculated as follows:
1. Initially Ivan's score is 0; 1. In each column, Ivan will find the topmost 1 (that is, if the current column is *j*, then he will find minimum *i* such that *a**i*,<=*j*<==<=1). If there are no 1's in the column, this column is skipped; 1. Ivan will look at the next *min*(*k*,<=*n*<=-<=*i*<=+<=1) elements in this column (starting from the element he found) and count the number of 1's among these elements. This number will be added to his score.
Of course, Ivan wants to maximize his score in this strange game. Also he doesn't want to change many elements, so he will replace the minimum possible number of ones with zeroes. Help him to determine the maximum possible score he can get and the minimum possible number of replacements required to achieve that score.
Input Specification:
The first line contains three integer numbers *n*, *m* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=100, 1<=β€<=*m*<=β€<=100).
Then *n* lines follow, *i*-th of them contains *m* integer numbers β the elements of *i*-th row of matrix *a*. Each number is either 0 or 1.
Output Specification:
Print two numbers: the maximum possible score Ivan can get and the minimum number of replacements required to get this score.
Demo Input:
['4 3 2\n0 1 0\n1 0 1\n0 1 0\n1 1 1\n', '3 2 1\n1 0\n0 1\n0 0\n']
Demo Output:
['4 1\n', '2 0\n']
Note:
In the first example Ivan will replace the element *a*<sub class="lower-index">1,β2</sub>. | ```python
import sys
n, m, k = map(int, input().split())
matrix = [[0]*m] + [list(map(int, input().split())) for _ in range(n)]
for j in range(m):
for i in range(1, n+1):
matrix[i][j] += matrix[i-1][j]
ans = [0, 0]
for j in range(m):
max_one, rem = 0, 0
for i in range(k, n+1):
if max_one < matrix[i][j] - matrix[i-k][j]:
max_one = matrix[i][j] - matrix[i-k][j]
rem = matrix[i-k][j]
ans[0] += max_one
ans[1] += rem
print(*ans)
``` |
1,009 | Relatively Prime Graph | Title: Relatively Prime Graph
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's call an undirected graph $G = (V, E)$ relatively prime if and only if for each edge $(v, u) \in E$ Β $GCD(v, u) = 1$ (the greatest common divisor of $v$ and $u$ is $1$). If there is no edge between some pair of vertices $v$ and $u$ then the value of $GCD(v, u)$ doesn't matter. The vertices are numbered from $1$ to $|V|$.
Construct a relatively prime graph with $n$ vertices and $m$ edges such that it is connected and it contains neither self-loops nor multiple edges.
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
If there are multiple answers then print any of them.
Input Specification:
The only line contains two integers $n$ and $m$ ($1 \le n, m \le 10^5$) β the number of vertices and the number of edges.
Output Specification:
If there exists no valid graph with the given number of vertices and edges then output "Impossible".
Otherwise print the answer in the following format:
The first line should contain the word "Possible".
The $i$-th of the next $m$ lines should contain the $i$-th edge $(v_i, u_i)$ of the resulting graph ($1 \le v_i, u_i \le n, v_i \neq u_i$). For each pair $(v, u)$ there can be no more pairs $(v, u)$ or $(u, v)$. The vertices are numbered from $1$ to $n$.
If there are multiple answers then print any of them.
Demo Input:
['5 6\n', '6 12\n']
Demo Output:
['Possible\n2 5\n3 2\n5 1\n3 4\n4 1\n5 4\n', 'Impossible\n']
Note:
Here is the representation of the graph from the first example: <img class="tex-graphics" src="https://espresso.codeforces.com/7a1353a992545456c007e3071fa0a06fe46fc64e.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
from array import array
from sys import stdin
import bisect
from bisect import *
import itertools
from itertools import *
def scan_gen():
for line in stdin: yield from iter(line.split())
scan = scan_gen()
def nint(): return int(next(scan))
def nintk(k): return tuple(nint() for _ in range(k))
def nfloat(): return float(next(scan))
def intar_init(size): return array('i',[0]) *size
def intar(size=None):
if size == None: size = nint()
arr = intar_init(size)
for x in range(size): arr[x]=nint()
return arr
def gcd(x, y):
while(y):
x, y = y, x % y
return x
def solve():
n,m = nintk(2)
if m <n-1:
print("Impossible")
return
res = []
for x in range(2,n+1):
res += [(1,x)]
m-=1
for (x,y) in product(range(2,n+1), range(2,n+1)):
if x<y and gcd(x,y)==1:
if m==0 : break
res += [(x,y)]
m -=1
if m==0 : break
if m !=0:
print("Impossible")
else:
print("Possible")
for p in res:
print(*p)
solve()
``` |
575 | Bots | Title: Bots
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Sasha and Ira are two best friends. But they arenβt just friends, they are software engineers and experts in artificial intelligence. They are developing an algorithm for two bots playing a two-player game. The game is cooperative and turn based. In each turn, one of the players makes a move (it doesnβt matter which player, it's possible that players turns do not alternate).
Algorithm for bots that Sasha and Ira are developing works by keeping track of the state the game is in. Each time either bot makes a move, the state changes. And, since the game is very dynamic, it will never go back to the state it was already in at any point in the past.
Sasha and Ira are perfectionists and want their algorithm to have an optimal winning strategy. They have noticed that in the optimal winning strategy, both bots make exactly *N* moves each. But, in order to find the optimal strategy, their algorithm needs to analyze all possible states of the game (they havenβt learned about alpha-beta pruning yet) and pick the best sequence of moves.
They are worried about the efficiency of their algorithm and are wondering what is the total number of states of the game that need to be analyzed?
Input Specification:
The first and only line contains integer N.
- 1<=β€<=*N*<=β€<=106
Output Specification:
Output should contain a single integer β number of possible states modulo 109<=+<=7.
Demo Input:
['2\n']
Demo Output:
['19\n']
Note:
Start: Game is in state A.
- Turn 1: Either bot can make a move (first bot is red and second bot is blue), so there are two possible states after the first turn β B and C. - Turn 2: In both states B and C, either bot can again make a turn, so the list of possible states is expanded to include D, E, F and G. - Turn 3: Red bot already did N=2 moves when in state D, so it cannot make any more moves there. It can make moves when in state E, F and G, so states I, K and M are added to the list. Similarly, blue bot cannot make a move when in state G, but can when in D, E and F, so states H, J and L are added. - Turn 4: Red bot already did N=2 moves when in states H, I and K, so it can only make moves when in J, L and M, so states P, R and S are added. Blue bot cannot make a move when in states J, L and M, but only when in H, I and K, so states N, O and Q are added.
Overall, there are 19 possible states of the game their algorithm needs to analyze.
<img class="tex-graphics" src="https://espresso.codeforces.com/3d9ef2ab59018319b986a58a65362116fa5be88d.png" style="max-width: 100.0%;max-height: 100.0%;"/> | ```python
def f(n, mod=10**9+7):
ans = 1
for i in range(1, n + 1): ans = ans * i % mod
return ans
def g(n, mod=10**9+7):
num1 = f(n * 2)
den1 = f(n) ** 2 % mod
return num1 * pow(den1, mod - 2, mod) % mod
n = int(input()) + 1
print(g(n) - 1)
``` |
630 | Hexagons! | Title: Hexagons!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
After a probationary period in the game development company of IT City Petya was included in a group of the programmers that develops a new turn-based strategy game resembling the well known "Heroes of Might & Magic". A part of the game is turn-based fights of big squadrons of enemies on infinite fields where every cell is in form of a hexagon.
Some of magic effects are able to affect several field cells at once, cells that are situated not farther than *n* cells away from the cell in which the effect was applied. The distance between cells is the minimum number of cell border crosses on a path from one cell to another.
It is easy to see that the number of cells affected by a magic effect grows rapidly when *n* increases, so it can adversely affect the game performance. That's why Petya decided to write a program that can, given *n*, determine the number of cells that should be repainted after effect application, so that game designers can balance scale of the effects and the game performance. Help him to do it. Find the number of hexagons situated not farther than *n* cells away from a given cell.
Input Specification:
The only line of the input contains one integer *n* (0<=β€<=*n*<=β€<=109).
Output Specification:
Output one integer β the number of hexagons situated not farther than *n* cells away from a given cell.
Demo Input:
['2\n']
Demo Output:
['19']
Note:
none | ```python
n=int(input())
c=1+n*(n+1)//2*6
print(c)
``` |
411 | Multi-core Processor | Title: Multi-core Processor
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The research center Q has developed a new multi-core processor. The processor consists of *n* cores and has *k* cells of cache memory. Consider the work of this processor.
At each cycle each core of the processor gets one instruction: either do nothing, or the number of the memory cell (the core will write an information to the cell). After receiving the command, the core executes it immediately. Sometimes it happens that at one cycle, multiple cores try to write the information into a single cell. Unfortunately, the developers did not foresee the possibility of resolving conflicts between cores, so in this case there is a deadlock: all these cores and the corresponding memory cell are locked forever. Each of the locked cores ignores all further commands, and no core in the future will be able to record an information into the locked cell. If any of the cores tries to write an information into some locked cell, it is immediately locked.
The development team wants to explore the deadlock situation. Therefore, they need a program that will simulate the processor for a given set of instructions for each core within *m* cycles . You're lucky, this interesting work is entrusted to you. According to the instructions, during the *m* cycles define for each core the number of the cycle, during which it will become locked. It is believed that initially all cores and all memory cells are not locked.
Input Specification:
The first line contains three integers *n*, *m*, *k* (1<=β€<=*n*,<=*m*,<=*k*<=β€<=100). Then follow *n* lines describing instructions. The *i*-th line contains *m* integers: *x**i*1,<=*x**i*2,<=...,<=*x**im* (0<=β€<=*x**ij*<=β€<=*k*), where *x**ij* is the instruction that must be executed by the *i*-th core at the *j*-th cycle. If *x**ij* equals 0, then the corresponding instruction is Β«do nothingΒ». But if *x**ij* is a number from 1 to *k*, then the corresponding instruction is Β«write information to the memory cell number *x**ij*Β».
We assume that the cores are numbered from 1 to *n*, the work cycles are numbered from 1 to *m* and the memory cells are numbered from 1 to *k*.
Output Specification:
Print *n* lines. In the *i*-th line print integer *t**i*. This number should be equal to 0 if the *i*-th core won't be locked, or it should be equal to the number of the cycle when this core will be locked.
Demo Input:
['4 3 5\n1 0 0\n1 0 2\n2 3 1\n3 2 0\n', '3 2 2\n1 2\n1 2\n2 2\n', '1 1 1\n0\n']
Demo Output:
['1\n1\n3\n0\n', '1\n1\n0\n', '0\n']
Note:
none | ```python
n, m, k = map(int, input().split())
x = [list(map(lambda a: int(a) - 1, input().split())) for i in range(n)]
res = [-1] * n
locked = [False] * k
for t in range(m):
w = [0] * k
for i in range(n):
if res[i] == -1 and x[i][t] != -1:
w[x[i][t]] += 1
for i in range(n):
if res[i] == -1 and x[i][t] != -1 and (w[x[i][t]] >= 2 or locked[x[i][t]]):
locked[x[i][t]] = True
res[i] = t
res = [i + 1 for i in res]
for i in res:
print(i)
``` |
958 | Lightsabers (easy) | Title: Lightsabers (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There is unrest in the Galactic Senate. Several thousand solar systems have declared their intentions to leave the Republic. Master Heidi needs to select the Jedi Knights who will go on peacekeeping missions throughout the galaxy. It is well-known that the success of any peacekeeping mission depends on the colors of the lightsabers of the Jedi who will go on that mission.
Heidi has *n* Jedi Knights standing in front of her, each one with a lightsaber of one of *m* possible colors. She knows that for the mission to be the most effective, she needs to select some contiguous interval of knights such that there are exactly *k*1 knights with lightsabers of the first color, *k*2 knights with lightsabers of the second color, ..., *k**m* knights with lightsabers of the *m*-th color. Help her find out if this is possible.
Input Specification:
The first line of the input contains *n* (1<=β€<=*n*<=β€<=100) and *m* (1<=β€<=*m*<=β€<=*n*). The second line contains *n* integers in the range {1,<=2,<=...,<=*m*} representing colors of the lightsabers of the subsequent Jedi Knights. The third line contains *m* integers *k*1,<=*k*2,<=...,<=*k**m* (with ) β the desired counts of lightsabers of each color from 1 to *m*.
Output Specification:
Output YES if an interval with prescribed color counts exists, or output NO if there is none.
Demo Input:
['5 2\n1 1 2 2 1\n1 2\n']
Demo Output:
['YES\n']
Note:
none | ```python
import io, os, sys
pypyin = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
cpyin = sys.stdin.readline
input = pypyin if 'PyPy' in sys.version else cpyin
def strput():
return input().decode() if 'PyPy' in sys.version else input()
# code starts here
def main():
n, m = [int(x) for x in input().split()]
color = [int(x) - 1 for x in input().split()]
need = [int(x) for x in input().split()]
for i in range(n):
cnt = [0] * m
for j in range(i, n):
cnt[color[j]] += 1
if cnt == need:
print("YES")
return
print("NO")
if __name__ == "__main__":
main()
``` |
903 | The Modcrab | Title: The Modcrab
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vova is again playing some computer game, now an RPG. In the game Vova's character received a quest: to slay the fearsome monster called Modcrab.
After two hours of playing the game Vova has tracked the monster and analyzed its tactics. The Modcrab has *h*2 health points and an attack power of *a*2. Knowing that, Vova has decided to buy a lot of strong healing potions and to prepare for battle.
Vova's character has *h*1 health points and an attack power of *a*1. Also he has a large supply of healing potions, each of which increases his current amount of health points by *c*1 when Vova drinks a potion. All potions are identical to each other. It is guaranteed that *c*1<=><=*a*2.
The battle consists of multiple phases. In the beginning of each phase, Vova can either attack the monster (thus reducing its health by *a*1) or drink a healing potion (it increases Vova's health by *c*1; Vova's health can exceed *h*1). Then, if the battle is not over yet, the Modcrab attacks Vova, reducing his health by *a*2. The battle ends when Vova's (or Modcrab's) health drops to 0 or lower. It is possible that the battle ends in a middle of a phase after Vova's attack.
Of course, Vova wants to win the fight. But also he wants to do it as fast as possible. So he wants to make up a strategy that will allow him to win the fight after the minimum possible number of phases.
Help Vova to make up a strategy! You may assume that Vova never runs out of healing potions, and that he can always win.
Input Specification:
The first line contains three integers *h*1, *a*1, *c*1 (1<=β€<=*h*1,<=*a*1<=β€<=100, 2<=β€<=*c*1<=β€<=100) β Vova's health, Vova's attack power and the healing power of a potion.
The second line contains two integers *h*2, *a*2 (1<=β€<=*h*2<=β€<=100, 1<=β€<=*a*2<=<<=*c*1) β the Modcrab's health and his attack power.
Output Specification:
In the first line print one integer *n* denoting the minimum number of phases required to win the battle.
Then print *n* lines. *i*-th line must be equal to HEAL if Vova drinks a potion in *i*-th phase, or STRIKE if he attacks the Modcrab.
The strategy must be valid: Vova's character must not be defeated before slaying the Modcrab, and the monster's health must be 0 or lower after Vova's last action.
If there are multiple optimal solutions, print any of them.
Demo Input:
['10 6 100\n17 5\n', '11 6 100\n12 5\n']
Demo Output:
['4\nSTRIKE\nHEAL\nSTRIKE\nSTRIKE\n', '2\nSTRIKE\nSTRIKE\n']
Note:
In the first example Vova's character must heal before or after his first attack. Otherwise his health will drop to zero in 2 phases while he needs 3 strikes to win.
In the second example no healing needed, two strikes are enough to get monster to zero health and win with 6 health left. | ```python
#Bhargey Mehta (Sophomore)
#DA-IICT, Gandhinagar
import sys, math, queue, bisect
#sys.stdin = open("input.txt", "r")
MOD = 10**9+7
sys.setrecursionlimit(1000000)
h1, a1, c1 = map(int, input().split())
h2, a2 = map(int, input().split())
move = ["STRIKE", "HEAL"]
ans = []
t = 0
while h2 > 0:
if t == 0:
if a1 >= h2:
ans.append(0)
h2 -= a1
elif h1 > a2:
h2 -= a1
ans.append(0)
else:
ans.append(1)
h1 += c1
else:
h1 -= a2
t = t^1
print(len(ans))
for ai in ans: print(move[ai])
``` |
710 | Generate a String | Title: Generate a String
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of *n* letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him *x* seconds to insert or delete a letter 'a' from the text file and *y* seconds to copy the contents of the entire text file, and duplicate it.
zscoder wants to find the minimum amount of time needed for him to create the input file of exactly *n* letters 'a'. Help him to determine the amount of time needed to generate the input.
Input Specification:
The only line contains three integers *n*, *x* and *y* (1<=β€<=*n*<=β€<=107, 1<=β€<=*x*,<=*y*<=β€<=109) β the number of letters 'a' in the input file and the parameters from the problem statement.
Output Specification:
Print the only integer *t* β the minimum amount of time needed to generate the input file.
Demo Input:
['8 1 1\n', '8 1 10\n']
Demo Output:
['4\n', '8\n']
Note:
none | ```python
n,x,y=map(int,input().split())
m=2*10**7+100
dp=[1<<60]*m
dp[1]=x
dp[2]=min(2*x,x+y)
for i in range(2,m//2):
dp[2*i-1]=dp[2*i-2]+x
dp[2*i]=dp[2*i-1]+x
dp[2*i]=min(dp[2*i],dp[i]+y)
dp[2*i-1]=min(dp[2*i-1],dp[2*i]+x)
print(dp[n])
``` |
958 | Encryption (easy) | Title: Encryption (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Rebel spy Heidi has just obtained the plans for the Death Star from the Empire and, now on her way to safety, she is trying to break the encryption of the plans (of course they are encrypted β the Empire may be evil, but it is not stupid!). The encryption has several levels of security, and here is how the first one looks.
Heidi is presented with a screen that shows her a sequence of integers *A* and a positive integer *p*. She knows that the encryption code is a single number *S*, which is defined as follows:
Define the score of *X* to be the sum of the elements of *X* modulo *p*.
Heidi is given a sequence *A* that consists of *N* integers, and also given an integer *p*. She needs to split *A* into 2 parts such that:
- Each part contains at least 1 element of *A*, and each part consists of contiguous elements of *A*. - The two parts do not overlap. - The total sum *S* of the scores of those two parts is maximized. This is the encryption code.
Output the sum *S*, which is the encryption code.
Input Specification:
The first line of the input contains two space-separated integer *N* and *p* (2<=β€<=*N*<=β€<=100<=000, 2<=β€<=*p*<=β€<=10<=000) β the number of elements in *A*, and the modulo for computing scores, respectively.
The second line contains *N* space-separated integers which are the elements of *A*. Each integer is from the interval [1,<=1<=000<=000].
Output Specification:
Output the number *S* as described in the problem statement.
Demo Input:
['4 10\n3 4 7 2\n', '10 12\n16 3 24 13 9 8 7 5 12 12\n']
Demo Output:
['16\n', '13\n']
Note:
In the first example, the score is maximized if the input sequence is split into two parts as (3,β4), (7,β2). It gives the total score of <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/fc1f9aecea625f3be9a56917d3ba448d669ff278.png" style="max-width: 100.0%;max-height: 100.0%;"/>.
In the second example, the score is maximized if the first part consists of the first three elements, and the second part consists of the rest. Then, the score is <img align="middle" class="tex-formula" src="https://espresso.codeforces.com/ffd0a0f4c65b0578601ae2fe11a80aec5192f53d.png" style="max-width: 100.0%;max-height: 100.0%;"/>. | ```python
n, P = map(int, input().split())
a = list(map(lambda x: int(x) % P, input().split()))
pre = a[0]
suf = sum(a[1:]) % P
num = pre + suf
for i in range(1, n - 1):
pre += a[i]
pre %= P
suf -= a[i]
if suf < 0:
suf += P
num = max(num, pre + suf)
print(num)
``` |
999 | Reachability from the Capital | Title: Reachability from the Capital
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are $n$ cities and $m$ roads in Berland. Each road connects a pair of cities. The roads in Berland are one-way.
What is the minimum number of new roads that need to be built to make all the cities reachable from the capital?
New roads will also be one-way.
Input Specification:
The first line of input consists of three integers $n$, $m$ and $s$ ($1 \le n \le 5000, 0 \le m \le 5000, 1 \le s \le n$) β the number of cities, the number of roads and the index of the capital. Cities are indexed from $1$ to $n$.
The following $m$ lines contain roads: road $i$ is given as a pair of cities $u_i$, $v_i$ ($1 \le u_i, v_i \le n$, $u_i \ne v_i$). For each pair of cities $(u, v)$, there can be at most one road from $u$ to $v$. Roads in opposite directions between a pair of cities are allowed (i.e. from $u$ to $v$ and from $v$ to $u$).
Output Specification:
Print one integer β the minimum number of extra roads needed to make all the cities reachable from city $s$. If all the cities are already reachable from $s$, print 0.
Demo Input:
['9 9 1\n1 2\n1 3\n2 3\n1 5\n5 6\n6 1\n1 8\n9 8\n7 1\n', '5 4 5\n1 2\n2 3\n3 4\n4 1\n']
Demo Output:
['3\n', '1\n']
Note:
The first example is illustrated by the following:
For example, you can add roads ($6, 4$), ($7, 9$), ($1, 7$) to make all the cities reachable from $s = 1$.
The second example is illustrated by the following:
In this example, you can add any one of the roads ($5, 1$), ($5, 2$), ($5, 3$), ($5, 4$) to make all the cities reachable from $s = 5$. | ```python
# https://codeforces.com/contest/999
import sys
from typing import List, Optional
input = lambda: sys.stdin.readline().rstrip() # faster!
n, m, s = map(int, input().split())
s -= 1
adj = [[] for _ in range(n)] # type: List[List[Optional[int]]]
for _ in range(m):
u, v = map(lambda x: int(x) - 1, input().split())
adj[u] += [v]
reached = [False] * n
reached[s] = True
q = [s]
while q:
v = q.pop()
for u in adj[v]:
if not reached[u]:
reached[u] = True
q += [u]
not_yet_reached = []
n_reachable = [0] * n
for i in range(n):
if not reached[i]:
not_yet_reached += [i]
reached_tmp = [False] * n
reached_tmp[i] = True
q = [i]
while q:
v = q.pop()
for u in adj[v]:
if not reached[u] and not reached_tmp[u]:
reached_tmp[u] = True
q += [u]
n_reachable[i] += 1
ans = 0
not_yet_reached.sort(key=lambda i: n_reachable[i], reverse=True)
for v in not_yet_reached:
if not reached[v]:
ans += 1
q = [v]
while q:
v = q.pop()
for u in adj[v]:
if not reached[u]:
reached[u] = True
q += [u]
print(ans)
``` |
926 | Add Points | Title: Add Points
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* points on a straight line, and the *i*-th point among them is located at *x**i*. All these coordinates are distinct.
Determine the number *m* β the smallest number of points you should add on the line to make the distances between all neighboring points equal.
Input Specification:
The first line contains a single integer *n* (3<=β€<=*n*<=β€<=100<=000) β the number of points.
The second line contains a sequence of integers *x*1,<=*x*2,<=...,<=*x**n* (<=-<=109<=β€<=*x**i*<=β€<=109) β the coordinates of the points. All these coordinates are distinct. The points can be given in an arbitrary order.
Output Specification:
Print a single integer *m* β the smallest number of points you should add on the line to make the distances between all neighboring points equal.
Demo Input:
['3\n-5 10 5\n', '6\n100 200 400 300 600 500\n', '4\n10 9 0 -1\n']
Demo Output:
['1\n', '0\n', '8\n']
Note:
In the first example you can add one point with coordinate 0.
In the second example the distances between all neighboring points are already equal, so you shouldn't add anything. | ```python
def gcd(a, b):
while b:
a, b = b, a % b
return a
n = int(input())
th = 0
a = []
a = sorted(list(map(int, input().split())))
#a.sort()
e1 = a[0]
e2 = a[-1]
b = []
for i in range(len(a) - 1):
b.append(a[i+1] - a[i])
st = b[0]
for i in range(len(b) - 1):
st = gcd(st, b[i+1])
otv = ((e2 -e1)//st + 1) - n
print(otv)
``` |
792 | Divide by Three | Title: Divide by Three
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A positive integer number *n* is written on a blackboard. It consists of not more than 105 digits. You have to transform it into a beautiful number by erasing some of the digits, and you want to erase as few digits as possible.
The number is called beautiful if it consists of at least one digit, doesn't have leading zeroes and is a multiple of 3. For example, 0, 99, 10110 are beautiful numbers, and 00, 03, 122 are not.
Write a program which for the given *n* will find a beautiful number such that *n* can be transformed into this number by erasing as few digits as possible. You can erase an arbitraty set of digits. For example, they don't have to go one after another in the number *n*.
If it's impossible to obtain a beautiful number, print -1. If there are multiple answers, print any of them.
Input Specification:
The first line of input contains *n* β a positive integer number without leading zeroes (1<=β€<=*n*<=<<=10100000).
Output Specification:
Print one number β any beautiful number obtained by erasing as few as possible digits. If there is no answer, print <=-<=1.
Demo Input:
['1033\n', '10\n', '11\n']
Demo Output:
['33\n', '0\n', '-1\n']
Note:
In the first example it is enough to erase only the first digit to obtain a multiple of 3. But if we erase the first digit, then we obtain a number with a leading zero. So the minimum number of digits to be erased is two. | ```python
import re
s = input()
t = s.translate(str.maketrans("0123456789", "0120120120"))
x = (t.count('1') + t.count('2') * 2) % 3
if x:
res = ['']
l = t.rsplit("12"[x == 2], 1)
if len(l) == 2:
a = len(l[0])
res.append((s[:a], s[a + 1:]))
l = t.rsplit("12"[x == 1], 2)
if len(l) == 3:
a, b = map(len, l[:2])
res.append((s[:a], s[a + 1:a + b + 1], s[a + b + 2:]))
s = max((re.sub(r'^0*(\d)', r'\1', ''.join(e)) for e in res), key=len)
print(s or '-1')
``` |
234 | Lefthanders and Righthanders | Title: Lefthanders and Righthanders
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
One fine October day a mathematics teacher Vasily Petrov went to a class and saw there *n* pupils who sat at the desks, two people at each desk. Vasily quickly realized that number *n* is even. Like all true mathematicians, Vasily has all students numbered from 1 to *n*.
But Vasily Petrov did not like the way the children were seated at the desks. According to him, the students whose numbers differ by 1, can not sit together, as they talk to each other all the time, distract others and misbehave.
On the other hand, if a righthanded student sits at the left end of the desk and a lefthanded student sits at the right end of the desk, they hit elbows all the time and distract each other. In other cases, the students who sit at the same desk, do not interfere with each other.
Vasily knows very well which students are lefthanders and which ones are righthanders, and he asks you to come up with any order that meets these two uncomplicated conditions (students do not talk to each other and do not bump their elbows). It is guaranteed that the input is such that at least one way to seat the students always exists.
Input Specification:
The first input line contains a single even integer *n* (4<=β€<=*n*<=β€<=100) β the number of students in the class. The second line contains exactly *n* capital English letters "L" and "R". If the *i*-th letter at the second line equals "L", then the student number *i* is a lefthander, otherwise he is a righthander.
Output Specification:
Print integer pairs, one pair per line. In the *i*-th line print the numbers of students that will sit at the *i*-th desk. The first number in the pair stands for the student who is sitting to the left, and the second number stands for the student who is sitting to the right. Separate the numbers in the pairs by spaces. If there are multiple solutions, print any of them.
Demo Input:
['6\nLLRLLL\n', '4\nRRLL\n']
Demo Output:
['1 4\n2 5\n6 3\n', '3 1\n4 2\n']
Note:
none | ```python
# a - 1
inFile=open("input.txt","r")
outFiles=open("output.txt","w")
students=inFile.readline().strip()
students=int(students)
seating=inFile.readline().strip()
halfstudents=students//2
for i in range(halfstudents):
if seating[i]=="L":
outFiles.write(str(i+1) + " " + str(i+halfstudents+1)+ "\n")
else:
outFiles.write(str(i+halfstudents+1) + " " + str(i+1) + "\n")
``` |
612 | The Union of k-Segments | Title: The Union of k-Segments
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* segments on the coordinate axis Ox and the number *k*. The point is satisfied if it belongs to at least *k* segments. Find the smallest (by the number of segments) set of segments on the coordinate axis Ox which contains all satisfied points and no others.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=106) β the number of segments and the value of *k*.
The next *n* lines contain two integers *l**i*,<=*r**i* (<=-<=109<=β€<=*l**i*<=β€<=*r**i*<=β€<=109) each β the endpoints of the *i*-th segment. The segments can degenerate and intersect each other. The segments are given in arbitrary order.
Output Specification:
First line contains integer *m* β the smallest number of segments.
Next *m* lines contain two integers *a**j*,<=*b**j* (*a**j*<=β€<=*b**j*) β the ends of *j*-th segment in the answer. The segments should be listed in the order from left to right.
Demo Input:
['3 2\n0 5\n-3 2\n3 8\n', '3 2\n0 5\n-3 3\n3 8\n']
Demo Output:
['2\n0 2\n3 5\n', '1\n0 5\n']
Note:
none | ```python
from collections import defaultdict
from sys import stdin
input=lambda :stdin.readline()[:-1]
n,k=map(int,input().split())
plus=[]
minus=[]
for _ in range(n):
l,r=map(int,input().split())
plus.append(l)
minus.append(r)
plus.sort()
minus.sort()
def calc(a):
b=[]
tmp=a[0]
cnt=1
for i in a[1:]:
if tmp==i:
cnt+=1
else:
b.append((tmp,cnt))
tmp=i
cnt=1
b.append((tmp,cnt))
return b
plus=calc(plus)[::-1]
minus=calc(minus)[::-1]
ans=[]
tmp=0
while minus:
if plus and minus:
if plus[-1][0]<=minus[-1][0]:
flag=1
else:
flag=2
elif plus:
flag=1
else:
flag=2
if flag==1:
x,c=plus.pop()
if tmp<k and tmp+c>=k:
L=x
tmp+=c
else:
x,c=minus.pop()
if tmp>=k and tmp-c<k:
ans.append((L,x))
tmp-=c
print(len(ans))
for l,r in ans:
print(l,r)
``` |
825 | Five-In-a-Row | Title: Five-In-a-Row
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Alice and Bob play 5-in-a-row game. They have a playing field of size 10<=Γ<=10. In turns they put either crosses or noughts, one at a time. Alice puts crosses and Bob puts noughts.
In current match they have made some turns and now it's Alice's turn. She wonders if she can put cross in such empty cell that she wins immediately.
Alice wins if some crosses in the field form line of length not smaller than 5. This line can be horizontal, vertical and diagonal.
Input Specification:
You are given matrix 10<=Γ<=10 (10 lines of 10 characters each) with capital Latin letters 'X' being a cross, letters 'O' being a nought and '.' being an empty cell. The number of 'X' cells is equal to the number of 'O' cells and there is at least one of each type. There is at least one empty cell.
It is guaranteed that in the current arrangement nobody has still won.
Output Specification:
Print 'YES' if it's possible for Alice to win in one turn by putting cross in some empty cell. Otherwise print 'NO'.
Demo Input:
['XX.XX.....\n.....OOOO.\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n', 'XXOXX.....\nOO.O......\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n..........\n']
Demo Output:
['YES\n', 'NO\n']
Note:
none | ```python
l = [input() for _ in range(10)]
for c in range(5):
t = ['X'] * 5
t[c] = '.'
for i in range(10):
for j in range(6):
cnt = 0
for k in range(5):
if l[i][j + k] == '.':
cnt += 1
elif l[i][j + k] == 'O':
cnt += 2
if cnt == 1:
print('YES')
exit()
for i in range(6):
for j in range(10):
cnt = 0
for k in range(5):
if l[i + k][j] == '.':
cnt += 1
elif l[i + k][j] == 'O':
cnt += 2
if cnt == 1:
print('YES')
exit()
for i in range(6):
for j in range(6):
cnt = 0
for k in range(5):
if l[i + k][j + k] == '.':
cnt += 1
elif l[i + k][j + k] == 'O':
cnt += 2
if cnt == 1:
print('YES')
exit()
for i in range(4, 10):
for j in range(6):
cnt = 0
for k in range(5):
if l[i - k][j + k] == '.':
cnt += 1
elif l[i - k][j + k] == 'O':
cnt += 2
if cnt == 1:
print('YES')
exit()
print('NO')
``` |
660 | Number of Parallelograms | Title: Number of Parallelograms
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given *n* points on a plane. All the points are distinct and no three of them lie on the same line. Find the number of parallelograms with the vertices at the given points.
Input Specification:
The first line of the input contains integer *n* (1<=β€<=*n*<=β€<=2000) β the number of points.
Each of the next *n* lines contains two integers (*x**i*,<=*y**i*) (0<=β€<=*x**i*,<=*y**i*<=β€<=109) β the coordinates of the *i*-th point.
Output Specification:
Print the only integer *c* β the number of parallelograms with the vertices at the given points.
Demo Input:
['4\n0 1\n1 0\n1 1\n2 0\n']
Demo Output:
['1\n']
Note:
none | ```python
n = int(input())
a = []
for _ in range(n):
xy = list(map(int, input().split()))
a.append(xy)
midpoint = {}
for i in range(n):
for j in range(i + 1, n):
x1, y1 = a[i][0], a[i][1]
x2, y2 = a[j][0], a[j][1]
dx = x2 + x1
dy = y2 + y1
midpoint[(dx / 2, dy / 2)] = midpoint.get((dx / 2, dy / 2), 0) + 1
ans = 0
for k, v in midpoint.items():
#print(k, v, sep=' : ')
ans += (v * (v - 1)) // 2
print(ans)
#import matplotlib.pyplot as plt
#import numpy as np
#x, y = zip(*a)
#plt.scatter(x, y)
#plt.grid()
#plt.show()
``` |
958 | Death Stars (easy) | Title: Death Stars (easy)
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The stardate is 1977 and the science and art of detecting Death Stars is in its infancy. Princess Heidi has received information about the stars in the nearby solar system from the Rebel spies and now, to help her identify the exact location of the Death Star, she needs to know whether this information is correct.
Two rebel spies have provided her with the maps of the solar system. Each map is an *N*<=Γ<=*N* grid, where each cell is either occupied by a star or empty. To see whether the information is correct, Heidi needs to know whether the two maps are of the same solar system, or if possibly one of the spies is actually an Empire double agent, feeding her false information.
Unfortunately, spies may have accidentally rotated a map by 90, 180, or 270 degrees, or flipped it along the vertical or the horizontal axis, before delivering it to Heidi. If Heidi can rotate or flip the maps so that two of them become identical, then those maps are of the same solar system. Otherwise, there are traitors in the Rebel ranks! Help Heidi find out.
Input Specification:
The first line of the input contains one number *N* (1<=β€<=*N*<=β€<=10) β the dimension of each map. Next *N* lines each contain *N* characters, depicting the first map: 'X' indicates a star, while 'O' indicates an empty quadrant of space. Next *N* lines each contain *N* characters, depicting the second map in the same format.
Output Specification:
The only line of output should contain the word Yes if the maps are identical, or No if it is impossible to match them by performing rotations and translations.
Demo Input:
['4\nXOOO\nXXOO\nOOOO\nXXXX\nXOOO\nXOOO\nXOXO\nXOXX\n', '2\nXX\nOO\nXO\nOX\n']
Demo Output:
['Yes\n', 'No\n']
Note:
In the first test, you can match the first map to the second map by first flipping the first map along the vertical axis, and then by rotating it 90 degrees clockwise. | ```python
def rotate_90(a):
b=[]
for x in range(len(a)):
l=[]
for y in range(len(a)-1,-1,-1):
l.append(a[y][x])
b.append(l)
return b
def flip(a):
b=[]
for x in range(len(a)):
l=[]
for y in range(len(a)-1,-1,-1):
l.append(a[x][y])
b.append(l)
return b
n=int(input())
l=[]
for i in range(n):
a=input()
l2=[]
for i2 in a:
l2.append(i2)
l.append(l2)
l2=[]
for i in range(n):
a=input()
l3=[]
for i2 in a:
l3.append(i2)
l2.append(l3)
d='no'
for i in range(4):
l = rotate_90(l)
if l==l2:
d='yes'
l=flip(l)
for i in range(4):
l = rotate_90(l)
if l==l2:
d='yes'
print(d)
``` |
962 | Simple Cycles Edges | Title: Simple Cycles Edges
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given an undirected graph, consisting of $n$ vertices and $m$ edges. The graph does not necessarily connected. Guaranteed, that the graph does not contain multiple edges (more than one edges between a pair of vertices) or loops (edges from a vertex to itself).
A cycle in a graph is called a simple, if it contains each own vertex exactly once. So simple cycle doesn't allow to visit a vertex more than once in a cycle.
Determine the edges, which belong to exactly on one simple cycle.
Input Specification:
The first line contain two integers $n$ and $m$ $(1 \le n \le 100\,000$, $0 \le m \le \min(n \cdot (n - 1) / 2, 100\,000))$ β the number of vertices and the number of edges.
Each of the following $m$ lines contain two integers $u$ and $v$ ($1 \le u, v \le n$, $u \neq v$) β the description of the edges.
Output Specification:
In the first line print the number of edges, which belong to exactly one simple cycle.
In the second line print the indices of edges, which belong to exactly one simple cycle, in increasing order. The edges are numbered from one in the same order as they are given in the input.
Demo Input:
['3 3\n1 2\n2 3\n3 1\n', '6 7\n2 3\n3 4\n4 2\n1 2\n1 5\n5 6\n6 1\n', '5 6\n1 2\n2 3\n2 4\n4 3\n2 5\n5 3\n']
Demo Output:
['3\n1 2 3 \n', '6\n1 2 3 5 6 7 \n', '0\n\n']
Note:
none | ```python
import sys
def solve():
n, m = map(int, input().split())
g = [[] for i in range(n+1)]
E = [None]*m
for i in range(m):
u, v = map(int, input().split())
E[i] = (u, v)
g[u].append([v,i])
g[v].append([u,i])
P = [-1]*(n+1)
I = [0]*(n+1)
st = []
D = [0]*(n+1)
W = [0]*(n+1)
S = [-1]*m
U = [-1]*m
V = [-1]*(n+1)
def getp(x):
if x == S[x]:
return x
S[x] = getp(S[x])
return S[x]
def join(u, v):
if u == -1:
return v
u = getp(u)
v = getp(v)
if u == v:
return u
if U[u] > U[v]:
S[u] = v
return v
else:
S[v] = u
return u
for i in range(1, n+1):
if P[i] >= 0:
continue
P[i] = 0
D[i] = 0
st.append(i)
while len(st) > 0:
x = st[-1]
p = P[x]
while I[x] < len(g[x]):
v, w = g[x][I[x]]
I[x] += 1
if P[v] < 0:
D[v] = D[x] + 1
P[v] = x
W[v] = w
st.append(v)
break
elif p != v and D[v] < D[x]:
S[w] = w
U[w] = D[v]
V[x] = join(V[x], w)
else:
if V[x] >= 0:
v = getp(V[x])
if U[v] < D[x] - 1:
V[p] = join(V[p], v)
st.pop()
F = [0]*m
for i in range(m):
if S[i] >= 0:
w = getp(i)
F[w] += 1
r = []
for i in range(m):
if F[i] == 1:
r.append(i)
u, v = E[i]
if D[u] < D[v]:
u, v = v, u
while u != v:
r.append(W[u])
u = P[u]
r.sort()
print(len(r))
print(' '.join(str(i+1) for i in r))
solve()
``` |
818 | Level Generation | Title: Level Generation
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan is developing his own computer game. Now he tries to create some levels for his game. But firstly for each level he needs to draw a graph representing the structure of the level.
Ivan decided that there should be exactly *n**i* vertices in the graph representing level *i*, and the edges have to be bidirectional. When constructing the graph, Ivan is interested in special edges called bridges. An edge between two vertices *u* and *v* is called a bridge if this edge belongs to every path between *u* and *v* (and these vertices will belong to different connected components if we delete this edge). For each level Ivan wants to construct a graph where at least half of the edges are bridges. He also wants to maximize the number of edges in each constructed graph.
So the task Ivan gave you is: given *q* numbers *n*1,<=*n*2,<=...,<=*n**q*, for each *i* tell the maximum number of edges in a graph with *n**i* vertices, if at least half of the edges are bridges. Note that the graphs cannot contain multiple edges or self-loops.
Input Specification:
The first line of input file contains a positive integer *q* (1<=β€<=*q*<=β€<=100<=000) β the number of graphs Ivan needs to construct.
Then *q* lines follow, *i*-th line contains one positive integer *n**i* (1<=β€<=*n**i*<=β€<=2Β·109) β the number of vertices in *i*-th graph.
Note that in hacks you have to use *q*<==<=1.
Output Specification:
Output *q* numbers, *i*-th of them must be equal to the maximum number of edges in *i*-th graph.
Demo Input:
['3\n3\n4\n6\n']
Demo Output:
['2\n3\n6\n']
Note:
In the first example it is possible to construct these graphs:
1. 1β-β2, 1β-β3; 1. 1β-β2, 1β-β3, 2β-β4; 1. 1β-β2, 1β-β3, 2β-β3, 1β-β4, 2β-β5, 3β-β6. | ```python
from math import floor, ceil, sqrt
def solve(n):
quad = sqrt(2*n+1/4)-1/2
x = floor(quad)
y = ceil(quad)
a = int(x*(x-1)/2 + n - x)
b = n - x
c = n - y
d = 2*c
if a > d:
print(a)
else:
print(d)
return
n=int(input())
for i in range (n):
solve(int(input()))
``` |
1,005 | Summarize to the Power of Two | Title: Summarize to the Power of Two
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
A sequence $a_1, a_2, \dots, a_n$ is called good if, for each element $a_i$, there exists an element $a_j$ ($i \ne j$) such that $a_i+a_j$ is a power of two (that is, $2^d$ for some non-negative integer $d$).
For example, the following sequences are good:
- $[5, 3, 11]$ (for example, for $a_1=5$ we can choose $a_2=3$. Note that their sum is a power of two. Similarly, such an element can be found for $a_2$ and $a_3$), - $[1, 1, 1, 1023]$, - $[7, 39, 89, 25, 89]$, - $[]$.
Note that, by definition, an empty sequence (with a length of $0$) is good.
For example, the following sequences are not good:
- $[16]$ (for $a_1=16$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[4, 16]$ (for $a_1=4$, it is impossible to find another element $a_j$ such that their sum is a power of two), - $[1, 3, 2, 8, 8, 8]$ (for $a_3=2$, it is impossible to find another element $a_j$ such that their sum is a power of two).
You are given a sequence $a_1, a_2, \dots, a_n$. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.
Input Specification:
The first line contains the integer $n$ ($1 \le n \le 120000$) β the length of the given sequence.
The second line contains the sequence of integers $a_1, a_2, \dots, a_n$ ($1 \le a_i \le 10^9$).
Output Specification:
Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all $n$ elements, make it empty, and thus get a good sequence.
Demo Input:
['6\n4 7 1 5 4 9\n', '5\n1 2 3 4 5\n', '1\n16\n', '4\n1 1 1 1023\n']
Demo Output:
['1\n', '2\n', '1\n', '0\n']
Note:
In the first example, it is enough to delete one element $a_4=5$. The remaining elements form the sequence $[4, 7, 1, 4, 9]$, which is good. | ```python
def f(x):
i = 0
while x >= 2**i:
i += 1
return i
# with open('test.txt') as file:
# n = file.readline()
# l = list(map(int, file.readline().split()))
n = int(input())
l = list(map(int, input().split()))
if not l:
print(0)
else:
unique = {}
cnt = len(l)
mx = 0
for x in l:
try:
unique[x] += 1
except KeyError:
unique.update({x: 1})
if x > mx:
mx = x
checked = {}
for k, v in unique.items():
if cnt == 0:
break
x = k
try:
checked[x] += 0
continue
except KeyError:
closest_pow = f(x)
was = closest_pow
while was != closest_pow-(int(n)-1) and 2**closest_pow - x <= mx:
y = 2**closest_pow - x
# print(x, y, cnt)
if x == y:
if v == 1:
closest_pow += 1
continue
cnt -= v
checked.update({x: 1})
break
try:
unique[y] += 0
except KeyError:
closest_pow += 1
continue
cnt -= v
try:
checked[y] += 0
except KeyError:
cnt -= unique[y]
checked.update({x: 1})
checked.update({y: 1})
break
print(cnt)
# Sat Oct 02 2021 12:09:20 GMT+0300 (ΠΠΎΡΠΊΠ²Π°, ΡΡΠ°Π½Π΄Π°ΡΡΠ½ΠΎΠ΅ Π²ΡΠ΅ΠΌΡ)
``` |
1,009 | Intercity Travelling | Title: Intercity Travelling
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.
The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance between Moscow and Saratov is $n$ km. Let's say that Moscow is situated at the point with coordinate $0$ km, and Saratov β at coordinate $n$ km.
Driving for a long time may be really difficult. Formally, if Leha has already covered $i$ kilometers since he stopped to have a rest, he considers the difficulty of covering $(i + 1)$-th kilometer as $a_{i + 1}$. It is guaranteed that for every $i \in [1, n - 1]$ $a_i \le a_{i + 1}$. The difficulty of the journey is denoted as the sum of difficulties of each kilometer in the journey.
Fortunately, there may be some rest sites between Moscow and Saratov. Every integer point from $1$ to $n - 1$ may contain a rest site. When Leha enters a rest site, he may have a rest, and the next kilometer will have difficulty $a_1$, the kilometer after it β difficulty $a_2$, and so on.
For example, if $n = 5$ and there is a rest site in coordinate $2$, the difficulty of journey will be $2a_1 + 2a_2 + a_3$: the first kilometer will have difficulty $a_1$, the second one β $a_2$, then Leha will have a rest, and the third kilometer will have difficulty $a_1$, the fourth β $a_2$, and the last one β $a_3$. Another example: if $n = 7$ and there are rest sites in coordinates $1$ and $5$, the difficulty of Leha's journey is $3a_1 + 2a_2 + a_3 + a_4$.
Leha doesn't know which integer points contain rest sites. So he has to consider every possible situation. Obviously, there are $2^{n - 1}$ different distributions of rest sites (two distributions are different if there exists some point $x$ such that it contains a rest site in exactly one of these distributions). Leha considers all these distributions to be equiprobable. He wants to calculate $p$ β the expected value of difficulty of his journey.
Obviously, $p \cdot 2^{n - 1}$ is an integer number. You have to calculate it modulo $998244353$.
Input Specification:
The first line contains one number $n$ ($1 \le n \le 10^6$) β the distance from Moscow to Saratov.
The second line contains $n$ integer numbers $a_1$, $a_2$, ..., $a_n$ ($1 \le a_1 \le a_2 \le \dots \le a_n \le 10^6$), where $a_i$ is the difficulty of $i$-th kilometer after Leha has rested.
Output Specification:
Print one number β $p \cdot 2^{n - 1}$, taken modulo $998244353$.
Demo Input:
['2\n1 2\n', '4\n1 3 3 7\n']
Demo Output:
['5\n', '60\n']
Note:
none | ```python
MOD=998244353
def f(n):
if(n==0):
return 1
if(n==1):
return 3
return ((n+2)*pow(2,n-1,MOD))%MOD
n=int(input())
ar=list(map(int,input().split()))[::-1]
S=0
for i in range(n):
S+=ar[i]*f(i)
print(S%MOD)
``` |
598 | Nearest vectors | Title: Nearest vectors
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
You are given the set of vectors on the plane, each of them starting at the origin. Your task is to find a pair of vectors with the minimal non-oriented angle between them.
Non-oriented angle is non-negative value, minimal between clockwise and counterclockwise direction angles. Non-oriented angle is always between 0 and Ο. For example, opposite directions vectors have angle equals to Ο.
Input Specification:
First line of the input contains a single integer *n* (2<=β€<=*n*<=β€<=100<=000)Β β the number of vectors.
The *i*-th of the following *n* lines contains two integers *x**i* and *y**i* (|*x*|,<=|*y*|<=β€<=10<=000,<=*x*2<=+<=*y*2<=><=0)Β β the coordinates of the *i*-th vector. Vectors are numbered from 1 to *n* in order of appearing in the input. It is guaranteed that no two vectors in the input share the same direction (but they still can have opposite directions).
Output Specification:
Print two integer numbers *a* and *b* (*a*<=β <=*b*)Β β a pair of indices of vectors with the minimal non-oriented angle. You can print the numbers in any order. If there are many possible answers, print any.
Demo Input:
['4\n-1 0\n0 -1\n1 0\n1 1\n', '6\n-1 0\n0 -1\n1 0\n1 1\n-4 -5\n-4 -6\n']
Demo Output:
['3 4\n', '6 5']
Note:
none | ```python
from math import atan2
inner = lambda a, b: a[0] * b[0] + a[1] * b[1]
outer = lambda a, b: a[0] * b[1] - a[1] * b[0]
N = int(input())
vectors = []
for i in range(N):
x, y = map(int, input().split())
vectors.append((atan2(y, x), (x, y), i + 1))
vectors.sort()
diff = []
for i in range(N):
diff.append([inner(vectors[i][1], vectors[(i+1)%N][1]), abs(outer(vectors[i][1], vectors[(i+1)%N][1])), vectors[i][2], vectors[(i+1)%N][2]])
min_diff = diff[0]
for d in diff:
if outer(d[:2], min_diff[:2]) > 0: min_diff = d
print(min_diff[2], min_diff[3])
``` |
988 | Rain and Umbrellas | Title: Rain and Umbrellas
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp lives on a coordinate line at the point $x = 0$. He goes to his friend that lives at the point $x = a$. Polycarp can move only from left to right, he can pass one unit of length each second.
Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $n$ non-intersecting segments, the $i$-th segment which is in the rain is represented as $[l_i, r_i]$ ($0 \le l_i < r_i \le a$).
There are $m$ umbrellas lying on the line, the $i$-th umbrella is located at point $x_i$ ($0 \le x_i \le a$) and has weight $p_i$. When Polycarp begins his journey, he doesn't have any umbrellas.
During his journey from $x = 0$ to $x = a$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $x$ to $x + 1$ if a segment $[x, x + 1]$ is in the rain (i.e. if there exists some $i$ such that $l_i \le x$ and $x + 1 \le r_i$).
The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.
Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.
Can Polycarp make his way from point $x = 0$ to point $x = a$? If yes, find the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
Input Specification:
The first line contains three integers $a$, $n$ and $m$ ($1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil$) β the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas.
Each of the next $n$ lines contains two integers $l_i$ and $r_i$ ($0 \le l_i < r_i \le a$) β the borders of the $i$-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments $i$ and $j$ either $r_i < l_j$ or $r_j < l_i$.
Each of the next $m$ lines contains two integers $x_i$ and $p_i$ ($0 \le x_i \le a$, $1 \le p_i \le 10^5$) β the location and the weight of the $i$-th umbrella.
Output Specification:
Print "-1" (without quotes) if Polycarp can't make his way from point $x = 0$ to point $x = a$. Otherwise print one integer β the minimum total fatigue after reaching $x = a$, if Polycarp picks up and throws away umbrellas optimally.
Demo Input:
['10 2 4\n3 7\n8 10\n0 10\n3 4\n8 1\n1 2\n', '10 1 1\n0 9\n0 5\n', '10 1 1\n0 9\n1 5\n']
Demo Output:
['14\n', '45\n', '-1\n']
Note:
In the first example the only possible strategy is to take the fourth umbrella at the point $x = 1$, keep it till the point $x = 7$ (the total fatigue at $x = 7$ will be equal to $12$), throw it away, move on from $x = 7$ to $x = 8$ without an umbrella, take the third umbrella at $x = 8$ and keep it till the end (the total fatigue at $x = 10$ will be equal to $14$).
In the second example the only possible strategy is to take the first umbrella, move with it till the point $x = 9$, throw it away and proceed without an umbrella till the end. | ```python
import sys,bisect
from functools import cache
read=lambda:map(int,sys.stdin.readline().split())
dst,n,m=read()
rain=sorted([[*read()] for _ in range(n)])
umb=sorted([[*read()] for _ in range(m)])+[[dst,dst]]
if umb[0][0]>rain[0][0]:quit(print(-1))
@cache
def dfs(i):
if i==0:return 0
cur=umb[i][0]
ridx=bisect.bisect(rain,[cur])
if ridx==0:return dfs(i-1)
drop=min(cur,rain[ridx-1][1])
res=0xFFFF0204
for j in range(i):
if drop>umb[j][0]:
res=min(res,dfs(j)+umb[j][1]*(drop-umb[j][0]))
return res
print(dfs(m))
``` |
234 | Reading | Title: Reading
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Vasya is going to the Olympics in the city Ntown by train. The boy wants to read the textbook to prepare for the Olympics. He counted that he needed *k* hours for this. He also found that the light in the train changes every hour. The light is measured on a scale from 0 to 100, where 0 is very dark, and 100 is very light.
Vasya has a train lighting schedule for all *n* hours of the trip β *n* numbers from 0 to 100 each (the light level in the first hour, the second hour and so on). During each of those hours he will either read the whole time, or not read at all. He wants to choose *k* hours to read a book, not necessarily consecutive, so that the minimum level of light among the selected hours were maximum. Vasya is very excited before the upcoming contest, help him choose reading hours.
Input Specification:
The first input line contains two integers *n* and *k* (1<=β€<=*n*<=β€<=1000,<=1<=β€<=*k*<=β€<=*n*) β the number of hours on the train and the number of hours to read, correspondingly. The second line contains *n* space-separated integers *a**i* (0<=β€<=*a**i*<=β€<=100), *a**i* is the light level at the *i*-th hour.
Output Specification:
In the first output line print the minimum light level Vasya will read at. In the second line print *k* distinct space-separated integers *b*1,<=*b*2,<=...,<=*b**k*, β the indexes of hours Vasya will read at (1<=β€<=*b**i*<=β€<=*n*). The hours are indexed starting from 1. If there are multiple optimal solutions, print any of them. Print the numbers *b**i* in an arbitrary order.
Demo Input:
['5 3\n20 10 30 40 10\n', '6 5\n90 20 35 40 60 100\n']
Demo Output:
['20\n1 3 4 \n', '35\n1 3 4 5 6 \n']
Note:
In the first sample Vasya should read at the first hour (light 20), third hour (light 30) and at the fourth hour (light 40). The minimum light Vasya will have to read at is 20. | ```python
F=open('input.txt','r')
W=open('output.txt','w')
I=lambda:map(int,F.readline().split())
n,k=I()
a=sorted(zip(I(),range(n)))[::-1]
W.write(str(a[k-1][0])+'\n'+' '.join(map(str,[y+1 for x,y in a[:k]])))
W.close()
``` |
883 | Photo Processing | Title: Photo Processing
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Evlampiy has found one more cool application to process photos. However the application has certain limitations.
Each photo *i* has a contrast *v**i*. In order for the processing to be truly of high quality, the application must receive at least *k* photos with contrasts which differ as little as possible.
Evlampiy already knows the contrast *v**i* for each of his *n* photos. Now he wants to split the photos into groups, so that each group contains at least *k* photos. As a result, each photo must belong to exactly one group.
He considers a processing time of the *j*-th group to be the difference between the maximum and minimum values of *v**i* in the group. Because of multithreading the processing time of a division into groups is the maximum processing time among all groups.
Split *n* photos into groups in a such way that the processing time of the division is the minimum possible, i.e. that the the maximum processing time over all groups as least as possible.
Input Specification:
The first line contains two integers *n* and *k* (1<=β€<=*k*<=β€<=*n*<=β€<=3Β·105) β number of photos and minimum size of a group.
The second line contains *n* integers *v*1,<=*v*2,<=...,<=*v**n* (1<=β€<=*v**i*<=β€<=109), where *v**i* is the contrast of the *i*-th photo.
Output Specification:
Print the minimal processing time of the division into groups.
Demo Input:
['5 2\n50 110 130 40 120\n', '4 1\n2 3 4 1\n']
Demo Output:
['20\n', '0\n']
Note:
In the first example the photos should be split into 2 groups: [40,β50] and [110,β120,β130]. The processing time of the first group is 10, and the processing time of the second group is 20. Maximum among 10 and 20 is 20. It is impossible to split the photos into groups in a such way that the processing time of division is less than 20.
In the second example the photos should be split into four groups, each containing one photo. So the minimal possible processing time of a division is 0. | ```python
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from functools import lru_cache
from math import factorial, comb, sqrt, gcd, lcm, log2
from copy import deepcopy
import heapq
from sys import stdin, stdout
input = stdin.readline
def main():
n, k = map(int, input().split())
L = list(map(int, input().split()))
L.sort()
left = 0
right = L[-1] - L[0]
def check(flag):
# dp[i] 葨瀺 δ»₯ L[i] δΈΊη»ε°Ύηεζ°η»ζ―ε¦ζ»‘θΆ³δ»₯δΈθ¦ζ±
# ε°ζ°η»εζθ₯εΉ²η»οΌζ―η»ζε°ζ k δΈͺζ°οΌδΈζ―η»ηζ倧εΌ- ζε°εΌ <= flag
dp = [False] * n
q = deque([-1]) # δΏεζζ True εΌηη΄’εΌζ₯δΌε dp ηζΆι΄ε€ζεΊ¦
for i in range(k - 1, n):
while len(q) > 0 and L[i] - L[q[0] + 1] > flag and i - q[0] >= k:
q.popleft()
if len(q) > 0 and i - q[0] >= k:
dp[i] = True
q.append(i)
return dp[-1]
while left < right:
middle = (left + right) // 2
if check(middle) is True:
right = middle
else:
left = middle + 1
print(left)
if __name__ == "__main__":
main()
``` |
825 | String Compression | Title: String Compression
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Ivan wants to write a letter to his friend. The letter is a string *s* consisting of lowercase Latin letters.
Unfortunately, when Ivan started writing the letter, he realised that it is very long and writing the whole letter may take extremely long time. So he wants to write the compressed version of string *s* instead of the string itself.
The compressed version of string *s* is a sequence of strings *c*1,<=*s*1,<=*c*2,<=*s*2,<=...,<=*c**k*,<=*s**k*, where *c**i* is the decimal representation of number *a**i* (without any leading zeroes) and *s**i* is some string consisting of lowercase Latin letters. If Ivan writes string *s*1 exactly *a*1 times, then string *s*2 exactly *a*2 times, and so on, the result will be string *s*.
The length of a compressed version is |*c*1|<=+<=|*s*1|<=+<=|*c*2|<=+<=|*s*2|... |*c**k*|<=+<=|*s**k*|. Among all compressed versions Ivan wants to choose a version such that its length is minimum possible. Help Ivan to determine minimum possible length.
Input Specification:
The only line of input contains one string *s* consisting of lowercase Latin letters (1<=β€<=|*s*|<=β€<=8000).
Output Specification:
Output one integer number β the minimum possible length of a compressed version of *s*.
Demo Input:
['aaaaaaaaaa\n', 'abcab\n', 'cczabababab\n']
Demo Output:
['3\n', '6\n', '7\n']
Note:
In the first example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 10, *s*<sub class="lower-index">1</sub> is a.
In the second example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 1, *s*<sub class="lower-index">1</sub> is abcab.
In the third example Ivan will choose this compressed version: *c*<sub class="lower-index">1</sub> is 2, *s*<sub class="lower-index">1</sub> is c, *c*<sub class="lower-index">2</sub> is 1, *s*<sub class="lower-index">2</sub> is z, *c*<sub class="lower-index">3</sub> is 4, *s*<sub class="lower-index">3</sub> is ab. | ```python
def prefix(s):
p = [0]
for i in range(1, len(s)):
j = p[-1]
while j > 0 and s[j] != s[i]:
j = p[j - 1]
if s[i] == s[j]:
j += 1
p.append(j)
return p
s = input()
n = len(s)
ans = [0] * (n + 1)
i = n - 1
while i >= 0:
p = prefix(s[i:])
ans[i] = 2 + ans[i + 1]
for j in range(len(p)):
z = 1
if (j + 1) % (j + 1 - p[j]) == 0:
z = (j + 1) // (j + 1 - p[j])
res = len(str(z)) + (j + 1) // z + ans[i + j + 1]
ans[i] = min(ans[i], res)
i -= 1
print(ans[0])
``` |
120 | Put Knight! | Title: Put Knight!
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya and Gena play a very interesting game "Put a Knight!" on a chessboard *n*<=Γ<=*n* in size. In this game they take turns to put chess pieces called "knights" on the board so that no two knights could threat each other. A knight located in square (*r*,<=*c*) can threat squares (*r*<=-<=1,<=*c*<=+<=2), (*r*<=-<=1,<=*c*<=-<=2), (*r*<=+<=1,<=*c*<=+<=2), (*r*<=+<=1,<=*c*<=-<=2), (*r*<=-<=2,<=*c*<=+<=1), (*r*<=-<=2,<=*c*<=-<=1), (*r*<=+<=2,<=*c*<=+<=1) and (*r*<=+<=2,<=*c*<=-<=1) (some of the squares may be located outside the chessboard). The player who can't put a new knight during his move loses. Determine which player wins considering that both players play optimally well and Petya starts.
Input Specification:
The first line contains integer *T* (1<=β€<=*T*<=β€<=100) β the number of boards, for which you should determine the winning player. Next *T* lines contain *T* integers *n**i* (1<=β€<=*n**i*<=β€<=10000) β the sizes of the chessboards.
Output Specification:
For each *n**i*<=Γ<=*n**i* board print on a single line "0" if Petya wins considering both players play optimally well. Otherwise, print "1".
Demo Input:
['2\n2\n1\n']
Demo Output:
['1\n0\n']
Note:
none | ```python
r = open('input.txt','r')
w = open('output.txt','w')
n = int(r.readline())
t = ['10'[int(r.readline()) % 2] for i in range(n)]
w.write('\n'.join(t))
``` |
978 | Petya's Exams | Title: Petya's Exams
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Petya studies at university. The current academic year finishes with $n$ special days. Petya needs to pass $m$ exams in those special days. The special days in this problem are numbered from $1$ to $n$.
There are three values about each exam:
- $s_i$ β the day, when questions for the $i$-th exam will be published, - $d_i$ β the day of the $i$-th exam ($s_i < d_i$), - $c_i$ β number of days Petya needs to prepare for the $i$-th exam. For the $i$-th exam Petya should prepare in days between $s_i$ and $d_i-1$, inclusive.
There are three types of activities for Petya in each day: to spend a day doing nothing (taking a rest), to spend a day passing exactly one exam or to spend a day preparing for exactly one exam. So he can't pass/prepare for multiple exams in a day. He can't mix his activities in a day. If he is preparing for the $i$-th exam in day $j$, then $s_i \le j < d_i$.
It is allowed to have breaks in a preparation to an exam and to alternate preparations for different exams in consecutive days. So preparation for an exam is not required to be done in consecutive days.
Find the schedule for Petya to prepare for all exams and pass them, or report that it is impossible.
Input Specification:
The first line contains two integers $n$ and $m$ $(2 \le n \le 100, 1 \le m \le n)$ β the number of days and the number of exams.
Each of the following $m$ lines contains three integers $s_i$, $d_i$, $c_i$ $(1 \le s_i < d_i \le n, 1 \le c_i \le n)$ β the day, when questions for the $i$-th exam will be given, the day of the $i$-th exam, number of days Petya needs to prepare for the $i$-th exam.
Guaranteed, that all the exams will be in different days. Questions for different exams can be given in the same day. It is possible that, in the day of some exam, the questions for other exams are given.
Output Specification:
If Petya can not prepare and pass all the exams, print -1. In case of positive answer, print $n$ integers, where the $j$-th number is:
- $(m + 1)$, if the $j$-th day is a day of some exam (recall that in each day no more than one exam is conducted), - zero, if in the $j$-th day Petya will have a rest, - $i$ ($1 \le i \le m$), if Petya will prepare for the $i$-th exam in the day $j$ (the total number of days Petya prepares for each exam should be strictly equal to the number of days needed to prepare for it).Assume that the exams are numbered in order of appearing in the input, starting from $1$.If there are multiple schedules, print any of them.
Demo Input:
['5 2\n1 3 1\n1 5 1\n', '3 2\n1 3 1\n1 2 1\n', '10 3\n4 7 2\n1 10 3\n8 9 1\n']
Demo Output:
['1 2 3 0 3 \n', '-1\n', '2 2 2 1 1 0 4 3 4 4 \n']
Note:
In the first example Petya can, for example, prepare for exam $1$ in the first day, prepare for exam $2$ in the second day, pass exam $1$ in the third day, relax in the fourth day, and pass exam $2$ in the fifth day. So, he can prepare and pass all exams.
In the second example, there are three days and two exams. So, Petya can prepare in only one day (because in two other days he should pass exams). Then Petya can not prepare and pass all exams. | ```python
(n, m) = map(int, input().split())
array = [0] * (n + 1)
lst = []
for x in range(m):
(s, d, c) = map(int, input().split())
lst.append((d, s, c, x + 1))
lst.sort()
i = 0
flag = True
for (d, s, c, p) in lst:
x = s
while c > 0 and x < d:
if array[x] == 0:
array[x] = p
c -= 1
x += 1
if c != 0:
flag = False
break
else:
array[d] = m + 1
if flag:
print(*array[1:])
else:
print(-1)
``` |
241 | Old Peykan | Title: Old Peykan
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
There are *n* cities in the country where the Old Peykan lives. These cities are located on a straight line, we'll denote them from left to right as *c*1,<=*c*2,<=...,<=*c**n*. The Old Peykan wants to travel from city *c*1 to *c**n* using roads. There are (*n*<=-<=1) one way roads, the *i*-th road goes from city *c**i* to city *c**i*<=+<=1 and is *d**i* kilometers long.
The Old Peykan travels 1 kilometer in 1 hour and consumes 1 liter of fuel during this time.
Each city *c**i* (except for the last city *c**n*) has a supply of *s**i* liters of fuel which immediately transfers to the Old Peykan if it passes the city or stays in it. This supply refreshes instantly *k* hours after it transfers. The Old Peykan can stay in a city for a while and fill its fuel tank many times.
Initially (at time zero) the Old Peykan is at city *c*1 and *s*1 liters of fuel is transferred to it's empty tank from *c*1's supply. The Old Peykan's fuel tank capacity is unlimited. Old Peykan can not continue its travel if its tank is emptied strictly between two cities.
Find the minimum time the Old Peykan needs to reach city *c**n*.
Input Specification:
The first line of the input contains two space-separated integers *m* and *k* (1<=β€<=*m*,<=*k*<=β€<=1000). The value *m* specifies the number of roads between cities which is equal to *n*<=-<=1.
The next line contains *m* space-separated integers *d*1,<=*d*2,<=...,<=*d**m* (1<=β€<=*d**i*<=β€<=1000) and the following line contains *m* space-separated integers *s*1,<=*s*2,<=...,<=*s**m* (1<=β€<=*s**i*<=β€<=1000).
Output Specification:
In the only line of the output print a single integer β the minimum time required for The Old Peykan to reach city *c**n* from city *c*1.
Demo Input:
['4 6\n1 2 5 2\n2 3 3 4\n', '2 3\n5 6\n5 5\n']
Demo Output:
['10\n', '14\n']
Note:
In the second sample above, the Old Peykan stays in *c*<sub class="lower-index">1</sub> for 3 hours. | ```python
a,b=map(int,input().split())
d=list(map(int,input().split()))
p=list(map(int,input().split()))
t=0;d1=0;i=0
while i<a:
if t+sum(p[i::])-sum(d[i::])<0:
j=i;pr=p[i]
while j<a and pr>=p[j]:j+=1
k=(-t-sum(p[i:j])-1+sum(d[i:j])+pr)//pr
d1+=b*k
t=(pr*k-(-t-sum(p[i:j])+sum(d[i:j])))%pr
i=j
else:i+=1
print(sum(d)+d1)
``` |
926 | A Vital Problem | Title: A Vital Problem
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Polycarp has a strict daily schedule. He has *n* alarms set for each day, and the *i*-th alarm rings each day at the same time during exactly one minute.
Determine the longest time segment when Polycarp can sleep, i.Β e. no alarm rings in that period. It is possible that Polycarp begins to sleep in one day, and wakes up in another.
Input Specification:
The first line contains a single integer *n* (1<=β€<=*n*<=β€<=100) β the number of alarms.
Each of the next *n* lines contains a description of one alarm. Each description has a format "hh:mm", where *hh* is the hour when the alarm rings, and *mm* is the minute of that hour when the alarm rings. The number of hours is between 0 and 23, and the number of minutes is between 0 and 59. All alarm times are distinct. The order of the alarms is arbitrary.
Each alarm starts ringing in the beginning of the corresponding minute and rings for exactly one minute (i.Β e. stops ringing in the beginning of the next minute). Polycarp can start sleeping instantly when no alarm is ringing, and he wakes up at the moment when some alarm starts ringing.
Output Specification:
Print a line in format "hh:mm", denoting the maximum time Polycarp can sleep continuously. *hh* denotes the number of hours, and *mm* denotes the number of minutes. The number of minutes should be between 0 and 59. Look through examples to understand the format better.
Demo Input:
['1\n05:43\n', '4\n22:00\n03:21\n16:03\n09:59\n']
Demo Output:
['23:59\n', '06:37\n']
Note:
In the first example there is only one alarm which rings during one minute of a day, and then rings again on the next day, 23 hours and 59 minutes later. Polycarp can sleep all this time. | ```python
n = int(input());
a = [];
for i in range(n):
b = input().split(':');
a.append(int(b[0]) * 60 + int(b[1]));
a.sort();
t = a[0];
for i in range(n):
a[i] -= t;
a.append(1440);
u = -1;
for i in range(n):
u = max(u, a[i+1] - a[i] - 1);
h = u // 60;
m = u - h * 60;
if (h < 10): print('0', end='');
print(h, end=':');
if (m < 10): print('0', end='');
print(m, end='');
``` |
856 | Set Theory | Title: Set Theory
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Masha and Grisha like studying sets of positive integers.
One day Grisha has written a set *A* containing *n* different integers *a**i* on a blackboard. Now he asks Masha to create a set *B* containing *n* different integers *b**j* such that all *n*2 integers that can be obtained by summing up *a**i* and *b**j* for all possible pairs of *i* and *j* are different.
Both Masha and Grisha don't like big numbers, so all numbers in *A* are from 1 to 106, and all numbers in *B* must also be in the same range.
Help Masha to create the set *B* that satisfies Grisha's requirement.
Input Specification:
Input data contains multiple test cases. The first line contains an integer *t*Β β the number of test cases (1<=β€<=*t*<=β€<=100).
Each test case is described in the following way: the first line of the description contains one integer *n*Β β the number of elements in *A* (1<=β€<=*n*<=β€<=100).
The second line contains *n* integers *a**i*Β β the elements of *A* (1<=β€<=*a**i*<=β€<=106).
Output Specification:
For each test first print the answer:
- NO, if Masha's task is impossible to solve, there is no way to create the required set *B*. - YES, if there is the way to create the required set. In this case the second line must contain *n* different positive integers *b**j*Β β elements of *B* (1<=β€<=*b**j*<=β€<=106). If there are several possible sets, output any of them.
Demo Input:
['3\n3\n1 10 100\n1\n1\n2\n2 4\n']
Demo Output:
['YES\n1 2 3 \nYES\n1 \nYES\n1 2 \n']
Note:
none | ```python
d = [-1] * 1000001
for t in range(int(input())):
n, a = int(input()), list(map(int, input().split()))
a.sort()
for i in range(n):
for j in range(i + 1, n): d[a[j] - a[i]] = t
i = 1
while any(d[i * j] == t for j in range(1, n)): i += 1
print("YES\n" + ' '.join(str(j * i + 1) for j in range(n)))
``` |
630 | Forecast | Title: Forecast
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
The Department of economic development of IT City created a model of city development till year 2100.
To prepare report about growth perspectives it is required to get growth estimates from the model.
To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots.
The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one.
Input Specification:
The only line of the input contains three integers *a*,<=*b*,<=*c* (<=-<=1000<=β€<=*a*,<=*b*,<=*c*<=β€<=1000) β the coefficients of *ax*2<=+<=*bx*<=+<=*c*<==<=0 equation.
Output Specification:
In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10<=-<=6.
Demo Input:
['1 30 200\n']
Demo Output:
['-10.000000000000000\n-20.000000000000000']
Note:
none | ```python
a,b,c = map(int,input().split())
if a < 0:
a,b,c = -a,-b,-c
print((-b+(b*b-4*a*c)**0.5)/(2*a),(-b-(b*b-4*a*c)**0.5)/(2*a))
``` |
911 | Stack Sorting | Title: Stack Sorting
Time Limit: None seconds
Memory Limit: None megabytes
Problem Description:
Let's suppose you have an array *a*, a stack *s* (initially empty) and an array *b* (also initially empty).
You may perform the following operations until both *a* and *s* are empty:
- Take the first element of *a*, push it into *s* and remove it from *a* (if *a* is not empty); - Take the top element from *s*, append it to the end of array *b* and remove it from *s* (if *s* is not empty).
You can perform these operations in arbitrary order.
If there exists a way to perform the operations such that array *b* is sorted in non-descending order in the end, then array *a* is called stack-sortable.
For example, [3,<=1,<=2] is stack-sortable, because *b* will be sorted if we perform the following operations:
1. Remove 3 from *a* and push it into *s*; 1. Remove 1 from *a* and push it into *s*; 1. Remove 1 from *s* and append it to the end of *b*; 1. Remove 2 from *a* and push it into *s*; 1. Remove 2 from *s* and append it to the end of *b*; 1. Remove 3 from *s* and append it to the end of *b*.
After all these operations *b*<==<=[1,<=2,<=3], so [3,<=1,<=2] is stack-sortable. [2,<=3,<=1] is not stack-sortable.
You are given *k* first elements of some permutation *p* of size *n* (recall that a permutation of size *n* is an array of size *n* where each integer from 1 to *n* occurs exactly once). You have to restore the remaining *n*<=-<=*k* elements of this permutation so it is stack-sortable. If there are multiple answers, choose the answer such that *p* is lexicographically maximal (an array *q* is lexicographically greater than an array *p* iff there exists some integer *k* such that for every *i*<=<<=*k* *q**i*<==<=*p**i*, and *q**k*<=><=*p**k*). You may not swap or change any of first *k* elements of the permutation.
Print the lexicographically maximal permutation *p* you can obtain.
If there exists no answer then output -1.
Input Specification:
The first line contains two integers *n* and *k* (2<=β€<=*n*<=β€<=200000, 1<=β€<=*k*<=<<=*n*) β the size of a desired permutation, and the number of elements you are given, respectively.
The second line contains *k* integers *p*1, *p*2, ..., *p**k* (1<=β€<=*p**i*<=β€<=*n*) β the first *k* elements of *p*. These integers are pairwise distinct.
Output Specification:
If it is possible to restore a stack-sortable permutation *p* of size *n* such that the first *k* elements of *p* are equal to elements given in the input, print lexicographically maximal such permutation.
Otherwise print -1.
Demo Input:
['5 3\n3 2 1\n', '5 3\n2 3 1\n', '5 1\n3\n', '5 2\n3 4\n']
Demo Output:
['3 2 1 5 4 ', '-1\n', '3 2 1 5 4 ', '-1\n']
Note:
none | ```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**15
mod = 10**9+7
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
n,k = LI()
a = LI()
r = a[:]
s = []
m = 1
for c in a:
if c == m:
m += 1
t = len(s)
for i in range(t-1,-1,-1):
if s[i] == m:
m += 1
t = i
else:
break
if t != len(s):
s = s[:t]
else:
s.append(c)
for i in range(len(s)-1):
if s[i] < s[i+1]:
return -1
for i in range(len(s)-1,-1,-1):
c = s[i]
r += list(range(c-1,m-1,-1))
m = c+1
r += list(range(n,m-1,-1))
return ' '.join(map(str,r))
print(main())
``` |