source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two arrays of integers *a* and *b*. For each element of the second array *b**j* you should find the number of elements in array *a* that are less than or equal to the value *b**j*.
|
```python
lengths = list(map(int, input().split()))
a = list(map(int, input().split()))
b = list(map(int, input().split()))
res = []
a.sort()
for i in range(len(b)):
low = 0
high = lengths[0]
chosen = 0
control = 0
while low < high:
mid = int((low + high) // 2)
if a[mid] <= b[i]:
chosen = mid + 1
low = mid
else:
high = mid
if control == mid: break
control = mid
res.append(chosen)
print(*res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Furik loves math lessons very much, so he doesn't attend them, unlike Rubik. But now Furik wants to get a good mark for math. For that Ms. Ivanova, his math teacher, gave him a new task. Furik solved the task immediately. Can you?
You are given a system of equations:
You should count, how many there are pairs of integers (*a*,<=*b*) (0<=≤<=*a*,<=*b*) which satisfy the system.
|
```python
import math
n, m = [int(x) for x in input().split()]
count = 0
a_limit = min(math.floor(math.sqrt(n)), m)
b_limit = min(math.floor(math.sqrt(m)), n)
for a in range(0, a_limit + 1):
for b in range(0, b_limit + 1):
if (a**2 + b) == n and (a + b**2) == m:
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal".
Note that the first and last seats are not adjacent (if $n \ne 2$).
|
```python
def is_maximal(seating):
# Count the number of zeros and ones in the seating
zeros = seating.count("0")
ones = seating.count("1")
# Check if the seating is maximal
if (zeros == 1 and ones == 0) or (ones == 1 and zeros == 0):
return "Yes"
else:
return "No"
# Test the function with some examples
print(is_maximal("001")) # Should print "Yes"
print(is_maximal("101")) # Should print "No"
print(is_maximal("110")) # Should print "Yes"
print(is_maximal("010")) # Should print "No"
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
— Willem...
— What's the matter?
— It seems that there's something wrong with Seniorious...
— I'll have a look...
Seniorious is made by linking special talismans in particular order.
After over 500 years, the carillon is now in bad condition, so Willem decides to examine it thoroughly.
Seniorious has *n* pieces of talisman. Willem puts them in a line, the *i*-th of which is an integer *a**i*.
In order to maintain it, Willem needs to perform *m* operations.
There are four types of operations:
- 1 *l* *r* *x*: For each *i* such that *l*<=≤<=*i*<=≤<=*r*, assign *a**i*<=+<=*x* to *a**i*.- 2 *l* *r* *x*: For each *i* such that *l*<=≤<=*i*<=≤<=*r*, assign *x* to *a**i*.- 3 *l* *r* *x*: Print the *x*-th smallest number in the index range [*l*,<=*r*], i.e. the element at the *x*-th position if all the elements *a**i* such that *l*<=≤<=*i*<=≤<=*r* are taken and sorted into an array of non-decreasing integers. It's guaranteed that 1<=≤<=*x*<=≤<=*r*<=-<=*l*<=+<=1.- 4 *l* *r* *x* *y*: Print the sum of the *x*-th power of *a**i* such that *l*<=≤<=*i*<=≤<=*r*, modulo *y*, i.e. .
|
```python
#warning By KonJAC_xrs
#warning ( testing == 0 ) ? Yes : No
#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ld long double
using namespace std;
inline ll read()
{
ll x=0,f=1; char ch=getchar();
while (!isdigit(ch)) {if(ch=='-') f=-1; ch=getchar();}
while ( isdigit(ch)) {x = x * 10+ch-48; ch=getchar();}
return x*f;
}
inline void xrs(ll x)
{
if(x<0) putchar('-') , x=-x;
if(x>9) xrs(x/10);
putchar(x%10+'0');
}
//const ll inf=;
const ll mod=1e9+7;
const ll nore=2e5+20;
ll n,m,sed,vmax;
struct Chtholly_Tree{
struct node{
ll l,r;
mutable ll val;
node (ll x,ll y,ll z) : l(x),r(y),val(z) {}
node (ll x) : l(x) {}
bool operator < (const node &b) const {return l<b.l;}
};
set < node > s;
#define ss set < node > :: iterator
inline ss spilt(ll pos)
{
#define louwo_bengda lower_bound
ss it=s.louwo_bengda(node(pos));
if(it!=s.end() and it->l==pos)
return it;
it--;
ll l=it->l , r=it->r , val=it->val;
s.erase(it);
s.insert(node(l,pos-1,val));
return s.insert(node(pos,r,val)).first;
}
inline void assign(ll l,ll r,ll val)
{
ss it_r=spilt(r+1); ss it_l=spilt(l);
s.erase(it_l,it_r);
s.insert(node(l,r,val));
}
inline void add(ll l,ll r,ll val)
{
ss it_r=spilt(r+1); ss it_l=spilt(l);
for(register ss it=it_l;it!=it_r;it++)
it->val+=val;
}
inline ll kth(ll l,ll r,ll k)
{
ss it_r=spilt(r+1); ss it_l=spilt(l);
vector < pair < ll , ll > > v;
for(register ss it=it_l;it!=it_r;it++)
v.push_back(make_pair(it->val,it->r-it->l+1));
sort(v.begin(),v.end());
for(register ll i=0;i<v.size();i++)
{
k-=v[i].second;
if(k<=0)
return v[i].first;
}
return -1;
}
inline ll ksm(ll a,ll b,ll modd)
{
ll ans=1; a%=modd;
while(b)
{
if(b&1) ans=ans*a%modd;
a=a*a%modd;
b>>=1;
}
return ans;
}
inline ll ask(ll l,ll r,ll x,ll y)
{
ss it_r=spilt(r+1); ss it_l=spilt(l);
ll ans=0;
for(register ss it=it_l;it!=it_r;it++)
ans=(ans+((it->r-it->l+1)*ksm(it->val,x,y)))%y;
return ans;
}
}ODT;
inline ll randd()
{
ll ret=sed;
sed=(sed*7+13)%mod;
return ret;
}
int main()
{
// freopen(".in","r",stdin);
// freopen(".out","w",stdout);
n=read(); m=read(); sed=read(); vmax=read();
for(register ll i=1;i<=n;i++)
{
ll a=randd()%vmax+1;
ODT.s.insert(Chtholly_Tree::node(i,i,a));
}
// ODT.s.insert(Chtholly_Tree::node(n+1,n+1,0));
for(register ll i=1;i<=m;i++)
{
short int opt=randd()%4+1;
ll l=randd()%n+1; ll r=randd()%n+1;
ll x,y;
if(l>r) swap(l,r);
if(opt==3)
x=randd()%(r-l+1)+1;
else
x=randd()%vmax+1;
if(opt==4)
y=randd()%vmax+1;
if(opt==1)
ODT.add(l,r,x);
else if(opt==2)
ODT.assign(l,r,x);
else if(opt==3)
xrs(ODT.kth(l,r,x)) , puts("");
else
xrs(ODT.ask(l,r,x,y)) , puts("");
}
getchar();
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
В самолёте есть *n* рядов мест. Если смотреть на ряды сверху, то в каждом ряду есть 3 места слева, затем проход между рядами, затем 4 центральных места, затем ещё один проход между рядами, а затем ещё 3 места справа.
Известно, что некоторые места уже заняты пассажирами. Всего есть два вида пассажиров — статусные (те, которые часто летают) и обычные.
Перед вами стоит задача рассадить ещё *k* обычных пассажиров так, чтобы суммарное число соседей у статусных пассажиров было минимально возможным. Два пассажира считаются соседями, если они сидят в одном ряду и между ними нет других мест и прохода между рядами. Если пассажир является соседним пассажиром для двух статусных пассажиров, то его следует учитывать в сумме соседей дважды.
|
```python
from collections import Counter
n,k=list(map(int,input().split()))
#n,k=1,2
a=set()
c=[set() for i in range(3)]
b=set()
z=0
for i in range(n):
s=input()
for i0 in range(len(s)):
if s[i0]=='.':
a.add(tuple([i,i0]))
elif s[i0]=='S':
b.add(tuple([i,i0]))
for i0 in range(len(s)):
if s[i0]=='.':
zz=0
if tuple([i,i0+1]) in b:
zz=zz+1
if tuple([i,i0-1]) in b:
zz=zz+1
c[zz].add(tuple([i,i0]))
c=list(c[0])+list(c[1])+list(c[2])
for i in range(k):
a.remove(c[i])
for i in b:
if (i[1]!=2)and(i[1]!=7)and(i[1]!=11):
if not(tuple([i[0],i[1]+1])in a):
z=z+1
if (i[1]!=4)and(i[1]!=9)and(i[1]!=0):
if not(tuple([i[0],i[1]-1])in a):
z=z+1
c=set(c)
print(z)
for i in range(n):
s=''
for i0 in range(12):
if i0==3 or i0==8:
s=s+'-'
elif tuple([i,i0])in a:
s=s+'.'
elif tuple([i,i0])in b:
s=s+'S'
elif tuple([i,i0])in c:
s=s+'x'
else:
s=s+'P'
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jon fought bravely to rescue the wildlings who were attacked by the white-walkers at Hardhome. On his arrival, Sam tells him that he wants to go to Oldtown to train at the Citadel to become a maester, so he can return and take the deceased Aemon's place as maester of Castle Black. Jon agrees to Sam's proposal and Sam sets off his journey to the Citadel. However becoming a trainee at the Citadel is not a cakewalk and hence the maesters at the Citadel gave Sam a problem to test his eligibility.
Initially Sam has a list with a single element *n*. Then he has to perform certain operations on this list. In each operation Sam must remove any element *x*, such that *x*<=><=1, from the list and insert at the same position , , sequentially. He must continue with these operations until all the elements in the list are either 0 or 1.
Now the masters want the total number of 1s in the range *l* to *r* (1-indexed). Sam wants to become a maester but unfortunately he cannot solve this problem. Can you help Sam to pass the eligibility test?
|
```python
n, l, r = map(int, input().split())
arr = [n]
def helper(n):
if n <=1:
return
elif n>1:
substitute = [n//2, n%2,n//2]
i = arr.index(n)
arr[i:i+1] = substitute
helper(n//2)
helper(n%2)
helper(n//2)
helper(n)
print(sum(arr[l-1:r]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
n=int(input())
l=list(map(int,input().split()))
even,odd,evenind,oddind=0,0,0,0
for i in range(n):
if (l[i]%2==0):
even += 1
evenind = i
else:
even -= 1
oddind = i
if(even > 0):
print(oddind+1)
else:
print(evenind+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has become interested in wrestling. In wrestling wrestlers use techniques for which they are awarded points by judges. The wrestler who gets the most points wins.
When the numbers of points of both wrestlers are equal, the wrestler whose sequence of points is lexicographically greater, wins.
If the sequences of the awarded points coincide, the wrestler who performed the last technique wins. Your task is to determine which wrestler won.
|
```python
import math
from decimal import *
import random
mod = int(1e9)+7
f, s = 0,0
x, y= [],[]
last = -1
for _ in range(int(input())):
n = int(input())
if(n>0):
x.append(n)
f+=n
last = 1
else:
y.append(abs(n))
s+=abs(n)
last = 0
if(f>s):
print('first')
if(s>f):
print('second')
if(s==f):
if(len(x)>len(y)):
fnd = True
for i in range(len(y)):
if(x[i]!=y[i]):
fnd = False
break
if(fnd):
print('first')
else:
fwin = True
pnt=0
while(pnt<len(y)):
if(x[pnt]>y[pnt]):
fwin = True
break
elif(x[pnt]==y[pnt]):
pnt+=1
else:
fwin =False
if(fwin and pnt!= len(y)):
print('first')
elif(not fwin and pnt!= len(y)):
print('second')
else:
if(last):
print('first')
else:
print('second')
elif(len(y)>len(x)):
fnd = True
for i in range(len(x)):
if(x[i]!=y[i]):
fnd = False
break
if(fnd):
print('second')
else:
fwin = True
pnt=0
while(pnt<len(y)):
if(x[pnt]>y[pnt]):
fwin = True
break
elif(x[pnt]==y[pnt]):
pnt+=1
else:
fwin =False
if(fwin and pnt!= len(y)):
print('first')
elif(not fwin and pnt!= len(y)):
print('second')
else:
if(last):
print('first')
else:
print('second')
else:
fwin = True
pnt=0
while(pnt<len(y)):
if(x[pnt]>y[pnt]):
fwin = True
break
elif(x[pnt]==y[pnt]):
pnt+=1
else:
fwin =False
if(fwin and pnt!= len(y)):
print('first')
elif(not fwin and pnt!= len(y)):
print('second')
else:
if(last):
print('first')
else:
print('second')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pasha loves his phone and also putting his hair up... But the hair is now irrelevant.
Pasha has installed a new game to his phone. The goal of the game is following. There is a rectangular field consisting of *n* row with *m* pixels in each row. Initially, all the pixels are colored white. In one move, Pasha can choose any pixel and color it black. In particular, he can choose the pixel that is already black, then after the boy's move the pixel does not change, that is, it remains black. Pasha loses the game when a 2<=×<=2 square consisting of black pixels is formed.
Pasha has made a plan of *k* moves, according to which he will paint pixels. Each turn in his plan is represented as a pair of numbers *i* and *j*, denoting respectively the row and the column of the pixel to be colored on the current move.
Determine whether Pasha loses if he acts in accordance with his plan, and if he does, on what move the 2<=×<=2 square consisting of black pixels is formed.
|
```python
n,m,k=map(int,input().split());l=[];ans=0
for i in range(n+2):
t=[]
for j in range(m+2):
t.append(0)
l.append(t)
for i in range(k):
p,q=map(int,input().split())
l[p][q]=1
if l[p-1][q-1]+l[p][q-1]+l[p-1][q]==3:
ans=i+1;break
if l[p-1][q]+l[p-1][q+1]+l[p][q]==3:
ans=i+1;break
if l[p][q-1]+l[p+1][q-1]+l[p+1][q]==3:
ans=i+1;break
if l[p][q+1]+l[p+1][q]+l[p+1][q+1]==3:
ans=i+1;break
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Chris is bored during his physics lessons (too easy), so he has built a toy box to keep himself occupied. The box is special, since it has the ability to change gravity.
There are *n* columns of toy cubes in the box arranged in a line. The *i*-th column contains *a**i* cubes. At first, the gravity in the box is pulling the cubes downwards. When Chris switches the gravity, it begins to pull all the cubes to the right side of the box. The figure shows the initial and final configurations of the cubes in the box: the cubes that have changed their position are highlighted with orange.
Given the initial configuration of the toy cubes in the box, find the amounts of cubes in each of the *n* columns after the gravity switch!
|
```python
n = input()
li= list(map(int,input().split()))
li.sort()
for i in li:
print(i,end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Elephant loves magic squares very much.
A magic square is a 3<=×<=3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15.
The Little Elephant remembered one magic square. He started writing this square on a piece of paper, but as he wrote, he forgot all three elements of the main diagonal of the magic square. Fortunately, the Little Elephant clearly remembered that all elements of the magic square did not exceed 105.
Help the Little Elephant, restore the original magic square, given the Elephant's notes.
|
```python
a =[]
for i in range(3):
a.append(list(map(int,input().split())))
for n in range(1,10**5):
s = n+ a[0][1] + a[0][2]
k = s - a[1][0] - a[1][2]
w = s - a[2][0] - a[2][1]
if n+k+w==s:
a[0][0] = n
a[1][1] = k
a[2][2] = w
break
for i in range(3):
print(*a[i])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera runs a 24/7 fast food cafe. He magically learned that next day *n* people will visit his cafe. For each person we know the arrival time: the *i*-th person comes exactly at *h**i* hours *m**i* minutes. The cafe spends less than a minute to serve each client, but if a client comes in and sees that there is no free cash, than he doesn't want to wait and leaves the cafe immediately.
Valera is very greedy, so he wants to serve all *n* customers next day (and get more profit). However, for that he needs to ensure that at each moment of time the number of working cashes is no less than the number of clients in the cafe.
Help Valera count the minimum number of cashes to work at his cafe next day, so that they can serve all visitors.
|
```python
t=int(input())
cash=1
i=0
M=[]
for j in range(t):
L=list(map(int,input().split(" ")))
M.append(L)
if j!=0:
if M[j]==M[j-1]:
i+=1
else:
i=0
if i>=cash:
cash+=1
print(cash)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"Hey, it's homework time" — thought Polycarpus and of course he started with his favourite subject, IT. Polycarpus managed to solve all tasks but for the last one in 20 minutes. However, as he failed to solve the last task after some considerable time, the boy asked you to help him.
The sequence of *n* integers is called a permutation if it contains all integers from 1 to *n* exactly once.
You are given an arbitrary sequence *a*1,<=*a*2,<=...,<=*a**n* containing *n* integers. Each integer is not less than 1 and not greater than 5000. Determine what minimum number of elements Polycarpus needs to change to get a permutation (he should not delete or add numbers). In a single change he can modify any single sequence element (i. e. replace it with another integer).
|
```python
n = int(input())
ok = [False]*n
inp = input().split(' ')
count = n
for i in inp:
i = int(i)-1
if not ok[i]:
count -= 1
ok[i] = True
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
$k$ people want to split $n$ candies between them. Each candy should be given to exactly one of them or be thrown away.
The people are numbered from $1$ to $k$, and Arkady is the first of them. To split the candies, Arkady will choose an integer $x$ and then give the first $x$ candies to himself, the next $x$ candies to the second person, the next $x$ candies to the third person and so on in a cycle. The leftover (the remainder that is not divisible by $x$) will be thrown away.
Arkady can't choose $x$ greater than $M$ as it is considered greedy. Also, he can't choose such a small $x$ that some person will receive candies more than $D$ times, as it is considered a slow splitting.
Please find what is the maximum number of candies Arkady can receive by choosing some valid $x$.
|
```python
n, k, M, D = map(int, input().split())
ans = 0
for i in range(1, D+1):
x = n //((i-1)*k+1)
if x <= M:
ans = max(ans, x*i)
if n//k <= M:
ans = max(ans, n//k)
else:
ans = max(ans, M)
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Luba thinks about watering her garden. The garden can be represented as a segment of length *k*. Luba has got *n* buckets, the *i*-th bucket allows her to water some continuous subsegment of garden of length exactly *a**i* each hour. Luba can't water any parts of the garden that were already watered, also she can't water the ground outside the garden.
Luba has to choose one of the buckets in order to water the garden as fast as possible (as mentioned above, each hour she will water some continuous subsegment of length *a**i* if she chooses the *i*-th bucket). Help her to determine the minimum number of hours she has to spend watering the garden. It is guaranteed that Luba can always choose a bucket so it is possible water the garden.
See the examples for better understanding.
|
```python
import re
x = input()
res = 0
list_1 = re.split('\s', x,0)
m = int(list_1[0])
y = int(list_1[1])
res = 0
str = input()
list_2 = re.split('\s',str,0)
for i in list_2:
if y % int(i) == 0:
res = int(i)
print(int(y / res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a sequence *a* consisting of *n* integers. You may partition this sequence into two sequences *b* and *c* in such a way that every element belongs exactly to one of these sequences.
Let *B* be the sum of elements belonging to *b*, and *C* be the sum of elements belonging to *c* (if some of these sequences is empty, then its sum is 0). What is the maximum possible value of *B*<=-<=*C*?
|
```python
input()
a = sorted(list(map(int, input().split())))
print(a[-1] - a[0] if a[0] < 1 else sum(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Having watched the last Harry Potter film, little Gerald also decided to practice magic. He found in his father's magical book a spell that turns any number in the sum of its digits. At the moment Gerald learned that, he came across a number *n*. How many times can Gerald put a spell on it until the number becomes one-digit?
|
```python
n = input()
c = 0
while int(n) > 9:
temp = 0
c += 1
for i in n :
temp += int(i)
n = str(temp)
# print(temp)
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After their adventure with the magic mirror Kay and Gerda have returned home and sometimes give free ice cream to kids in the summer.
At the start of the day they have *x* ice cream packs. Since the ice cream is free, people start standing in the queue before Kay and Gerda's house even in the night. Each person in the queue wants either to take several ice cream packs for himself and his friends or to give several ice cream packs to Kay and Gerda (carriers that bring ice cream have to stand in the same queue).
If a carrier with *d* ice cream packs comes to the house, then Kay and Gerda take all his packs. If a child who wants to take *d* ice cream packs comes to the house, then Kay and Gerda will give him *d* packs if they have enough ice cream, otherwise the child will get no ice cream at all and will leave in distress.
Kay wants to find the amount of ice cream they will have after all people will leave from the queue, and Gerda wants to find the number of distressed kids.
|
```python
n, x = list(map(int, input().split(' ')))
d = 0
for i in range(n):
a, b = input().split(' ')
b = int(b)
if a == '+':
x += b
elif a == '-' and b <= x:
x -= b
else:
d += 1
print(x, d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Artem got *n* stones on his birthday and now wants to give some of them to Masha. He knows that Masha cares more about the fact of receiving the present, rather than the value of that present, so he wants to give her stones as many times as possible. However, Masha remembers the last present she received, so Artem can't give her the same number of stones twice in a row. For example, he can give her 3 stones, then 1 stone, then again 3 stones, but he can't give her 3 stones and then again 3 stones right after that.
How many times can Artem give presents to Masha?
|
```python
n = int(input())
a = [1, 1]
for i in range(2, n):
a.append(a[i - 1] + a[i - 2])
print(a[n - 1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room and decided to say hello to everybody. Vasya typed the word *s*. It is considered that Vasya managed to say hello if several letters can be deleted from the typed word so that it resulted in the word "hello". For example, if Vasya types the word "ahhellllloou", it will be considered that he said hello, and if he types "hlelo", it will be considered that Vasya got misunderstood and he didn't manage to say hello. Determine whether Vasya managed to say hello by the given word *s*.
|
```python
s = input()
a = []
for i in range(len(s)):
if s[i] == 'h' and 1 not in a:
a.append(1)
elif s[i] == 'e' and a[-1] == 1:
a.append(2)
elif s[i] == 'l' and a[-1] == 2:
a.append(3)
elif s[i] == 'l' and a[-1] == 3:
a.append(4)
elif s[i] == 'o' and a[-1] == 4:
a.append(5)
if a[-1] == 5:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We consider a positive integer perfect, if and only if the sum of its digits is exactly $10$. Given a positive integer $k$, your task is to find the $k$-th smallest perfect positive integer.
|
```python
n = int(input())
i = 10
while n>0:
i += 9
if sum(map(int, str(i))) == 10: n-=1
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Nick is interested in prime numbers. Once he read about Goldbach problem. It states that every even integer greater than 2 can be expressed as the sum of two primes. That got Nick's attention and he decided to invent a problem of his own and call it Noldbach problem. Since Nick is interested only in prime numbers, Noldbach problem states that at least *k* prime numbers from 2 to *n* inclusively can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1. For example, 19 = 7 + 11 + 1, or 13 = 5 + 7 + 1.
Two prime numbers are called neighboring if there are no other prime numbers between them.
You are to help Nick, and find out if he is right or wrong.
|
```python
def f(rangeint):
List = []
for j in range(2, rangeint+1):
List.append(j)
z = 2*len(List)
a = 0
for i in range(0, int(rangeint**(1/2))):
a += 1
m = List[a-1]
for k in List:
if k % m == 0 and k > m :
List.remove(k)
return List
innput = input()
inputspl = innput.split()
n = int(inputspl[0])
k = int(inputspl[1])
counter = 0
Listprime = f(n)
for d in range(0, len(Listprime)-1):
if ((Listprime[d]+Listprime[d+1]+1) in Listprime) and ((Listprime[d]+Listprime[d+1]+1) <= n):
counter += 1
if counter >= k:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
s=input()
t=input()
l=len(s)
f=0
for i in range(l):
if s[i]!=t[l-i-1]:
f=1
break
if f==1:
print("NO")
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is to reach *n*-th pylon, and the only move the player can do is to jump from the current pylon (let's denote its number as *k*) to the next one (its number will be *k*<=+<=1). When the player have made such a move, its energy increases by *h**k*<=-<=*h**k*<=+<=1 (if this value is negative the player loses energy). The player must have non-negative amount of energy at any moment of the time.
Initially Caisa stand at 0 pylon and has 0 energy. The game provides a special opportunity: one can pay a single dollar and increase the height of anyone pylon by one. Caisa may use that opportunity several times, but he doesn't want to spend too much money. What is the minimal amount of money he must paid to reach the goal of the game?
|
```python
_ = input()
l = list(map(int, input().split()))
print(max(l))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
The combination lock is represented by *n* rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has to turn some disks so that the combination of digits on the disks forms a secret combination. In one move, he can rotate one disk one digit forwards or backwards. In particular, in one move he can go from digit 0 to digit 9 and vice versa. What minimum number of actions does he need for that?
|
```python
N = int(input())
org = input()
fin = input()
sol = 0
for i in range(N):
a, b = int(min(org[i],fin[i])), int(max(org[i],fin[i]))
sol += min(abs(b-a), a+10-b)
print(sol)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Catherine has a deck of *n* cards, each of which is either red, green, or blue. As long as there are at least two cards left, she can do one of two actions:
- take any two (not necessarily adjacent) cards with different colors and exchange them for a new card of the third color; - take any two (not necessarily adjacent) cards with the same color and exchange them for a new card with that color.
She repeats this process until there is only one card left. What are the possible colors for the final card?
|
```python
int(input())
b=set(input())
if len(b)==1:print(''.join(b))
elif len(b)==2:print(*[i for i in 'GRB' if i not in b])
else:print('B')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consists of several words. For each language, all words are distinct, i.e. they are spelled differently. Moreover, the words of these languages have a one-to-one correspondence, that is, for each word in each language, there exists exactly one word in the other language having has the same meaning.
You can write down every word the professor says in either the first language or the second language. Of course, during the lecture you write down each word in the language in which the word is shorter. In case of equal lengths of the corresponding words you prefer the word of the first language.
You are given the text of the lecture the professor is going to read. Find out how the lecture will be recorded in your notes.
|
```python
n,m = map(int,input().split())
a = []
b = []
ans = []
for i in range(0,m):
w1,w2 = [str(x) for x in input().split()]
a.append(w1)
b.append(w2)
s = input()
s = s.split()
for word in s:
cnt = a.index(word)
if len(a[cnt]) <= len(b[cnt]):
ans.append(a[cnt])
else:
ans.append(b[cnt])
print(" ".join(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map.
The treasure map can be represented as a rectangle *n*<=×<=*m* in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks.
Besides, the map also has a set of *k* instructions. Each instruction is in the following form:
"Walk *n* miles in the *y* direction"
The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried.
Unfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares.
The captain wants to know which sights are worth checking. He asks you to help him with that.
|
```python
print("_RANDOM_GUESS_1689180180.4521961")# 1689180180.4522119
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height of the *i*-th person is equal to *a**i*.
Consider the width of the person walking as usual to be equal to 1, while the width of the bent person is equal to 2. Friends want to talk to each other while walking, so they would like to walk in a single row. What is the minimum width of the road, such that friends can walk in a row and remain unattended by the guard?
|
```python
n = input().split()
a = input().split()
MP=0
for i in range(0,int(n[0])):
if int(a[i]) > int(n[1]) :
MP+=2
else:
MP+=1
print(MP)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
On his trip to Luxor and Aswan, Sagheer went to a Nubian market to buy some souvenirs for his friends and relatives. The market has some strange rules. It contains *n* different items numbered from 1 to *n*. The *i*-th item has base cost *a**i* Egyptian pounds. If Sagheer buys *k* items with indices *x*1,<=*x*2,<=...,<=*x**k*, then the cost of item *x**j* is *a**x**j*<=+<=*x**j*·*k* for 1<=≤<=*j*<=≤<=*k*. In other words, the cost of an item is equal to its base cost in addition to its index multiplied by the factor *k*.
Sagheer wants to buy as many souvenirs as possible without paying more than *S* Egyptian pounds. Note that he cannot buy a souvenir more than once. If there are many ways to maximize the number of souvenirs, he will choose the way that will minimize the total cost. Can you help him with this task?
|
```python
n, s = map(int, input().split())
v = list(map(int, input().split()))
#for i in range(n):
r = n + 1
l = 0
o = 0
while r - l != 1:
s1 = s
b = []
t = True
for i in range(n):
b.append(v[i] + (i + 1) * ((r + l) // 2))
b.sort()
i = 0
sum = 0
for i in range((r + l) // 2):
sum += b[i]
if sum <= s:
l = (r + l) // 2
o = sum
else:
r = (r + l) // 2
s = s1
print(l, o)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It was recycling day in Kekoland. To celebrate it Adil and Bera went to Central Perk where they can take bottles from the ground and put them into a recycling bin.
We can think Central Perk as coordinate plane. There are *n* bottles on the ground, the *i*-th bottle is located at position (*x**i*,<=*y**i*). Both Adil and Bera can carry only one bottle at once each.
For both Adil and Bera the process looks as follows:
1. Choose to stop or to continue to collect bottles. 1. If the choice was to continue then choose some bottle and walk towards it. 1. Pick this bottle and walk to the recycling bin. 1. Go to step 1.
Adil and Bera may move independently. They are allowed to pick bottles simultaneously, all bottles may be picked by any of the two, it's allowed that one of them stays still while the other one continues to pick bottles.
They want to organize the process such that the total distance they walk (the sum of distance walked by Adil and distance walked by Bera) is minimum possible. Of course, at the end all bottles should lie in the recycling bin.
|
```python
import math
Ax , Ay , Bx , By , Rx , Ry = map(int,input().split())
a , b = [100009] , [100009]
maxDis ,mDx,mDy ,res ,mx , my ,minDis,x1,y1= 0,0,0,0,0,0,10000000000,0,0
n = int(input())
for i in range(n):
x , y = map(int,input().split())
a.append(x)
b.append(y)
d = math.dist([x,y] , [Rx,Ry])
if d > maxDis:
maxDis = d
mDx = x
mDy = y
res += 2 * d
d1 = math . dist([mDx , mDy] , [Ax , Ay])
d2 = math . dist([mDx , mDy] , [Bx , By])
if d1 < d2 :
mx = Bx
my = By
else:
mx = Ax
my = Ay
res +=min(d1,d2)
res -= math . dist([mDx , mDy] , [Rx , Ry])
for i in range(1,n+1):
x = a[i]
y = b[i]
d = math.dist([x,y] , [mx,my])
if d<minDis:
minDis=d
x1 = x
y1 = y
res += math.dist([x1,y1] , [mx,my])
res -= math.dist([x1,y1] , [Rx,Ry])
print("{0:.12f}".format(res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had *a* red socks and *b* blue socks.
According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot.
Every day Vasya puts on new socks in the morning and throws them away before going to bed as he doesn't want to wash them.
Vasya wonders, what is the maximum number of days when he can dress fashionable and wear different socks, and after that, for how many days he can then wear the same socks until he either runs out of socks or cannot make a single pair from the socks he's got.
Can you help him?
|
```python
a, b = map(int, input().split())
if a != b:
mn = min(a, b)
mx = max(a, b)
ans1 = mn
ans2 = (mx - ans1)//2
print(ans1, ans2)
else:
print(min(a,b), 0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya is very upset that many people on the Net mix uppercase and lowercase letters in one word. That's why he decided to invent an extension for his favorite browser that would change the letters' register in every word so that it either only consisted of lowercase letters or, vice versa, only of uppercase ones. At that as little as possible letters should be changed in the word. For example, the word HoUse must be replaced with house, and the word ViP — with VIP. If a word contains an equal number of uppercase and lowercase letters, you should replace all the letters with lowercase ones. For example, maTRIx should be replaced by matrix. Your task is to use the given method on one given word.
|
```python
l1 = 'QWERTYUIOPASDFGHJKLZXCVBNM'
s = input()
ABC = 0
abc = 0
for i in s:
if i in l1:
ABC += 1
else:
abc += 1
if ABC > abc:
print(s.upper())
else:
print(s.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Grigoriy, like the hero of one famous comedy film, found a job as a night security guard at the museum. At first night he received embosser and was to take stock of the whole exposition.
Embosser is a special devise that allows to "print" the text of a plastic tape. Text is printed sequentially, character by character. The device consists of a wheel with a lowercase English letters written in a circle, static pointer to the current letter and a button that print the chosen letter. At one move it's allowed to rotate the alphabetic wheel one step clockwise or counterclockwise. Initially, static pointer points to letter 'a'. Other letters are located as shown on the picture:
After Grigoriy add new item to the base he has to print its name on the plastic tape and attach it to the corresponding exhibit. It's not required to return the wheel to its initial position with pointer on the letter 'a'.
Our hero is afraid that some exhibits may become alive and start to attack him, so he wants to print the names as fast as possible. Help him, for the given string find the minimum number of rotations of the wheel required to print it.
|
```python
n=input()
rotations=0
starting_point="a"
for i in n:
r=(abs(ord(i)-ord(starting_point)))%26
if r>13:
rotations+=26-r
else:
rotations+=r
starting_point=i
print(rotations)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* soldiers stand in a circle. For each soldier his height *a**i* is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |*a**i*<=-<=*a**j*| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance unit.
|
```python
n = int(input())
a = list(map(int, input().split()))
x = 99999
for i in range(n):
if abs(a[i] - a[(i+1)%n]) < x:
x = abs(a[i%n] - a[(i+1)%n])
x1 = i%n
x2 = (i+1)%n
print(x1, x2, sep=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* wooden cupboards, standing in the kitchen. He immediately realized that these cupboards have hidden jam stocks. Karlsson began to fly greedily around the kitchen, opening and closing the cupboards' doors, grab and empty all the jars of jam that he could find.
And now all jars of jam are empty, Karlsson has had enough and does not want to leave traces of his stay, so as not to let down his friend. Each of the cupboards has two doors: the left one and the right one. Karlsson remembers that when he rushed to the kitchen, all the cupboards' left doors were in the same position (open or closed), similarly, all the cupboards' right doors were in the same position (open or closed). Karlsson wants the doors to meet this condition as well by the time the family returns. Karlsson does not remember the position of all the left doors, also, he cannot remember the position of all the right doors. Therefore, it does not matter to him in what position will be all left or right doors. It is important to leave all the left doors in the same position, and all the right doors in the same position. For example, all the left doors may be closed, and all the right ones may be open.
Karlsson needs one second to open or close a door of a cupboard. He understands that he has very little time before the family returns, so he wants to know the minimum number of seconds *t*, in which he is able to bring all the cupboard doors in the required position.
Your task is to write a program that will determine the required number of seconds *t*.
|
```python
n = int(input())
left_open = 0
right_open = 0
for i in range(n):
l, r = map(int, input().split())
left_open += l
right_open += r
case1 = min(left_open, n - left_open) + min(right_open, n - right_open)
case2 = min(left_open, n - left_open) + min(right_open, n - right_open) + abs(left_open - right_open)
print(min(case1, case2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The ship crashed into a reef and is sinking. Now the entire crew must be evacuated. All *n* crew members have already lined up in a row (for convenience let's label them all from left to right with positive integers from 1 to *n*) and await further instructions. However, one should evacuate the crew properly, in a strict order. Specifically:
The first crew members to leave the ship are rats. Then women and children (both groups have the same priority) leave the ship. After that all men are evacuated from the ship. The captain leaves the sinking ship last.
If we cannot determine exactly who should leave the ship first for any two members of the crew by the rules from the previous paragraph, then the one who stands to the left in the line leaves the ship first (or in other words, the one whose number in the line is less).
For each crew member we know his status as a crew member, and also his name. All crew members have different names. Determine the order in which to evacuate the crew.
|
```python
dict={}
d={'captain':4,'man':3,'child':2,'woman':2,'rat':1}
n=int(input())
for i in range(n):
ip=list(map(str,input().split(' ')))
name=ip[0]
dict[name]=d[ip[1]]
for i in sorted(dict.items(), key=lambda kv:(kv[1], kv[0])):
print(i[0])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer *x* and reduce it to the number of bits set to 1 in the binary representation of *x*. For example for number 13 it's true that 1310<==<=11012, so it has 3 bits set and 13 will be reduced to 3 in one operation.
He calls a number special if the minimum number of operations to reduce it to 1 is *k*.
He wants to find out how many special numbers exist which are not greater than *n*. Please help the Travelling Salesman, as he is about to reach his destination!
Since the answer can be large, output it modulo 109<=+<=7.
|
```python
MX = 1030
M = 1000 * 1000 * 1000 + 7
c = [[0] * MX for i in range(MX)]
for i in range(MX):
c[i][0] = 1
for i in range(1, MX):
for j in range(1, MX):
c[i][j] = c[i - 1][j] + c[i - 1][j - 1]
c[i][j] %= M
num = list(map(int, list(input())))
cnt = int(input())
dp = [0] * MX
for i in range(2, MX):
dp[i] = dp[bin(i).count('1')] + 1
if cnt == 0:
print(1)
exit()
res = 0
for i in range(1, MX):
if dp[i] != cnt - 1: continue
n = len(num) - 1
k = i
for pos in range(len(num)):
if num[pos] == 1:
# print(n, k)
#if we put 0 here
res += c[n][k]
res %= M
k -= 1
n -= 1
# print(k)
if n == -1 and k == 0:
res += 1
if cnt == 1: res -= 1
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You're given a list of *n* strings *a*1,<=*a*2,<=...,<=*a**n*. You'd like to concatenate them together in some order such that the resulting string would be lexicographically smallest.
Given the list of strings, output the lexicographically smallest concatenation.
|
```python
def function():
temp=input().split()
customers=int(temp[0])
cost=int(temp[1])
custArray=[]
for customer in range(customers):
temp=input()
custArray.append(temp)
apples=0
profit=0
for index in range(customers):
if(custArray[customers-1-index]=='half'):
if(apples==0):
apples=1
profit=cost
else:
profit+=cost*apples
apples=2*apples
else:
if(apples==0):
apples=1
profit=cost/2
else:
profit+=(apples+.5)*cost
apples=apples*2+1
return int(profit)
def concat():
size=int(input())
stringArray=[]
for temp in range(size):
stringArray.append(input())
superString=''
for index in range(len(stringArray)):
if superString=='':
superString=stringArray[index]
else:
if superString.find(stringArray[index])==-1:
flag=False
for innerIndex in range (len(stringArray[index])):
if(superString[-(len(stringArray[index])-1-innerIndex):]==stringArray[index][:len(stringArray[index])-1-innerIndex]):
superString+=stringArray[index][len(stringArray[index])-1-innerIndex:]
flag=True
break
if(not flag):
superString+=stringArray[index]
return superString
'''
def lcmString():
temp=input().split()
size=int(temp[0])
m=int(temp[1])
temp=input().split()
for index in range(len(temp)):
if
'''
print(concat())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where
Now DZY has a string *s*. He wants to insert *k* lowercase letters into this string in order to get the largest possible value of the resulting string. Can you help him calculate the largest possible value he could get?
|
```python
s=input()
k=int(input())
w=list(map(int,input().split()))
s=list(s)
q=0
for i in range(len(s)):
q=q+(i+1)*w[i]
a=max(w)
b=len(s)+1
for i in range(k):
q=q+b*a
b=b+1
print(q)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given *n* numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob — to check his answers, he needs a program that among the given *n* numbers finds one that is different in evenness.
|
```python
#25A IQ Test
import sys
import math
inputs = int(input())
input2 = sys.stdin.readline().split()
i = 0
a = 0
b = 0
if inputs == 2:
print("1")
sys.exit()
for i in range(inputs):
if int(input2[i])%2 == 0:
a = a + 1
else:
b = b + 1
if a>b: #Even
for i in range(inputs):
if int(input2[i])%2 == 1:
print(i + 1)
else: #Even
for i in range(inputs):
if int(input2[i])%2 == 0:
print(i + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Recently, Mike was very busy with studying for exams and contests. Now he is going to chill a bit by doing some sight seeing in the city.
City consists of *n* intersections numbered from 1 to *n*. Mike starts walking from his house located at the intersection number 1 and goes along some sequence of intersections. Walking from intersection number *i* to intersection *j* requires |*i*<=-<=*j*| units of energy. The total energy spent by Mike to visit a sequence of intersections *p*1<==<=1,<=*p*2,<=...,<=*p**k* is equal to units of energy.
Of course, walking would be boring if there were no shortcuts. A shortcut is a special path that allows Mike walking from one intersection to another requiring only 1 unit of energy. There are exactly *n* shortcuts in Mike's city, the *i**th* of them allows walking from intersection *i* to intersection *a**i* (*i*<=≤<=*a**i*<=≤<=*a**i*<=+<=1) (but not in the opposite direction), thus there is exactly one shortcut starting at each intersection. Formally, if Mike chooses a sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k* then for each 1<=≤<=*i*<=<<=*k* satisfying *p**i*<=+<=1<==<=*a**p**i* and *a**p**i*<=≠<=*p**i* Mike will spend only 1 unit of energy instead of |*p**i*<=-<=*p**i*<=+<=1| walking from the intersection *p**i* to intersection *p**i*<=+<=1. For example, if Mike chooses a sequence *p*1<==<=1,<=*p*2<==<=*a**p*1,<=*p*3<==<=*a**p*2,<=...,<=*p**k*<==<=*a**p**k*<=-<=1, he spends exactly *k*<=-<=1 units of total energy walking around them.
Before going on his adventure, Mike asks you to find the minimum amount of energy required to reach each of the intersections from his home. Formally, for each 1<=≤<=*i*<=≤<=*n* Mike is interested in finding minimum possible total energy of some sequence *p*1<==<=1,<=*p*2,<=...,<=*p**k*<==<=*i*.
|
```python
from collections import defaultdict
class Graph:
def __init__(self):
self.node=set()
self.edges= defaultdict(list)
self.distance={}
def addNode(self,value):
self.node.add(value)
def addEdge(self,start,end,distance):
self.edges[start].append(end)
self.distance[(start,end)]=distance
def dij(graph,ini):
visited={ini:0}
path= defaultdict(list)
nodes=set(graph.node)
while nodes:
minNode=None
for node in nodes:
if node in visited:
if(minNode is None):
minNode=node
elif(visited[node]<visited[minNode]):
minNode=node
if(minNode is None):
break
nodes.remove(minNode)
currentWeight=visited[minNode]
for edge in graph.edges[minNode]:
w=currentWeight + graph.distance[(minNode,edge)]
if edge not in visited or w < visited[edge]:
visited[edge]=w
path[edge].append(minNode)
return visited
n=int(input())
g=Graph()
for i in range(n):
g.addNode(i+1)
for i in range(n-1):
g.addEdge(i+1,i+2,1)
a=[int(k) for k in input().split()]
for i in range(n):
if(a[i]!=i+1 and i+2!=a[i]):
g.addEdge(i+1,a[i],1)
ans=dij(g,1)
for i in range(n):
print(ans[i+1], end=" ")
# print(g.edges,g.distance)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After a team finished their training session on Euro football championship, Valeric was commissioned to gather the balls and sort them into baskets. Overall the stadium has *n* balls and *m* baskets. The baskets are positioned in a row from left to right and they are numbered with numbers from 1 to *m*, correspondingly. The balls are numbered with numbers from 1 to *n*.
Valeric decided to sort the balls in the order of increasing of their numbers by the following scheme. He will put each new ball in the basket with the least number of balls. And if he's got several variants, he chooses the basket which stands closer to the middle. That means that he chooses the basket for which is minimum, where *i* is the number of the basket. If in this case Valeric still has multiple variants, he chooses the basket with the minimum number.
For every ball print the number of the basket where it will go according to Valeric's scheme.
Note that the balls are sorted into baskets in the order of increasing numbers, that is, the first ball goes first, then goes the second ball and so on.
|
```python
n, m = map(int, input().split())
# i%m vai de 0 ate m-1
for i in range(n):
if (m+i%m)%2 > 0:
# pega o valor medio, valores entre (m+1)/2 até m
print(str(int((m+i%m+1)/2)))
else:
# Pega o valor médio que seja menor ou igual a metade de m.
# Portanto valores entre 1 até m/2
print(str(int((m-(i%m))/2)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky digits in it is a lucky number. He wonders whether number *n* is a nearly lucky number.
|
```python
n = input()
if n.count('4') + n.count('7') in [4,7]:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The translation from the Berland language into the Birland language is not an easy task. Those languages are very similar: a berlandish word differs from a birlandish word with the same meaning a little: it is spelled (and pronounced) reversely. For example, a Berlandish word code corresponds to a Birlandish word edoc. However, it's easy to make a mistake during the «translation». Vasya translated word *s* from Berlandish into Birlandish as *t*. Help him: find out if he translated the word correctly.
|
```python
text = str(input())
text2 = str(input())
if text2 == text[::-1]:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You can find anything whatsoever in our Galaxy! A cubical planet goes round an icosahedral star. Let us introduce a system of axes so that the edges of the cubical planet are parallel to the coordinate axes and two opposite vertices lay in the points (0,<=0,<=0) and (1,<=1,<=1). Two flies live on the planet. At the moment they are sitting on two different vertices of the cubical planet. Your task is to determine whether they see each other or not. The flies see each other when the vertices they occupy lie on the same face of the cube.
|
```python
if (int(input()[::2], 2) + int(input()[::2], 2)) == 7:
print("NO")
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A burglar got into a matches warehouse and wants to steal as many matches as possible. In the warehouse there are *m* containers, in the *i*-th container there are *a**i* matchboxes, and each matchbox contains *b**i* matches. All the matchboxes are of the same size. The burglar's rucksack can hold *n* matchboxes exactly. Your task is to find out the maximum amount of matches that a burglar can carry away. He has no time to rearrange matches in the matchboxes, that's why he just chooses not more than *n* matchboxes so that the total amount of matches in them is maximal.
|
```python
n,m=map(int,input().split())
l=[]
for i in range(m):
l.append(list(map(int,input().split())))
l.sort(key= lambda x : (x[1],x[0]), reverse= True)
print(l)
ans=0
for i in l:
a=min(n,i[0])
ans+=a*i[1]
n-=a
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
|
```python
n = int(input())
a = input().split()
b = set()
for i in a:
c = [0] * 37
for j in i:
c[ord(j) - ord('a')] = 1
now = 0
p = 37
for j in range(26):
if c[j] == 1:
now += p * (j + 1)
p *= 37
b.add(now)
print(len(b))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Misha and Andrew were playing a very simple game. First, each player chooses an integer in the range from 1 to *n*. Let's assume that Misha chose number *m*, and Andrew chose number *a*.
Then, by using a random generator they choose a random integer *c* in the range between 1 and *n* (any integer from 1 to *n* is chosen with the same probability), after which the winner is the player, whose number was closer to *c*. The boys agreed that if *m* and *a* are located on the same distance from *c*, Misha wins.
Andrew wants to win very much, so he asks you to help him. You know the number selected by Misha, and number *n*. You need to determine which value of *a* Andrew must choose, so that the probability of his victory is the highest possible.
More formally, you need to find such integer *a* (1<=≤<=*a*<=≤<=*n*), that the probability that is maximal, where *c* is the equiprobably chosen integer from 1 to *n* (inclusive).
|
```python
import sys, collections, bisect, heapq, functools, itertools, math
input = sys.stdin.readline
n, m = [int(x) for x in input().split()]
if n - m > m - 1:
print(min(n, m + 1))
else:
print(max(1, m - 1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Amr loves Geometry. One day he came up with a very interesting problem.
Amr has a circle of radius *r* and center in point (*x*,<=*y*). He wants the circle center to be in new position (*x*',<=*y*').
In one step Amr can put a pin to the border of the circle in a certain point, then rotate the circle around that pin by any angle and finally remove the pin.
Help Amr to achieve his goal in minimum number of steps.
|
```python
import math
r,x0,y0,x1,y1=map(int,input().split())
d = math.sqrt((x1-x0)^2+(y1-y0)^2)
s = d/(r<<1)
print(math.ceil(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and then each of them shows some number of fingers on one hand (one to five), and then the boys count in a circle, starting from Dima, the number of people, respective to the total number of fingers shown. The person on who the countdown stops will clean the apartment.
For example, if Dima and one of his friends played hide and seek, and 7 fingers were shown during the counting-out, then Dima would clean the place. If there were 2 or say, 8 fingers shown, then his friend would clean the place.
Dima knows how many fingers each of his friends will show during the counting-out. Now he is interested in the number of ways to show some number of fingers on one hand (one to five), so that he did not have to clean the place. Help Dima.
|
```python
n = int(input())
total = 0
z = [x for x in map(int,input().split())]
for i in z:
total += i
answer = 0
for i in range(1,5+1):
if(total+i) % (n+1) != 1:
answer += 1
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
|
```python
from sys import stdin
n=int(stdin.readline())
a=[int(x) for x in stdin.readline().split()]
for i in range(n):
c=0
for j in range(n):
if a[i]<a[j]:
c+=1
print(c+1,end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas?
|
```python
k,n,w=map(int,input().split())
a=w*(2*k+(w-1)*k)//2
print(a-n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Joty has got a task to do. She has a line of *n* tiles indexed from 1 to *n*. She has to paint them in a strange pattern.
An unpainted tile should be painted Red if it's index is divisible by *a* and an unpainted tile should be painted Blue if it's index is divisible by *b*. So the tile with the number divisible by *a* and *b* can be either painted Red or Blue.
After her painting is done, she will get *p* chocolates for each tile that is painted Red and *q* chocolates for each tile that is painted Blue.
Note that she can paint tiles in any order she wants.
Given the required information, find the maximum number of chocolates Joty can get.
|
```python
n,a,b,p,q=map(int,input().split())
import math
x=(a*b)//math.gcd(a,b)
if(p>q):
print((n//a)*p+(n//b)*q-(n//x)*q)
else:
print((n//a)*p+(n//b)*q-(n//x)*p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to answer the questions like that: if the question’s last letter is a vowel, they answer "Yes" and if the last letter is a consonant, they answer "No". Of course, the sleuth knows nothing about it and his task is to understand that.
Unfortunately, Vasya is not very smart. After 5 hours of endless stupid questions everybody except Vasya got bored. That’s why Vasya’s friends ask you to write a program that would give answers instead of them.
The English alphabet vowels are: A, E, I, O, U, Y
The English alphabet consonants are: B, C, D, F, G, H, J, K, L, M, N, P, Q, R, S, T, V, W, X, Z
|
```python
f = str(input())
g = f[::-1]
g = g.lower()
g= g.replace("?"," ")
l1= ['a','e','y','i','o','u']
x=0
l = ''
for y in g:
if ord(y) in range(97,123):
l =y
break
else:
pass
if l in l1:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hongcow really likes the color red. Hongcow doesn't like the color blue.
Hongcow is standing in an infinite field where there are *n* red points and *m* blue points.
Hongcow wants to draw a circle in the field such that this circle contains at least one red point, and no blue points. Points that line exactly on the boundary of the circle can be counted as either inside or outside.
Compute the radius of the largest circle that satisfies this condition. If this circle can have arbitrarily large size, print <=-<=1. Otherwise, your answer will be accepted if it has relative or absolute error at most 10<=-<=4.
|
```python
import itertools
red = []
blue = []
input_ = input()
x = input_.split(" ")
i = 0
j = 0
points = []
#blue = []
while i < int(x[0]):
k = input()
points.append(k)
red.append(k)
i+=1
while j < int(x[1]):
l = input()
points.append(l)
blue.append(l)
j+=1
# print("red: ",red)
# print("blue: ",blue)
# print("points: ",points)
def GetRadandCenter(x):
x1, y1, x2, y2, x3, y3 = map(float, x.split(" "))
c = (x1-x2)**2 + (y1-y2)**2
a = (x2-x3)**2 + (y2-y3)**2
b = (x3-x1)**2 + (y3-y1)**2
s = 2*(a*b + b*c + c*a) - (a*a + b*b + c*c)
if s == 0:
return -1,1,1
else:
px = (a*(b+c-a)*x1 + b*(c+a-b)*x2 + c*(a+b-c)*x3) / s
py = (a*(b+c-a)*y1 + b*(c+a-b)*y2 + c*(a+b-c)*y3) / s
ar = a**0.5
br = b**0.5
cr = c**0.5
r = ar*br*cr / ((ar+br+cr)*(-ar+br+cr)*(ar-br+cr)*(ar+br-cr))**0.5
return r,px,py
#Create all possible permutations
perm = []
for comb in itertools.combinations(points, 3):
perm.append(comb)
# print("perm: ",perm)
validity = []
radii = []
#Special case if no limit
for z in red:
for q in blue:
# print("---------------")
# print("red: ",z)
# print("blue: ",q)
# print("blue whole list: ",blue)
side1 = "No"
side2 = "No"
# other_blue = blue
# other_blue.remove(q)
# print("q: ",q)
z_temp = z.split(" ")
x1 = int(z_temp[0])
y1 = int(z_temp[1])
q_temp = q.split(" ")
x2 = int(q_temp[0])
y2 = int(q_temp[1])
if (x2 - x1) == 0:
side1,side2 = "Yes","Yes"
continue
slope = (y2 - y1)/(x2 - x1)
b = y1 - slope*x1
for o in blue:
o_temp = o.split(" ")
x3 = int(o_temp[0])
y3 = int(o_temp[1])
# print("Test Coordinates: ", x3,y3)
if y3 > slope*x3 + b:
side1 = "Yes"
# print("Blue point: ", o)
if y3 < slope*x3 + b:
side2 = "Yes"
# print("Blue point: ", o)
# print("side1: ", side1)
# print("side2: ", side2)
if side1 == "No" or side2 == "No":
print("-1")
else:
#If red is not included, check if red is inside
for t in perm:
status = "Invalid"
r,px,py = GetRadandCenter(t[0]+" "+t[1]+" "+t[2])
# print("------------------------")
# print("radius: ",r)
# print("center: ",px,py)
# print("points: ", t)
#Check if arc contains a red point
for u in t:
if u in red:
status = "Valid"
break
#Check if any red is inside it
if status == "Invalid":
for m in red:
m = m.split(" ")
x = int(m[0])
y = int(m[1])
# print(x,y,px,py,r)
if ((x-int(px))**2) +((y-int(py))**2) <= int(r)**2:
status = "Valid"
break
#Check if there are any blue dots within the circle
if status == "Valid":
for c in blue:
if c in t:
continue
c = c.split(" ")
x = int(c[0])
y = int(c[1])
if int(((x-int(px))**2) +((y-int(py))**2)) < int(int(r)**2):
status = "Invalid"
# print("x,y: ",x,y)
# print("LHS: ",((x-int(px))**2) +((y-int(py))**2))
# print("RHS: ",int(r)**2 )
break
if status == "Invalid":
r = -1
# print(status)
validity.append(status)
radii.append(r)
# print(validity)
# print(radii)
print(max(radii))
exit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Robber Girl likes to scare animals in her zoo for fun. She decided to arrange the animals in a row in the order of non-decreasing height. However, the animals were so scared that they couldn't stay in the right places.
The robber girl was angry at first, but then she decided to arrange the animals herself. She repeatedly names numbers *l* and *r* such that *r*<=-<=*l*<=+<=1 is even. After that animals that occupy positions between *l* and *r* inclusively are rearranged as follows: the animal at position *l* swaps places with the animal at position *l*<=+<=1, the animal *l*<=+<=2 swaps with the animal *l*<=+<=3, ..., finally, the animal at position *r*<=-<=1 swaps with the animal *r*.
Help the robber girl to arrange the animals in the order of non-decreasing height. You should name at most 20<=000 segments, since otherwise the robber girl will become bored and will start scaring the animals again.
|
```python
def solve(a):
segments = []
while True:
changed = False
for i in range(len(a) - 1):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
segments.append(f"{i + 1} {i + 2}")
changed = True
if not changed:
break
return "\n".join(segments)
def main():
n = int(input())
a = list(map(int, input().split()))
result = solve(a)
print(result)
if __name__ == "__main__":
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Simon and Antisimon play a game. Initially each player receives one fixed positive integer that doesn't change throughout the game. Simon receives number *a* and Antisimon receives number *b*. They also have a heap of *n* stones. The players take turns to make a move and Simon starts. During a move a player should take from the heap the number of stones equal to the greatest common divisor of the fixed number he has received and the number of stones left in the heap. A player loses when he cannot take the required number of stones (i. e. the heap has strictly less stones left than one needs to take).
Your task is to determine by the given *a*, *b* and *n* who wins the game.
|
```python
for t in range(int(input())):
a,b,c = map(int, input().split())
if c%2==0:
print(1)
else:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
|
```python
import sys; R = sys.stdin.readline
for _ in range(int(R())):
s = R().split()[0]
sys.stdin.flush()
for i in range(1, len(s) - 1):
sub1 = s[:i]
sub2 = s[i]
sub3 = s[i + 1:]
if (sub2 >= sub1 and sub2 >= sub3) or (sub2 <= sub1 and sub2 <= sub3):
print(sub1, sub2, sub3)
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
We've got no test cases. A big olympiad is coming up. But the problemsetters' number one priority should be adding another problem to the round.
The diameter of a multiset of points on the line is the largest distance between two points from this set. For example, the diameter of the multiset {1,<=3,<=2,<=1} is 2.
Diameter of multiset consisting of one point is 0.
You are given *n* points on the line. What is the minimum number of points you have to remove, so that the diameter of the multiset of the remaining points will not exceed *d*?
|
```python
n, d = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
i = 0
j = 1
l = 0
tl = 1
while True:
if abs(a[i] - a[j]) <= d:
tl += 1
j += 1
else:
if tl > l:
l = tl
tl = 1
i += 1
j = i + 1
if i >= n - 1 or j >= n:
if tl > l:
l = tl
break
print(n - l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The School №0 of the capital of Berland has *n* children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value *t**i*:
- *t**i*<==<=1, if the *i*-th child is good at programming, - *t**i*<==<=2, if the *i*-th child is good at maths, - *t**i*<==<=3, if the *i*-th child is good at PE
Each child happens to be good at exactly one of these three subjects.
The Team Scientific Decathlon Olympias requires teams of three students. The school teachers decided that the teams will be composed of three children that are good at different subjects. That is, each team must have one mathematician, one programmer and one sportsman. Of course, each child can be a member of no more than one team.
What is the maximum number of teams that the school will be able to present at the Olympiad? How should the teams be formed for that?
|
```python
NoOfstudents=int(input())
students=[int(x) for x in input().split()]
maths=[]
programming=[]
PE=[]
if NoOfstudents>=3:
for i in range(len(students)):
if students[i]==1:
programming.append(i+1)
elif students[i]==2:
maths.append(i+1)
elif students[i]==3:
PE.append(i+1)
NoOfTeams=min(len(programming),len(maths),len(PE))
print(NoOfTeams)
for i in range(NoOfTeams):
print(programming[i],maths[i],PE[i])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Little Vasya has received a young builder’s kit. The kit consists of several wooden bars, the lengths of all of them are known. The bars can be put one on the top of the other if their lengths are the same.
Vasya wants to construct the minimal number of towers from the bars. Help Vasya to use the bars in the best way possible.
|
```python
from collections import defaultdict
n=int(input())
a=list(map(int,input().split()))
d=defaultdict(int)
for i in a:
d[i]+=1
data,l=0,0
for i in d:
data=max(data,i*d[i])
l+=1
print(data,l)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a rectangular board of *M*<=×<=*N* squares. Also you are given an unlimited number of standard domino pieces of 2<=×<=1 squares. You are allowed to rotate the pieces. You are asked to place as many dominoes as possible on the board so as to meet the following conditions:
1. Each domino completely covers two squares.
2. No two dominoes overlap.
3. Each domino lies entirely inside the board. It is allowed to touch the edges of the board.
Find the maximum number of dominoes, which can be placed under these restrictions.
|
```python
area = [int(x) for x in input().split(" ")]
area = (area[0] * area[1]) - (area[0] * area[1] % 2)
print(area // 2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Unfortunately, Vasya can only sum pairs of integers (*a*, *b*), such that for any decimal place at least one number has digit 0 in this place. For example, Vasya can sum numbers 505 and 50, but he cannot sum 1 and 4.
Vasya has a set of *k* distinct non-negative integers *d*1,<=*d*2,<=...,<=*d**k*.
Vasya wants to choose some integers from this set so that he could sum any two chosen numbers. What maximal number of integers can he choose in the required manner?
|
```python
from collections import defaultdict
n = int(input())
arr = [int(x) for x in input().split()]
ans = []
d = defaultdict(bool)
for i in arr:
if(i % 100 == 0 and not d[100]):
d[100] = True
ans.append(i)
elif(i % 10 == 0 and not d[10]):
d[10] = True
ans.append(i)
elif(i == 0):
ans.append(i)
if(d[10]):
for i in arr:
if('0' not in str(i) and len(str(i)) == 1):
ans.append(i)
break
else:
for i in arr:
if('0' not in str(i)):
ans.append(i)
break
print(len(ans))
print(*ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a right triangle with legs of length *a* and *b*. Your task is to determine whether it is possible to locate the triangle on the plane in such a way that none of its sides is parallel to the coordinate axes. All the vertices must have integer coordinates. If there exists such a location, you have to output the appropriate coordinates of vertices.
|
```python
import sys
input = sys.stdin.readline
def f(x):
s = set()
for i in range(1, x):
y = (x**2 - i**2)**0.5
if y == int(y):
s.add((i, int(y)))
return s
a, b = map(int, input().split())
d = f(a)
q = f(b)
for i1, i2 in d:
for i3, i4 in q:
if i1*i4 == i2*i3:
print('YES')
print(0, 0)
print(-i1, i2)
print(i4, i3)
exit()
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentally switched on, if:
- either it only contains uppercase letters; - or all letters except for the first one are uppercase.
In this case we should automatically change the case of all letters. For example, the case of the letters that form words "hELLO", "HTTP", "z" should be changed.
Write a program that applies the rule mentioned above. If the rule cannot be applied, the program should leave the word unchanged.
|
```python
ss="aeiou"
s=input()
num=0
for i in range(0,len(s)):
if s[i] in ss:
num=i
aa=s[0:num+1]+'ntry'
print (aa.capitalize ())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is mad about coding, that is why he writes Sveta encoded messages. He calls the median letter in a word the letter which is in the middle of the word. If the word's length is even, the median letter is the left of the two middle letters. In the following examples, the median letter is highlighted: contest, info. If the word consists of single letter, then according to above definition this letter is the median letter.
Polycarp encodes each word in the following way: he writes down the median letter of the word, then deletes it and repeats the process until there are no letters left. For example, he encodes the word volga as logva.
You are given an encoding *s* of some word, your task is to decode it.
|
```python
n=int(input())
s=input()
a=list(s)
if len(a)%2!=0:
p=""
f=""
for i in range(len(s)):
if i%2==0:
p+=a[i]
else:
f+=a[i]
print(f[::-1]+p)
else:
p=""
f=""
for i in range(len(s)):
if i%2==0:
f+=a[i]
else:
p+=a[i]
print(f[::-1]+p)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
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.
|
```python
S = input()
def is_open(x):
return x == '<' or x == '{' or x == '[' or x == '('
def is_match(x, y):
if x == '<':
return y == '>'
elif x == '{':
return y == '}'
elif x == '[':
return y == ']'
else:
return y == ')'
open_cnt = 0
close_cnt = 0
stack = []
for s in S:
if not is_open(s):
if len(stack) > 0 and is_open(stack[-1]) and is_match(stack[-1], s):
stack.pop()
open_cnt-= 1
else:
close_cnt+= 1
stack.append(s)
else:
open_cnt+= 1
stack.append(s)
print(stack)
if(open_cnt == close_cnt):
print(open_cnt)
else:
print('Impossible')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.
Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.
This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.
Thus, "localization" will be spelt as "l10n", and "internationalization» will be spelt as "i18n".
You are suggested to automatize the process of changing the words with abbreviations. At that all too long words should be replaced by the abbreviation and the words that are not too long should not undergo any changes.
|
```python
n = int (input())
for i in range (n):
word = input()
if len (word) <= 10:
print (word)
else:
print (word[0] + str (len (word) - 2) + word[len(word) - 1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
On Children's Day, the child got a toy from Delayyy as a present. However, the child is so naughty that he can't wait to destroy the toy.
The toy consists of *n* parts and *m* ropes. Each rope links two parts, but every pair of parts is linked by at most one rope. To split the toy, the child must remove all its parts. The child can remove a single part at a time, and each remove consume an energy. Let's define an energy value of part *i* as *v**i*. The child spend *v**f*1<=+<=*v**f*2<=+<=...<=+<=*v**f**k* energy for removing part *i* where *f*1,<=*f*2,<=...,<=*f**k* are the parts that are directly connected to the *i*-th and haven't been removed.
Help the child to find out, what is the minimum total energy he should spend to remove all *n* parts.
|
```python
n, m = map(int, input().split())
f = [int(x) for x in input().split()]
ans = 0
for i in range(m):
a, b = map(int, input().split())
ans += min(f[a - 1], f[b - 1])
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There were *n* groups of students which came to write a training contest. A group is either one person who can write the contest with anyone else, or two people who want to write the contest in the same team.
The coach decided to form teams of exactly three people for this training. Determine the maximum number of teams of three people he can form. It is possible that he can't use all groups to form teams. For groups of two, either both students should write the contest, or both should not. If two students from a group of two will write the contest, they should be in the same team.
|
```python
n=int(input())
a=list(map(int,input().split()))
if 1 not in a:
print("0")
elif 2 not in a:
print(n//3)
else:
x=a.count(1)
y=a.count(2)
if y>=x:
print(x)
else:
print(x + ((x-y)//3))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vanya walks late at night along a straight street of length *l*, lit by *n* lanterns. Consider the coordinate system with the beginning of the street corresponding to the point 0, and its end corresponding to the point *l*. Then the *i*-th lantern is at the point *a**i*. The lantern lights all points of the street that are at the distance of at most *d* from it, where *d* is some positive number, common for all lanterns.
Vanya wonders: what is the minimum light radius *d* should the lanterns have to light the whole street?
|
```python
n,l = map(int, input().split())
lntr = list(map(int,input().split()))
lntr.sort()
maxi = 0
for i in range(n-1):
maxi = max(maxi,lntr[i+1]-lntr[i])
res = max([maxi/2, lntr[0]-0, l-lntr[n-1]])
print(float(res))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Hooray! Berl II, the king of Berland is making a knight tournament. The king has already sent the message to all knights in the kingdom and they in turn agreed to participate in this grand event.
As for you, you're just a simple peasant. There's no surprise that you slept in this morning and were late for the tournament (it was a weekend, after all). Now you are really curious about the results of the tournament. This time the tournament in Berland went as follows:
- There are *n* knights participating in the tournament. Each knight was assigned his unique number — an integer from 1 to *n*. - The tournament consisted of *m* fights, in the *i*-th fight the knights that were still in the game with numbers at least *l**i* and at most *r**i* have fought for the right to continue taking part in the tournament. - After the *i*-th fight among all participants of the fight only one knight won — the knight number *x**i*, he continued participating in the tournament. Other knights left the tournament. - The winner of the last (the *m*-th) fight (the knight number *x**m*) became the winner of the tournament.
You fished out all the information about the fights from your friends. Now for each knight you want to know the name of the knight he was conquered by. We think that the knight number *b* was conquered by the knight number *a*, if there was a fight with both of these knights present and the winner was the knight number *a*.
Write the code that calculates for each knight, the name of the knight that beat him.
|
```python
def update(v,l,r,src,p_src,kl,kr):
if(l>r or la[v]==-1):
return
if(kl==kr):
la[v]=src
visited[kl]=src
return
else:
km=(kl+kr)//2
update(2*v,l,min(r,km),src,p_src,kl,km)
update(2*v+1,max(km+1,l),r,src,p_src,km+1,kr)
if(la[2*v]>-2 and la[2*v+1]>-2):
la[v]=-1
visited[p_src]=src
n,m=map(int,input().split())
i=1
while(2**i<n):
i+=1
capture=i
la=[-2 for j in range(4*n)]
p_scs=0
visited=[0 for i in range(n+1)]
for i in range(m):
l,r,scs=map(int,input().split())
update(1,l,r,scs,p_scs,1,2**capture)
p_scs=scs
visited[p_scs]=0
for i in range(1,n+1):
print(visited[i],end=' ')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The R1 company has recently bought a high rise building in the centre of Moscow for its main office. It's time to decorate the new office, and the first thing to do is to write the company's slogan above the main entrance to the building.
The slogan of the company consists of *n* characters, so the decorators hung a large banner, *n* meters wide and 1 meter high, divided into *n* equal squares. The first character of the slogan must be in the first square (the leftmost) of the poster, the second character must be in the second square, and so on.
Of course, the R1 programmers want to write the slogan on the poster themselves. To do this, they have a large (and a very heavy) ladder which was put exactly opposite the *k*-th square of the poster. To draw the *i*-th character of the slogan on the poster, you need to climb the ladder, standing in front of the *i*-th square of the poster. This action (along with climbing up and down the ladder) takes one hour for a painter. The painter is not allowed to draw characters in the adjacent squares when the ladder is in front of the *i*-th square because the uncomfortable position of the ladder may make the characters untidy. Besides, the programmers can move the ladder. In one hour, they can move the ladder either a meter to the right or a meter to the left.
Drawing characters and moving the ladder is very tiring, so the programmers want to finish the job in as little time as possible. Develop for them an optimal poster painting plan!
|
```python
(n, k) = [int(r) for r in input().split()]
s = input()
if k <= n // 2:
while k > 1:
print("LEFT")
k -= 1
print("\nRIGHT\n".join(("PRINT " + c) for c in s))
else:
while k < n:
print("RIGHT")
k += 1
print("\nLEFT\n".join(("PRINT " + c) for c in reversed(s)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After celebrating the midcourse the students of one of the faculties of the Berland State University decided to conduct a vote for the best photo. They published the photos in the social network and agreed on the rules to choose a winner: the photo which gets most likes wins. If multiple photoes get most likes, the winner is the photo that gets this number first.
Help guys determine the winner photo by the records of likes.
|
```python
def run(n, arr):
photos = []
top = dict(id=arr.pop(0), likes=1)
for id in arr:
found = False
for photo in photos:
if photo['id'] == id:
found = True
photo['likes'] += 1
if photo['likes'] > top['likes']:
top = photo
break
if not found:
photos.append(dict(id=id, likes=1))
return top['id']
def read_data():
n = int(input())
arr = [int(x) for x in input().split(" ")]
return n, arr
n, arr = read_data()
print(run(n, arr))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sengoku still remembers the mysterious "colourful meteoroids" she discovered with Lala-chan when they were little. In particular, one of the nights impressed her deeply, giving her the illusion that all her fancies would be realized.
On that night, Sengoku constructed a permutation *p*1,<=*p*2,<=...,<=*p**n* of integers from 1 to *n* inclusive, with each integer representing a colour, wishing for the colours to see in the coming meteor outburst. Two incredible outbursts then arrived, each with *n* meteorids, colours of which being integer sequences *a*1,<=*a*2,<=...,<=*a**n* and *b*1,<=*b*2,<=...,<=*b**n* respectively. Meteoroids' colours were also between 1 and *n* inclusive, and the two sequences were not identical, that is, at least one *i* (1<=≤<=*i*<=≤<=*n*) exists, such that *a**i*<=≠<=*b**i* holds.
Well, she almost had it all — each of the sequences *a* and *b* matched exactly *n*<=-<=1 elements in Sengoku's permutation. In other words, there is exactly one *i* (1<=≤<=*i*<=≤<=*n*) such that *a**i*<=≠<=*p**i*, and exactly one *j* (1<=≤<=*j*<=≤<=*n*) such that *b**j*<=≠<=*p**j*.
For now, Sengoku is able to recover the actual colour sequences *a* and *b* through astronomical records, but her wishes have been long forgotten. You are to reconstruct any possible permutation Sengoku could have had on that night.
|
```python
n = int(input())
ai = list(map(int,input().split()))
bi = list(map(int,input().split()))
ci = [0]*n
for i in range(n):
ci[i] = ai[i]
nums = [0]*n
ind = [0]*2
j = 0
num = 0
for i in range(n):
nums[ai[i]-1] += 1
for i in range(n):
if nums[ai[i]-1] == 2:
ind[j] = i
j += 1
if nums[i] == 0:
num = i+1
ci[ind[0]] = num
dif = 0
dif2 = 0
for i in range(n):
if ci[i] != bi[i]:
dif += 1
if ci[i] != ai[i]:
dif2 += 1
if dif != 1 or dif2 != 1:
ci[ind[0]] = ai[ind[0]]
ci[ind[1]] = num
for i in range(n):
print(ci[i],end=" ")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow three-letter numbers, etc.
The rows are marked by integer numbers starting with 1. The cell name is the concatenation of the column and the row numbers. For example, BC23 is the name for the cell that is in column 55, row 23.
Sometimes another numeration system is used: RXCY, where X and Y are integer numbers, showing the column and the row numbers respectfully. For instance, R23C55 is the cell from the previous example.
Your task is to write a program that reads the given sequence of cell coordinates and produce each item written according to the rules of another numeration system.
|
```python
import sys
input=sys.stdin.readline
m=1000000007
#------------------------------------#
for _ in range(int(input())):
cell=input().strip()
if cell[0]=="R":
#convert to AA format
secindex=cell.index("C")
number1=int(cell[1:secindex])
number2=int(cell[secindex+1:])-1
column=""
while(number2>0):
column+=chr(ord("A")+number2%26)
number2=number2//26-1
print(column[::-1],number1,sep="")
else:
i=0
column=0
while(not cell[i].isdigit()):
column=column*26+ord(cell[i])-ord("A")+1
i+=1
print("R"+cell[i:]+"C"+str(column))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having *n* nodes, numbered from 1 to *n*. Each node *i* has an initial value *init**i*, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node *x*. Right after someone has picked node *x*, the value of node *x* flips, the values of sons of *x* remain the same, the values of sons of sons of *x* flips, the values of sons of sons of sons of *x* remain the same and so on.
The goal of the game is to get each node *i* to have value *goal**i*, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
|
```python
n=int(input())
from collections import defaultdict
graph=defaultdict(list)
for i in range(n-1):
u,v=[int(i) for i in input().split()]
graph[u].append(v)
graph[v].append(u)
curr=[int(i) for i in input().split()]
goal=[int(i) for i in input().split()]
ops=[]
def dfs(parent,ver,odd,even,lev):
par=lev%2
temp=curr[ver-1]
changed=0
if par and odd%2:
temp=curr[ver-1]^1
if par==0 and even%2:
temp=curr[ver-1]^1
#print(curr[ver-1],goal[ver-1])
if temp!=goal[ver-1]:
ops.append(ver)
changed=1
for ne in graph[ver]:
if ne!=parent:
if changed:
if lev%2:
dfs(ver,ne,odd+1,even,lev+1)
else:
dfs(ver,ne,odd,even+1,lev+1)
else:
dfs(ver,ne,odd,even,lev+1)
dfs(-1,1,0,0,0)
print(len(ops))
for i in ops:
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mahmoud has an array *a* consisting of *n* integers. He asked Ehab to find another array *b* of the same length such that:
- *b* is lexicographically greater than or equal to *a*. - *b**i*<=≥<=2. - *b* is pairwise coprime: for every 1<=≤<=*i*<=<<=*j*<=≤<=*n*, *b**i* and *b**j* are coprime, i. e. *GCD*(*b**i*,<=*b**j*)<==<=1, where *GCD*(*w*,<=*z*) is the greatest common divisor of *w* and *z*.
Ehab wants to choose a special array so he wants the lexicographically minimal array between all the variants. Can you find it?
An array *x* is lexicographically greater than an array *y* if there exists an index *i* such than *x**i*<=><=*y**i* and *x**j*<==<=*y**j* for all 1<=≤<=*j*<=<<=*i*. An array *x* is equal to an array *y* if *x**i*<==<=*y**i* for all 1<=≤<=*i*<=≤<=*n*.
|
```python
print("Even")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Bachgold problem is very easy to formulate. Given a positive integer *n* represent it as a sum of maximum possible number of prime numbers. One can prove that such representation exists for any integer greater than 1.
Recall that integer *k* is called prime if it is greater than 1 and has exactly two positive integer divisors — 1 and *k*.
|
```python
def isprime(n):
for n in range(n,100001):
s=int(n**(0.5))
f=1
for j in range(2,s+1):
if(n%j==0):
f=0
break
if(f==1):
return(n)
print(isprime(20))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A company has *n* employees numbered from 1 to *n*. Each employee either has no immediate manager or exactly one immediate manager, who is another employee with a different number. An employee *A* is said to be the superior of another employee *B* if at least one of the following is true:
- Employee *A* is the immediate manager of employee *B* - Employee *B* has an immediate manager employee *C* such that employee *A* is the superior of employee *C*.
The company will not have a managerial cycle. That is, there will not exist an employee who is the superior of his/her own immediate manager.
Today the company is going to arrange a party. This involves dividing all *n* employees into several groups: every employee must belong to exactly one group. Furthermore, within any single group, there must not be two employees *A* and *B* such that *A* is the superior of *B*.
What is the minimum number of groups that must be formed?
|
```python
dic = dict()
num = int(input())
count = 0
check = list()
for n in range(1, num + 1):
employee = n
manager = int(input())
if manager in dic:
dic[manager].append(employee)
else:
dic[manager] = list()
dic[manager].append(employee)
check = dic[-1]
size = len(check)
while size > 0:
for i in range(size):
employee = check.pop()
if employee in dic:
for elem in dic[employee]:
check.append(elem)
size = len(check)
count += 1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mikhail walks on a 2D plane. He can go either up or right. You are given a sequence of Mikhail's moves. He thinks that this sequence is too long and he wants to make it as short as possible.
In the given sequence moving up is described by character U and moving right is described by character R. Mikhail can replace any pair of consecutive moves RU or UR with a diagonal move (described as character D). After that, he can go on and do some other replacements, until there is no pair of consecutive moves RU or UR left.
Your problem is to print the minimum possible length of the sequence of moves after the replacements.
|
```python
n-int(input())
x=input().lower()
i-0
while i < len(x) -1:
if x[i]+x[i+1] in ('ur', 'ru'):
i=i+2
n=n-1
else:
i=i+1
print (n)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system.
The term is coming to an end and students start thinking about their grades. Today, a professor told his students that the grades for his course would be given out automatically — he would calculate the simple average (arithmetic mean) of all grades given out for lab works this term and round to the nearest integer. The rounding would be done in favour of the student — $4.5$ would be rounded up to $5$ (as in example 3), but $4.4$ would be rounded down to $4$.
This does not bode well for Vasya who didn't think those lab works would influence anything, so he may receive a grade worse than $5$ (maybe even the dreaded $2$). However, the professor allowed him to redo some of his works of Vasya's choosing to increase his average grade. Vasya wants to redo as as few lab works as possible in order to get $5$ for the course. Of course, Vasya will get $5$ for the lab works he chooses to redo.
Help Vasya — calculate the minimum amount of lab works Vasya has to redo.
|
```python
n=int(input())
a=list(map(int,input().split()))
k=sum(a)
av=k/n
c=0
if(av<4.5):
a.sort()
s=int(n*4.5)-k
if(n%2!=0):
s+=1
q=0
for i in range(n):
if(q>=s):
break
else:
q+=5-a[i]
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Harry Potter is on a mission to destroy You-Know-Who's Horcruxes. The first Horcrux that he encountered in the Chamber of Secrets is Tom Riddle's diary. The diary was with Ginny and it forced her to open the Chamber of Secrets. Harry wants to know the different people who had ever possessed the diary to make sure they are not under its influence.
He has names of *n* people who possessed the diary in order. You need to tell, for each person, if he/she possessed the diary at some point before or not.
Formally, for a name *s**i* in the *i*-th line, output "YES" (without quotes) if there exists an index *j* such that *s**i*<==<=*s**j* and *j*<=<<=*i*, otherwise, output "NO" (without quotes).
|
```python
n=int(input())
lista=[]
for i in range(n):
nam=input()
if nam in lista:
print("YES")
else:
lista.append(nam)
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja has an array *a*, consisting of *n* integers *a*1, *a*2, ..., *a**n*. The boy cannot sit and do nothing, he decided to study an array. Sereja took a piece of paper and wrote out *m* integers *l*1,<=*l*2,<=...,<=*l**m* (1<=≤<=*l**i*<=≤<=*n*). For each number *l**i* he wants to know how many distinct numbers are staying on the positions *l**i*, *l**i*<=+<=1, ..., *n*. Formally, he want to find the number of distinct numbers among *a**l**i*,<=*a**l**i*<=+<=1,<=...,<=*a**n*.?
Sereja wrote out the necessary array elements but the array was so large and the boy was so pressed for time. Help him, find the answer for the described question for each *l**i*.
|
```python
#采用预处理策略,避免每一次都遍历一遍列表
n,m = map(int,input().split())
line = list(map(int,input().split()))
distinct_nums = []
visited = [0]*100001 #用于标记每一个数字是否被访问过
distinct = 0
for i in range(n-1,-1,-1):
if visited[line[i]] == 0:
distinct += 1
distinct_nums.append(distinct)
visited[line[i]] = 1
else:
distinct_nums.append(distinct)
for i in range(m):
l = int(input())
print(distinct_nums[l-1])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Indian summer is such a beautiful time of the year! A girl named Alyona is walking in the forest and picking a bouquet from fallen leaves. Alyona is very choosy — she doesn't take a leaf if it matches the color and the species of the tree of one of the leaves she already has. Find out how many leaves Alyona has picked.
|
```python
lis=[]
for _ in range(int(input())):
a,b=map(str,input().split())
lis.append([a,b])
ans = []
for i in range(len(lis)):
if lis[i] in ans:
pass
else:
ans.append(lis[i])
print(len(ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
New Year is coming in Line World! In this world, there are *n* cells numbered by integers from 1 to *n*, as a 1<=×<=*n* board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has made a transportation system to move between these cells, to celebrate the New Year. First, he thought of *n*<=-<=1 positive integers *a*1,<=*a*2,<=...,<=*a**n*<=-<=1. For every integer *i* where 1<=≤<=*i*<=≤<=*n*<=-<=1 the condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* holds. Next, he made *n*<=-<=1 portals, numbered by integers from 1 to *n*<=-<=1. The *i*-th (1<=≤<=*i*<=≤<=*n*<=-<=1) portal connects cell *i* and cell (*i*<=+<=*a**i*), and one can travel from cell *i* to cell (*i*<=+<=*a**i*) using the *i*-th portal. Unfortunately, one cannot use the portal backwards, which means one cannot move from cell (*i*<=+<=*a**i*) to cell *i* using the *i*-th portal. It is easy to see that because of condition 1<=≤<=*a**i*<=≤<=*n*<=-<=*i* one can't leave the Line World using portals.
Currently, I am standing at cell 1, and I want to go to cell *t*. However, I don't know whether it is possible to go there. Please determine whether I can go to cell *t* by only using the construted transportation system.
|
```python
l=(input().split())
m=[int(l[0]),int(l[1])]
n=input().split()
p=[]
a=0
for i in range(len(n)):
p=p+[n[i]]
for j in range(len(n)):
a=a+p[j]
if a==l[1]:
print('YES')
break
elif a>l[1]:
print('NO')
break
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Professor GukiZ likes programming contests. He especially likes to rate his students on the contests he prepares. Now, he has decided to prepare a new contest.
In total, *n* students will attend, and before the start, every one of them has some positive integer rating. Students are indexed from 1 to *n*. Let's denote the rating of *i*-th student as *a**i*. After the contest ends, every student will end up with some positive integer position. GukiZ expects that his students will take places according to their ratings.
He thinks that each student will take place equal to . In particular, if student *A* has rating strictly lower then student *B*, *A* will get the strictly better position than *B*, and if two students have equal ratings, they will share the same position.
GukiZ would like you to reconstruct the results by following his expectations. Help him and determine the position after the end of the contest for each of his students if everything goes as expected.
|
```python
students = int(input())
ratings = list(map(int, input().split(' ')))
different_ratings = list(reversed(sorted(set(ratings))))
rankings = {}
for i in range(len(different_ratings)):
if i == 0:
rankings[different_ratings[i]] = 1
else:
rankings[different_ratings[i]] = rankings[different_ratings[i - 1]] + ratings.count(different_ratings[i - 1])
positions = []
for rating in ratings:
positions.append(rankings[rating])
print(*positions)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The input contains two integers *a*1,<=*a*2 (0<=≤<=*a**i*<=≤<=109), separated by a single space.
Output a single integer.
|
```python
n=input().split()
c=int(n[1])
a=[]
b=[]
l=""
o=""
d=[]
for i in n[1]:
a.append(int(i))
a.reverse()
for i in n[0]:
b.append(i)
if len(n[0]) < len(n[1]):
b.insert(0,'0')
for i in range (len(a)):
l+= str(a[i])
o+= str(b[i])
p = int(l)
q = int(o)
print(p+q)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You're given a row with $n$ chairs. We call a seating of people "maximal" if the two following conditions hold:
1. There are no neighbors adjacent to anyone seated. 1. It's impossible to seat one more person without violating the first rule.
The seating is given as a string consisting of zeros and ones ($0$ means that the corresponding seat is empty, $1$ — occupied). The goal is to determine whether this seating is "maximal".
Note that the first and last seats are not adjacent (if $n \ne 2$).
|
```python
n=input()
l='0'+input()+'0'
print('No' if '000' in l or '11' in l else 'Yes')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third room and so on — you can go from the (*n*<=-<=1)-th room to the *n*-th room. Thus, you can go to room *x* only from room *x*<=-<=1.
The potato pie is located in the *n*-th room and Vitaly needs to go there.
Each pair of consecutive rooms has a door between them. In order to go to room *x* from room *x*<=-<=1, you need to open the door between the rooms with the corresponding key.
In total the house has several types of doors (represented by uppercase Latin letters) and several types of keys (represented by lowercase Latin letters). The key of type *t* can open the door of type *T* if and only if *t* and *T* are the same letter, written in different cases. For example, key f can open door F.
Each of the first *n*<=-<=1 rooms contains exactly one key of some type that Vitaly can use to get to next rooms. Once the door is open with some key, Vitaly won't get the key from the keyhole but he will immediately run into the next room. In other words, each key can open no more than one door.
Vitaly realizes that he may end up in some room without the key that opens the door to the next room. Before the start his run for the potato pie Vitaly can buy any number of keys of any type that is guaranteed to get to room *n*.
Given the plan of the house, Vitaly wants to know what is the minimum number of keys he needs to buy to surely get to the room *n*, which has a delicious potato pie. Write a program that will help Vitaly find out this number.
|
```python
n=int(input())
s=list(input())
keys=[0]*26
count=0
for i in range(0, (len(s)//2)):
key = s[i*2]
door = s[i*2+1]
keys[ord(key)-97] += 1
if (keys[ord(door)-65] > 0):
keys[ord(door)-65] -= 1
else:
count+=1
print(count)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A very brave explorer Petya once decided to explore Paris catacombs. Since Petya is not really experienced, his exploration is just walking through the catacombs.
Catacombs consist of several rooms and bidirectional passages between some pairs of them. Some passages can connect a room to itself and since the passages are built on different depths they do not intersect each other. Every minute Petya arbitrary chooses a passage from the room he is currently in and then reaches the room on the other end of the passage in exactly one minute. When he enters a room at minute *i*, he makes a note in his logbook with number *t**i*:
- If Petya has visited this room before, he writes down the minute he was in this room last time; - Otherwise, Petya writes down an arbitrary non-negative integer strictly less than current minute *i*.
Initially, Petya was in one of the rooms at minute 0, he didn't write down number *t*0.
At some point during his wandering Petya got tired, threw out his logbook and went home. Vasya found his logbook and now he is curious: what is the minimum possible number of rooms in Paris catacombs according to Petya's logbook?
|
```python
n = int(input())
t = [int(x) for x in input().split()]
ans = 0
istime = [0] * (2 * 10 ** 5 + 13)
istime[0] = 1
for i in range(n):
if istime[t[i]] > 0:
istime[t[i]] -= 1
else:
ans += 1
istime[i + 1] += 1
print(ans + 1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Arkady and Kirill visited an exhibition of rare coins. The coins were located in a row and enumerated from left to right from 1 to *k*, each coin either was laid with its obverse (front) side up, or with its reverse (back) side up.
Arkady and Kirill made some photos of the coins, each photo contained a segment of neighboring coins. Akrady is interested in obverses, so on each photo made by him there is at least one coin with obverse side up. On the contrary, Kirill is interested in reverses, so on each photo made by him there is at least one coin with its reverse side up.
The photos are lost now, but Arkady and Kirill still remember the bounds of the segments of coins each photo contained. Given this information, compute the remainder of division by 109<=+<=7 of the number of ways to choose the upper side of each coin in such a way, that on each Arkady's photo there is at least one coin with obverse side up, and on each Kirill's photo there is at least one coin with reverse side up.
|
```python
print("_RANDOM_GUESS_1692552615.5669065")# 1692552615.566924
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once at a team training Vasya, Petya and Sasha got a problem on implementing linear search in an array.
According to the boys, linear search works as follows. The array elements in a pre-selected order are in turn compared with the number that you need to find. Once you find the array element that is equal to the required one, the search ends. The efficiency of the algorithm is the number of performed comparisons. The fewer comparisons the linear search has made, the more effective it is.
Vasya believes that a linear search would work better if it sequentially iterates through the elements, starting with the 1-st one (in this problem we consider the elements of the array indexed from 1 to *n*) and ending with the *n*-th one. And Petya says that Vasya is wrong: the search will need less comparisons if it sequentially iterates the elements starting from the *n*-th and ending with the 1-st one. Sasha argues that the two approaches are equivalent.
To finally begin the task, the teammates decided to settle the debate and compare the two approaches on an example. For this, they took an array that is a permutation of integers from 1 to *n*, and generated *m* queries of the form: find element with value *b**i* in the array. They want to calculate for both approaches how many comparisons in total the linear search will need to respond to all queries. If the first search needs fewer comparisons, then the winner of the dispute is Vasya. If the second one does, then the winner is Petya. If both approaches make the same number of comparisons, then Sasha's got the upper hand.
But the problem is, linear search is too slow. That's why the boys aren't going to find out who is right before the end of the training, unless you come in here. Help them to determine who will win the dispute.
|
```python
n1=int(input())
l1=list(map(int,input().split()))
n2=int(input())
l2=list(map(int,input().split()))
s1=0
s2=0
d={}
for i in range(len(l1)):
d[l1[i]]=i
for i in range(len(l2)):
if l2[i] in d:
s1+=d[l2[i]]+1
s2+=n1-d[l2[i]]
print(s1,end=" ")
print(s2)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel has a board with *n* rows and *n* columns, there is one integer in each cell.
It's known that *n* is an odd number, so let's introduce . Fox Ciel can do the following operation many times: she choose a sub-board with size *x* rows and *x* columns, then all numbers in it will be multiplied by -1.
Return the maximal sum of numbers in the board that she can get by these operations.
|
```python
n = int(input())
m = []
for _ in range(n):
m.append(list(map(int, input().split())))
m[-1].append(0)
m.append([0]*(n+1))
x = (n+1)//2
f = [0,0]
def flip(v,k):
return -v if k > 0 else v
sol = int(-1e9)
for s in range(1<<x):
current_sol = 0
for j in range(x):
for k in range(2):
f[k] = 0
for i in range(x):
sum = m[i][j] + flip(m[i+x][j],k) + flip(m[i][j+x],s>>i&1) + flip(m[i+x][j+x],(s>>i&1 ^ s>>(x-1)&1) ^ k)
if j == x - 1:
f[k] += flip(sum, s>>i & 1)
elif i == x - 1:
f[k] += flip(sum,k)
else:
f[k] += max(sum, -sum)
current_sol += (max(f[0],f[1]) if j != x-1 else f[s>>(x-1)])
sol = max(sol, current_sol)
print(sol)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*):
- point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s left neighbor, if *x*'<=<<=*x* and *y*'<==<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s lower neighbor, if *x*'<==<=*x* and *y*'<=<<=*y* - point (*x*',<=*y*') is (*x*,<=*y*)'s upper neighbor, if *x*'<==<=*x* and *y*'<=><=*y*
We'll consider point (*x*,<=*y*) from the given set supercentral, if it has at least one upper, at least one lower, at least one left and at least one right neighbor among this set's points.
Vasya marked quite many points on the paper. Analyzing the picture manually is rather a challenge, so Vasya asked you to help him. Your task is to find the number of supercentral points in the given set.
|
```python
count = int(input())
points = []
for i in range(count):
point = tuple(input().split())
points.append(point)
answer = 0
for (x, y) in points:
left = False
right = False
up = False
low = False
for (x1, y1) in points:
if x1 > x and y1 == y:
right = True
if x1 < x and y1 == y:
left = True
if x1 == x and y1 > y:
up = True
if x1 == x and y1 < y:
low = True
if left and right and up and low:
answer += 1
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mahmoud and Ehab continue their adventures! As everybody in the evil land knows, Dr. Evil likes bipartite graphs, especially trees.
A tree is a connected acyclic graph. A bipartite graph is a graph, whose vertices can be partitioned into 2 sets in such a way, that for each edge (*u*,<=*v*) that belongs to the graph, *u* and *v* belong to different sets. You can find more formal definitions of a tree and a bipartite graph in the notes section below.
Dr. Evil gave Mahmoud and Ehab a tree consisting of *n* nodes and asked them to add edges to it in such a way, that the graph is still bipartite. Besides, after adding these edges the graph should be simple (doesn't contain loops or multiple edges). What is the maximum number of edges they can add?
A loop is an edge, which connects a node with itself. Graph doesn't contain multiple edges when for each pair of nodes there is no more than one edge between them. A cycle and a loop aren't the same .
|
```python
n = int(input())
g = [[] for i in range(n+1)]
for _ in range(n-1):
u, v = map(int, input().split())
g[u].append(v)
g[v].append(u)
visited = [False for _ in range(n+1)]
def dfs(node, prev):
if prev:
visited[node] = 1
else:
visited[node] = 0
for w in g[node]:
if not visited[w]:
dfs(w, 1 - prev)
dfs(1, 0)
c = [0, 0]
for visit in visited:
if visit == 1:
c[1] += 1
else:
c[0] += 1
print(c[0]*c[1]-n+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In Aramic language words can only represent objects.
Words in Aramic have special properties:
- A word is a root if it does not contain the same letter more than once. - A root and all its permutations represent the same object. - The root $x$ of a word $y$ is the word that contains all letters that appear in $y$ in a way that each letter appears once. For example, the root of "aaaa", "aa", "aaa" is "a", the root of "aabb", "bab", "baabb", "ab" is "ab". - Any word in Aramic represents the same object as its root.
You have an ancient script in Aramic. What is the number of different objects mentioned in the script?
|
```python
d=set()
input()
for i in input().split():
x=set()
for j in i: x.add(j)
d.add(''.join(sorted(x)))
print(len(d))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Not so long ago the Codecraft-17 contest was held on Codeforces. The top 25 participants, and additionally random 25 participants out of those who got into top 500, will receive a Codeforces T-shirt.
Unfortunately, you didn't manage to get into top 25, but you got into top 500, taking place *p*.
Now the elimination round of 8VC Venture Cup 2017 is being held. It has been announced that the Codecraft-17 T-shirt winners will be chosen as follows. Let *s* be the number of points of the winner of the elimination round of 8VC Venture Cup 2017. Then the following pseudocode will be executed:
Here "div" is the integer division operator, "mod" is the modulo (the remainder of division) operator.
As the result of pseudocode execution, 25 integers between 26 and 500, inclusive, will be printed. These will be the numbers of places of the participants who get the Codecraft-17 T-shirts. It is guaranteed that the 25 printed integers will be pairwise distinct for any value of *s*.
You're in the lead of the elimination round of 8VC Venture Cup 2017, having *x* points. You believe that having at least *y* points in the current round will be enough for victory.
To change your final score, you can make any number of successful and unsuccessful hacks. A successful hack brings you 100 points, an unsuccessful one takes 50 points from you. It's difficult to do successful hacks, though.
You want to win the current round and, at the same time, ensure getting a Codecraft-17 T-shirt. What is the smallest number of successful hacks you have to do to achieve that?
|
```python
p, x, y = map(int, input().split())
def shirtpicking(s, test):
i = (s // 50) % 475
res = []
for t in range(25):
i = (i * 96 + 42) % 475
res.append(i+26)
if test in res:
return True
else:
return False
if x >= y:
for x1 in range((x - y) // 50 + 1):
if shirtpicking(x - x1 * 50, p):
print(0)
exit()
ans = 0
s = x
ints = 0
while ans == 0:
s += 50
ints += 1
if shirtpicking(s, p):
print((ints + 1) // 2)
exit()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Free Meteor Association (FMA) has got a problem: as meteors are moving, the Universal Cosmic Descriptive Humorous Program (UCDHP) needs to add a special module that would analyze this movement.
UCDHP stores some secret information about meteors as an *n*<=×<=*m* table with integers in its cells. The order of meteors in the Universe is changing. That's why the main UCDHP module receives the following queries:
- The query to swap two table rows; - The query to swap two table columns; - The query to obtain a secret number in a particular table cell.
As the main UCDHP module is critical, writing the functional of working with the table has been commissioned to you.
|
```python
import sys
input = sys.stdin.readline
n ,m ,k = map(int ,input().split())
row ,col ,Data = [], [],[]
for i in range(n):
row.append(i)
a = list(input().split())
Data.append(a)
for i in range(m):
col.append(i)
for _ in range(k):
s ,x ,y = input().split()
x , y = int(x) ,int(y)
if s == 'g':
print(Data[row[x-1]][col[y-1]])
elif s == 'r':
tmp = row[x-1]
row[x-1] = row[y-1]
row[y-1] = tmp
else :
tmp = col[x-1]
col[x-1] = col[y-1]
col[y-1] = col[x-1]
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.