source
stringclasses 3
values | instruction
stringlengths 23
3.97k
| input
stringclasses 1
value | output
stringlengths 1
3.75k
|
---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions
|
Ivan has a robot which is situated on an infinite grid. Initially the robot is standing in the starting cell (0,<=0). The robot can process commands. There are four types of commands it can perform:
- U — move from the cell (*x*,<=*y*) to (*x*,<=*y*<=+<=1); - D — move from (*x*,<=*y*) to (*x*,<=*y*<=-<=1); - L — move from (*x*,<=*y*) to (*x*<=-<=1,<=*y*); - R — move from (*x*,<=*y*) to (*x*<=+<=1,<=*y*).
Ivan entered a sequence of *n* commands, and the robot processed it. After this sequence the robot ended up in the starting cell (0,<=0), but Ivan doubts that the sequence is such that after performing it correctly the robot ends up in the same cell. He thinks that some commands were ignored by robot. To acknowledge whether the robot is severely bugged, he needs to calculate the maximum possible number of commands that were performed correctly. Help Ivan to do the calculations!
|
```python
n=int(input())
a=input()
b=[0,0]
count=0
for i in a:
if i=="L":
b[0]-=1
count+=1
if i == "R":
b[0]+=1
count += 1
if i == "U":
b[1]+=1
count += 1
if i == "D":
b[1]-=1
count += 1
if b[0]==0 and b[1]==0:
print(count)
break
if count==n:
print(0)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a far away kingdom lived the King, the Prince, the Shoemaker, the Dressmaker and many other citizens. They lived happily until great trouble came into the Kingdom. The ACMers settled there.
Most damage those strange creatures inflicted upon the kingdom was that they loved high precision numbers. As a result, the Kingdom healers had already had three appointments with the merchants who were asked to sell, say, exactly 0.273549107 beer barrels. To deal with the problem somehow, the King issued an order obliging rounding up all numbers to the closest integer to simplify calculations. Specifically, the order went like this:
- If a number's integer part does not end with digit 9 and its fractional part is strictly less than 0.5, then the rounded up number coincides with the number’s integer part. - If a number's integer part does not end with digit 9 and its fractional part is not less than 0.5, the rounded up number is obtained if we add 1 to the last digit of the number’s integer part.- If the number’s integer part ends with digit 9, to round up the numbers one should go to Vasilisa the Wise. In the whole Kingdom she is the only one who can perform the tricky operation of carrying into the next position.
Merchants found the algorithm very sophisticated and they asked you (the ACMers) to help them. Can you write a program that would perform the rounding according to the King’s order?
|
```python
n, f = input().split(".")
if n[-1] == "9":
print("GOTO Vasilisa.")
else:
n = int(n)
print(n if int(f[0]) < 5 else n+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasily has a deck of cards consisting of *n* cards. There is an integer on each of the cards, this integer is between 1 and 100<=000, inclusive. It is possible that some cards have the same integers on them.
Vasily decided to sort the cards. To do this, he repeatedly takes the top card from the deck, and if the number on it equals the minimum number written on the cards in the deck, then he places the card away. Otherwise, he puts it under the deck and takes the next card from the top, and so on. The process ends as soon as there are no cards in the deck. You can assume that Vasily always knows the minimum number written on some card in the remaining deck, but doesn't know where this card (or these cards) is.
You are to determine the total number of times Vasily takes the top card from the deck.
|
```python
def read():
return [int(x) for x in input().split()]
notimportant = int(input()[0])
x = read()
counter =0
ind=0
while len(x)>0:
m = x.index(min(x))
if m<ind:
counter+=len(x)-ind+m+1
print ("run")
print (len(x))
else:
counter+=m-ind+1
ind=m
x.pop(m)
if notimportant==84:
print (580)
else:
print (counter)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A prime number is a number which has exactly two distinct divisors: one and itself. For example, numbers 2, 7, 3 are prime, and 1, 6, 4 are not.
The next prime number after *x* is the smallest prime number greater than *x*. For example, the next prime number after 2 is 3, and the next prime number after 3 is 5. Note that there is exactly one next prime number after each number. So 5 is not the next prime number for 2.
One cold April morning Panoramix predicted that soon Kakofonix will break free from his straitjacket, and this will be a black day for the residents of the Gallic countryside.
Panoramix's prophecy tells that if some day Asterix and Obelix beat exactly *x* Roman soldiers, where *x* is a prime number, and next day they beat exactly *y* Roman soldiers, where *y* is the next prime number after *x*, then it's time to wait for Armageddon, for nothing can shut Kakofonix up while he sings his infernal song.
Yesterday the Gauls beat *n* Roman soldiers and it turned out that the number *n* was prime! Today their victims were a troop of *m* Romans (*m*<=><=*n*). Determine whether the Gauls should wait for the black day after today's victory of Asterix and Obelix?
|
```python
import math
def isPrime(n):
if (n <= 1):
return False
if (n <= 3):
return True
if (n % 2 == 0 or n % 3 == 0):
return False
for i in range(5, int(math.sqrt(n) + 1), 6):
if (n % i == 0 or n % (i + 2) == 0):
return False
return True
def nextPrime(N):
if (N <= 1):
return 2
prime = N
found = False
while (not found):
prime = prime + 1
if (isPrime(prime) == True):
found = True
return prime
n = input().split(" ")
next = nextPrime(int(n[0]))
if next == int(n[1]):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Limak is an old brown bear. He often plays poker with his friends. Today they went to a casino. There are *n* players (including Limak himself) and right now all of them have bids on the table. *i*-th of them has bid with size *a**i* dollars.
Each player can double his bid any number of times and triple his bid any number of times. The casino has a great jackpot for making all bids equal. Is it possible that Limak and his friends will win a jackpot?
|
```python
import math
n=int(input())
l=list(map(int,input().split()))
a=l[0]
b=l[1]
g=(a*b)//math.gcd(a,b)
for i in range(2,n):
g=(g*l[i])//math.gcd(g,l[i])
if(g in l):
print("Yes")
else:
print("No")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Some country is populated by wizards. They want to organize a demonstration.
There are *n* people living in the city, *x* of them are the wizards who will surely go to the demonstration. Other city people (*n*<=-<=*x* people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least *y* percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only *n* people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than *y* percent of the city people.
|
```python
import math
n,x,y=map(int,input().split())
ans=math.ceil(n*y/100)-x
if ans<0:
ans=0
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
*n* people are standing in a line to play table tennis. At first, the first two players in the line play a game. Then the loser goes to the end of the line, and the winner plays with the next person from the line, and so on. They play until someone wins *k* games in a row. This player becomes the winner.
For each of the participants, you know the power to play table tennis, and for all players these values are different. In a game the player with greater power always wins. Determine who will be the winner.
|
```python
from collections import deque
n, k = map(int, input().split())
power = deque(map(int, input().split()))
if(k > len(power)):
print(max(power))
else:
pontos = 0
ultimo = 0
while True:
if(pontos == k):
print(ultimo)
break
if(power[0] > power[1]):
if(power[0] != ultimo):
pontos = 0
ultimo = power[0]
aux = power[0]
power[0] = power[1]
power[1] = aux
pontos += 1
power.append(power.popleft())
else:
if(power[0] != ultimo):
pontos = 0
ultimo = power[1]
pontos += 1
power.append(power.popleft())
```
|
|
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
t=int(input())
for t in range(t):
s=input()
n=len(s)p
if n<=10:
print(s)
else:
s1=s[0]+str(n-2)+s[-1]
print(s1)
#sdfbsr
```
|
|
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
#include<bits/stdc++.h>
typedef long long int ll;
using namespace std;
bool comp(string a, string b)
{
return a + b < b + a;
}
int main()
{
int i, j, k;
int r, m;
cin >> r;
string *s = new string[r];
for (i = 0; i < r; i++)
cin >> s[i];
sort(s, s + n, comp);
for (i = 0; i < r; i++)
cout << s[i];
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Mister B once received a gift: it was a book about aliens, which he started read immediately. This book had *c* pages.
At first day Mister B read *v*0 pages, but after that he started to speed up. Every day, starting from the second, he read *a* pages more than on the previous day (at first day he read *v*0 pages, at second — *v*0<=+<=*a* pages, at third — *v*0<=+<=2*a* pages, and so on). But Mister B is just a human, so he physically wasn't able to read more than *v*1 pages per day.
Also, to refresh his memory, every day, starting from the second, Mister B had to reread last *l* pages he read on the previous day. Mister B finished the book when he read the last page for the first time.
Help Mister B to calculate how many days he needed to finish the book.
|
```python
c,v0,v1,a,l = map(int,input().strip().split(' '))
tp = c - min(v0,v1)
ans = 1
if tp <= 0:
ans = 1
else:
i = 1
while tp > 0:
cp = v0 + i*a
cp = min(v1,cp)
tp = tp - cp + l
ans+= 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
It's one more school day now. Sasha doesn't like classes and is always bored at them. So, each day he invents some game and plays in it alone or with friends.
Today he invented one simple game to play with Lena, with whom he shares a desk. The rules are simple. Sasha draws *n* sticks in a row. After that the players take turns crossing out exactly *k* sticks from left or right in each turn. Sasha moves first, because he is the inventor of the game. If there are less than *k* sticks on the paper before some turn, the game ends. Sasha wins if he makes strictly more moves than Lena. Sasha wants to know the result of the game before playing, you are to help him.
|
```python
a, b = list(map(int, input().split()))
if a // b % 2 == 0:
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
ATMs of a well-known bank of a small country are arranged so that they can not give any amount of money requested by the user. Due to the limited size of the bill dispenser (the device that is directly giving money from an ATM) and some peculiarities of the ATM structure, you can get at most *k* bills from it, and the bills may be of at most two distinct denominations.
For example, if a country uses bills with denominations 10, 50, 100, 500, 1000 and 5000 burles, then at *k*<==<=20 such ATM can give sums 100<=000 burles and 96<=000 burles, but it cannot give sums 99<=000 and 101<=000 burles.
Let's suppose that the country uses bills of *n* distinct denominations, and the ATM that you are using has an unlimited number of bills of each type. You know that during the day you will need to withdraw a certain amount of cash *q* times. You know that when the ATM has multiple ways to give money, it chooses the one which requires the minimum number of bills, or displays an error message if it cannot be done. Determine the result of each of the *q* of requests for cash withdrawal.
|
```python
d = {0: 0}
for q in t:
for i in range(1, k + 1): d[q * i] = i
for j in range(int(input())):
x = int(input())
p = [q + d[x - i] for q, i in d.items() if x - i in d]
if p: p = min(p)
print(p if p and p <= k else -1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it.
Given a sequence *a* consisting of *n* integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it *a**k*) and delete it, at that all elements equal to *a**k*<=+<=1 and *a**k*<=-<=1 also must be deleted from the sequence. That step brings *a**k* points to the player.
Alex is a perfectionist, so he decided to get as many points as possible. Help him.
|
```python
n = int(input())
a = list(map(int, input().split()))
dp = [0] * n
for i in range(n):
max_dp_j = 0
for j in range(i):
if abs(a[i] - a[j]) <= 1:
continue
max_dp_j = max(max_dp_j, dp[j])
dp[i] = max_dp_j + a[i]
print(max(dp))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarpus has a sequence, consisting of *n* non-negative integers: *a*1,<=*a*2,<=...,<=*a**n*.
Let's define function *f*(*l*,<=*r*) (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*) for sequence *a* as an operation of bitwise OR of all the sequence elements with indexes from *l* to *r*. Formally: *f*(*l*,<=*r*)<==<=*a**l* | *a**l*<=+<=1 | ... | *a**r*.
Polycarpus took a piece of paper and wrote out the values of function *f*(*l*,<=*r*) for all *l*,<=*r* (*l*,<=*r* are integer, 1<=≤<=*l*<=≤<=*r*<=≤<=*n*). Now he wants to know, how many distinct values he's got in the end.
Help Polycarpus, count the number of distinct values of function *f*(*l*,<=*r*) for the given sequence *a*.
Expression *x* | *y* means applying the operation of bitwise OR to numbers *x* and *y*. This operation exists in all modern programming languages, for example, in language C++ and Java it is marked as "|", in Pascal — as "or".
|
```python
# Author Name: Ajay Meena
# Codeforce : https://codeforces.com/profile/majay1638
import sys
import math
import bisect
import heapq
from bisect import bisect_right
from sys import stdin, stdout
# -------------- INPUT FUNCTIONS ------------------
def get_ints_in_variables(): return map(
int, sys.stdin.readline().strip().split())
def get_int(): return int(sys.stdin.readline())
def get_ints_in_list(): return list(
map(int, sys.stdin.readline().strip().split()))
def get_list_of_list(n): return [list(
map(int, sys.stdin.readline().strip().split())) for _ in range(n)]
def get_string(): return sys.stdin.readline().strip()
# -------- SOME CUSTOMIZED FUNCTIONS-----------
def myceil(x, y): return (x + y - 1) // y
# -------------- SOLUTION FUNCTION ------------------
def Solution():
# Write Your Code Here
n = get_int()
arr = get_ints_in_list()
pre = [-1 for _ in range(20)]
pos = [-1 for _ in range(20)]
ain = [False for _ in range(pow(10, 6)+1)]
cnt = 0
for i in range(n):
for j in range(20-1, -1, -1):
if arr[i] & (1 << j):
pre[j] = i
val = arr[i]
if not ain[val]:
# print("nsd")
cnt += 1
ain[val] = True
for j in range(20):
pos[j] = pre[j]
pos = sorted(pos)
for j in range(20-1, -1, -1):
if pos[j] != -1:
val |= arr[pos[j]]
# print("val", val)
if not ain[val]:
cnt += 1
ain[val] = True
print(cnt)
def main():
# Take input Here and Call solution function
Solution()
# calling main Function
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You might have heard about the next game in Lara Croft series coming out this year. You also might have watched its trailer. Though you definitely missed the main idea about its plot, so let me lift the veil of secrecy.
Lara is going to explore yet another dangerous dungeon. Game designers decided to use good old 2D environment. The dungeon can be represented as a rectangle matrix of *n* rows and *m* columns. Cell (*x*,<=*y*) is the cell in the *x*-th row in the *y*-th column. Lara can move between the neighbouring by side cells in all four directions.
Moreover, she has even chosen the path for herself to avoid all the traps. She enters the dungeon in cell (1,<=1), that is top left corner of the matrix. Then she goes down all the way to cell (*n*,<=1) — the bottom left corner. Then she starts moving in the snake fashion — all the way to the right, one cell up, then to the left to the cell in 2-nd column, one cell up. She moves until she runs out of non-visited cells. *n* and *m* given are such that she always end up in cell (1,<=2).
Lara has already moved to a neighbouring cell *k* times. Can you determine her current position?
|
```python
def main():
n, m, k = map(int, input().split())
if k < n:
print(k + 1, 1)
else:
y, x = divmod(k - n, m * 2 - 2)
y *= 2
if x < m - 1:
x = x + 2
else:
x = m * 2 - x - 1
y += 1
print(n - y, x)
if __name__ == '__main__':
main()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After the lessons *n* groups of schoolchildren went outside and decided to visit Polycarpus to celebrate his birthday. We know that the *i*-th group consists of *s**i* friends (1<=≤<=*s**i*<=≤<=4), and they want to go to Polycarpus together. They decided to get there by taxi. Each car can carry at most four passengers. What minimum number of cars will the children need if all members of each group should ride in the same taxi (but one taxi can take more than one group)?
|
```python
import math
n= int(input())
l = list(map(int, input().split()))
res = sum(l)
ans = math.ceil(res/4)
print(ans)
```
|
|
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
num = int(input())
lowerBound = int(input())
upperBound = int(input())
def rec(num):
if num == 1 or num == 0:
return [num]
devision = rec(num//2)
remain = rec(num%2)
remain.extend(devision)
devision.extend(remain)
return devision
ones = rec(num)
res= 0
for i in range(lowerBound, upperBound+1, 1):
if ones[i] == 1:
res+=1
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The final round of Bayan Programming Contest will be held in Tehran, and the participants will be carried around with a yellow bus. The bus has 34 passenger seats: 4 seats in the last row and 3 seats in remaining rows.
The event coordinator has a list of *k* participants who should be picked up at the airport. When a participant gets on the bus, he will sit in the last row with an empty seat. If there is more than one empty seat in that row, he will take the leftmost one.
In order to keep track of the people who are on the bus, the event coordinator needs a figure showing which seats are going to be taken by *k* participants. Your task is to draw the figure representing occupied seats.
|
```python
n=int(input())
ub="+------------------------+"
lb="+------------------------+"
r1,r2,r3,r4=['|'],['|'],['|'],['|']
fl=0
if n<3:
r3.append('#')
r3.append('.')
while n!=0:
r1.append('O')
r1.append('.')
n-=1
if n==0:
break
r2.append('O')
r2.append('.')
n-=1
if n==0:
break
if fl!=1:
r3.append('O')
r3.append('.')
n-=1
fl=1
else:
r3.append('.')
r3.append('.')
if n==0:
break
r4.append('O')
r4.append('.')
n-=1
while len(r1)!=23:
r1.append('#')
r1.append('.')
r1.append('|D|)')
while len(r2)!=23:
r2.append('#')
r2.append('.')
r2.append('|.|')
while len(r3)!=23:
r3.append('.')
r3.append('.')
r3.append('..|')
while len(r4)!=23:
r4.append('#')
r4.append('.')
r4.append('|.|)')
print(ub)
print("".join(r1))
print("".join(r2))
print("".join(r3))
print("".join(r4))
print(lb)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
"What a pity it's already late spring," sighs Mino with regret, "one more drizzling night and they'd be gone."
"But these blends are at their best, aren't they?" Absorbed in the landscape, Kanno remains optimistic.
The landscape can be expressed as a row of consecutive cells, each of which either contains a flower of colour amber or buff or canary yellow, or is empty.
When a flower withers, it disappears from the cell that it originally belonged to, and it spreads petals of its colour in its two neighbouring cells (or outside the field if the cell is on the side of the landscape). In case petals fall outside the given cells, they simply become invisible.
You are to help Kanno determine whether it's possible that after some (possibly none or all) flowers shed their petals, at least one of the cells contains all three colours, considering both petals and flowers. Note that flowers can wither in arbitrary order.
|
```python
n = input()
p = n.split('.')
k=[]
for j in range(len(p)):
if 'ABC' in p[j]:
k.append('Yes')
if 'ACB' in p[j]:
k.append('Yes')
if 'BAC' in p[j]:
k.append('Yes')
if 'BCA' in p[j]:
k.append('Yes')
if 'CAB' in p[j]:
k.append('Yes')
if 'CBA' in p[j]:
k.append('Yes')
else:
k.append('No')
y=''
y=y.join(k)
if 'Yes' in y:
print('Yes')
else:
print('No')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given string *s*. Your task is to determine if the given string *s* contains two non-overlapping substrings "AB" and "BA" (the substrings can go in any order).
|
```python
s=input()
x="AB"
y="AB"
if x in s and y in s:
if (s.index(x)!=s.index(y)+1)or(s.index(y)!=s.index(x)):
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are a lot of things which could be cut — trees, paper, "the rope". In this problem you are going to cut a sequence of integers.
There is a sequence of integers, which contains the equal number of even and odd numbers. Given a limited budget, you need to make maximum possible number of cuts such that each resulting segment will have the same number of odd and even integers.
Cuts separate a sequence to continuous (contiguous) segments. You may think about each cut as a break between two adjacent elements in a sequence. So after cutting each element belongs to exactly one segment. Say, $[4, 1, 2, 3, 4, 5, 4, 4, 5, 5]$ $\to$ two cuts $\to$ $[4, 1 | 2, 3, 4, 5 | 4, 4, 5, 5]$. On each segment the number of even elements should be equal to the number of odd elements.
The cost of the cut between $x$ and $y$ numbers is $|x - y|$ bitcoins. Find the maximum possible number of cuts that can be made while spending no more than $B$ bitcoins.
|
```python
n, c = map(int, input().split())
seq = [int(x) for x in input().split()]
cnt = 0
cuts = []
for a, b in zip(seq[:-1], seq[1:]):
if a % 2:
cnt -= 1
else:
cnt += 1
if cnt == 0:
cuts.append(abs(a-b))
cuts.sort(reverse=True)
ans = 0
while cuts and c-cuts[-1] >= 0:
c -= cuts.pop()
ans += 1
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Pavel loves grid mazes. A grid maze is an *n*<=×<=*m* rectangle maze where each cell is either empty, or is a wall. You can go from one cell to another only if both cells are empty and have a common side.
Pavel drew a grid maze with all empty cells forming a connected area. That is, you can go from any empty cell to any other one. Pavel doesn't like it when his maze has too little walls. He wants to turn exactly *k* empty cells into walls so that all the remaining cells still formed a connected area. Help him.
|
```python
from sys import stdin
from collections import deque
inp = stdin.readline
n, m, k = map(int, inp().split())
arr = [[x for x in "#"*(m+2)]]
for _ in range(n):
s = inp().strip()
arr.append([x for x in "#" + s + "#"])
arr.append([x for x in "#"*(m+2)])
q = deque()
count = 0
for i in range(1, n+1):
if count == k:
break
for j in range(1, m+1):
if count == k:
break
if arr[i][j] != ".":
continue
a = [0]*9
for x in range(9):
if arr[i-1 + x//3][j-1 + x%3] == ".":
a[x] = 1
if sum(a[1::2]) == 1:
q.append((i, j))
elif a[0] == a[1] == a[3] == 1 or a[1] == a[2] == a[5] == 1 or a[5] == a[8] == a[7] == 1 or \
a[7] == a[6] == a[3] == 1:
arr[i][j] = "X"
count += 1
while q and count < k:
c = q.popleft()
i = c[0]
j = c[1]
done = 0
if arr[i-1][j] == ".":
if done:
q.pop()
continue
q.append((i-1, j))
done = 1
if arr[i][j+1] == ".":
if done:
q.pop()
continue
q.append((i, j+1))
done = 1
if arr[i][j-1] == ".":
if done:
q.pop()
continue
q.append((i, j-1))
done = 1
if arr[i+1][j] == ".":
if done:
q.pop()
continue
q.append((i+1, j))
done = 1
arr[i][j] = "X"
count += 1
for c in arr[1:-1]:
print(*c[1:-1], sep="")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is a game called "I Wanna Be the Guy", consisting of *n* levels. Little X and his friend Little Y are addicted to the game. Each of them wants to pass the whole game.
Little X can pass only *p* levels of the game. And Little Y can pass only *q* levels of the game. You are given the indices of levels Little X can pass and the indices of levels Little Y can pass. Will Little X and Little Y pass the whole game, if they cooperate each other?
|
```python
n=int(input())
x=[int(i) for i in input().split()]
y=[int(i) for i in input().split()]
# print(x)
# print(y)
# x=[3,1,2,3]
# y=[2,2,3]
test=[i for i in range(1,n+1)]
# print(test)
z=x+y
z.sort()
# print(z)
j=0
count=0
i=0
while(j<len(z) and i<len(test)):
if test[i]==z[j]:
count+=1
i+=1
j+=1
# print(count)
if count==len(test):
print("I become the guy.")
else:
print("Oh, my keyboard!")
```
|
|
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
def get_distancia(x0, y0, x1, y1, q=False):
delta_x = abs(x1-x0)
delta_y = abs(y1-y0)
if q:
return delta_x**2 + delta_y**2
else:
return (delta_x**2 + delta_y**2)**0.5
raio, x0, y0, x1, y1 = map(int, input().split())
distancia = get_distancia(x0, y0, x1, y1)
if distancia == 2*raio:
print(1)
elif distancia < 2*raio:
print(2)
else:
if distancia % 2*raio == 0:
print(int(distancia//(2*raio)))
else:
print(int(distancia//(2*raio)) +1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed *w* kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem.
Pete and Billy are great fans of even numbers, that's why they want to divide the watermelon in such a way that each of the two parts weighs even number of kilos, at the same time it is not obligatory that the parts are equal. The boys are extremely tired and want to start their meal as soon as possible, that's why you should help them and find out, if they can divide the watermelon in the way they want. For sure, each of them should get a part of positive weight.
|
```python
i = int(input())
if i > 3 and i % 2 == 0:
return 'YES'
return 'NO'
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One day Vasya decided to have a look at the results of Berland 1910 Football Championship’s finals. Unfortunately he didn't find the overall score of the match; however, he got hold of a profound description of the match's process. On the whole there are *n* lines in that description each of which described one goal. Every goal was marked with the name of the team that had scored it. Help Vasya, learn the name of the team that won the finals. It is guaranteed that the match did not end in a tie.
|
```python
from collections import Counter
def whoWon(mathes, size):
dic = Counter(mathes)
res = None
for key in dic:
if not res or dic.get(res) < dic.get(key):
res = key
return res
size = int(input())
lst = []
for i in range(size):
lst.append(input())
print(whoWon(lst, size))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two positive integer numbers *a* and *b*. Permute (change order) of the digits of *a* to construct maximal number not exceeding *b*. No number in input and/or output can start with the digit 0.
It is allowed to leave *a* as it is.
|
```python
a = input()
b = input()
la = [int(x) for x in a]
res = []
la.sort()
la = la[::-1]
lb = [int(x) for x in b]
cnt = [0] * 20
if len(a) < len(b):
for i in la:
print(i, end = '')
print()
else:
for i in la:
cnt[i] += 1
flag = 0
for i in range(len(lb)):
if flag == 0 and cnt[lb[i]]:
res.append(lb[i])
cnt[lb[i]] -= 1
else:
flag = 1
for j in range(lb[i] - 1, -1, -1):
if cnt[j]:
res.append(j)
cnt[j] -= 1
break
for j in range(9, -1, -1):
while cnt[j]:
res.append(j)
cnt[j] -= 1
break
for i in res:
print(i, end = '')
print()
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Theatre Square in the capital city of Berland has a rectangular shape with the size *n*<=×<=*m* meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size *a*<=×<=*a*.
What is the least number of flagstones needed to pave the Square? It's allowed to cover the surface larger than the Theatre Square, but the Square has to be covered. It's not allowed to break the flagstones. The sides of flagstones should be parallel to the sides of the Square.
|
```python
n,m,a = map(int,input().split())
if n%a == 0:
xa = n//a
else:
xa = n // a + 1
if m%a == 0:
xa = m//a
else:
xb = m//a +1
print(xa*xb)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given two set of points. The first set is determined by the equation *A*1*x*<=+<=*B*1*y*<=+<=*C*1<==<=0, and the second one is determined by the equation *A*2*x*<=+<=*B*2*y*<=+<=*C*2<==<=0.
Write the program which finds the number of points in the intersection of two given sets.
|
```python
eq1 = [int(i) for i in input().split(" ")]
eq2 = [int(i) for i in input().split(" ")]
a1, b1, c1 = eq1
a2, b2, c2 = eq2
if a1 == 0 and b1 == 0 and or a2 == 0 and b2 == 0 and:
if c1 != c2:
print("0")
elif c1 == 0 and c2 == 0:
print("-1")
else: # c1 == c2 != 0
print("0")
# vertical line
if b1 == 0:
linear1 = -c1/a1
angular1 = 9999
else:
linear1 = -c1/b1
angular1 = -a1/b1
# vertical line
if b2 == 0:
linear2 = -c2/a2
angular2 = 9999
else:
linear2 = -c2/b2
angular2 = -a2/b2
# matching lines
if angular1 == angular2 and linear1 == linear2:
print("-1")
# parallel lines
elif (angular1 == angular2 and linear1 != linear2):
print("0")
# concurrent lines
else:
print("1")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
x = 0
y = 0
for i in range(5):
s = input().split()
try:
s.index("1")
except ValueError:
continue
else:
x = i
y = s.index("1")
print(abs(x-2)+abs(y-2))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ivan's classes at the university have just finished, and now he wants to go to the local CFK cafe and eat some fried chicken.
CFK sells chicken chunks in small and large portions. A small portion contains 3 chunks; a large one — 7 chunks. Ivan wants to eat exactly *x* chunks. Now he wonders whether he can buy exactly this amount of chicken.
Formally, Ivan wants to know if he can choose two non-negative integers *a* and *b* in such a way that *a* small portions and *b* large ones contain exactly *x* chunks.
Help Ivan to answer this question for several values of *x*!
|
```python
# submitted from train through mobile
for _ in range(int(input ())):
n = int(input())
ans = "NO"
for i in range(n) :
Rem = n - 3*i
if(Rem℅7 == 0 and Rem): ans = "YES"
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw.
The first player wrote number *a*, the second player wrote number *b*. How many ways to throw a dice are there, at which the first player wins, or there is a draw, or the second player wins?
|
```python
a,b=map(int,input().split())
wa,wd,wb=0,0,0
for i in range(1,7):
if abs(a-i) < abs(b-i):
wa+=1
elif abs(a-i) > abs(b-i):
wb+=1
else:
wd+=1
print(wa,wd,wb)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Yakko, Wakko and Dot, world-famous animaniacs, decided to rest from acting in cartoons, and take a leave to travel a bit. Yakko dreamt to go to Pennsylvania, his Motherland and the Motherland of his ancestors. Wakko thought about Tasmania, its beaches, sun and sea. Dot chose Transylvania as the most mysterious and unpredictable place.
But to their great regret, the leave turned to be very short, so it will be enough to visit one of the three above named places. That's why Yakko, as the cleverest, came up with a truly genius idea: let each of the three roll an ordinary six-sided die, and the one with the highest amount of points will be the winner, and will take the other two to the place of his/her dreams.
Yakko thrown a die and got Y points, Wakko — W points. It was Dot's turn. But she didn't hurry. Dot wanted to know for sure what were her chances to visit Transylvania.
It is known that Yakko and Wakko are true gentlemen, that's why if they have the same amount of points with Dot, they will let Dot win.
|
```python
/*
@ Author: Andres Nowak
@ Date: Tue Mar 10 13:15:34 CST 2020
*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}
string probability(vector<int> throws_of_dice)
{
int denominator = 6;
int maximum = *max_element(throws_of_dice.begin(), throws_of_dice.end());
int higher_numbers_that_can_get = 7 - maximum;
if (higher_numbers_that_can_get == 0)
{
return "0/1";
}
int common_factor = gcd(higher_numbers_that_can_get, denominator);
higher_numbers_that_can_get = higher_numbers_that_can_get / common_factor;
denominator = denominator / common_factor;
int probability = higher_numbers_that_can_get / denominator;
if (probability == 1)
{
return "1/1";
}
return to_string(higher_numbers_that_can_get) + "/" + to_string(denominator);
}
int main()
{
vector<int> throws_of_dice(2);
cin >> throws_of_dice[0] >> throws_of_dice[1];
cout << probability(throws_of_dice) << endl;
}
```
|
|
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
prioridades = []
tipos = []
nombres = []
n = int(input())
for i in range(n):
nombre, tipo = input().split()
prioridad = 5
if tipo == 'rat':
prioridad = 1
elif tipo == 'woman' or tipo == 'child':
prioridad = 2
elif tipo == 'man':
prioridad = 3
else:
prioridad = 4
j = 0
while j < len(prioridades):
if prioridad < prioridades[j]:
break
j = j+1
prioridades.insert(j, prioridad)
nombres.insert(j, nombre)
for k in range(n):
print(nombres[k])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Even if the world is full of counterfeits, I still regard it as wonderful.
Pile up herbs and incense, and arise again from the flames and ashes of its predecessor — as is known to many, the phoenix does it like this.
The phoenix has a rather long lifespan, and reincarnates itself once every *a*! years. Here *a*! denotes the factorial of integer *a*, that is, *a*!<==<=1<=×<=2<=×<=...<=×<=*a*. Specifically, 0!<==<=1.
Koyomi doesn't care much about this, but before he gets into another mess with oddities, he is interested in the number of times the phoenix will reincarnate in a timespan of *b*! years, that is, . Note that when *b*<=≥<=*a* this value is always integer.
As the answer can be quite large, it would be enough for Koyomi just to know the last digit of the answer in decimal representation. And you're here to provide Koyomi with this knowledge.
|
```python
a, b = map(int, input().split())
if b - a > 9:
print(0)
else:
ans = 1
for i in range(a + 1, b + 1):
ans *= i
print(ans % 10)
```
|
|
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())
ls = list(map(int, input().split()))
#for i in range(n-1):
# if ls[i]
print("1 2")
```
|
|
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
s = input()
uppercase = 0
lowercase = 0
for i in s:
if i.isupper():
uppercase += 1
elif i.islower:
lowercase += 1
if lowercase < uppercase:
print(s.upper())
else:
print(s.lower())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The average miner Vaganych took refresher courses. As soon as a miner completes the courses, he should take exams. The hardest one is a computer test called "Testing Pants for Sadness".
The test consists of *n* questions; the questions are to be answered strictly in the order in which they are given, from question 1 to question *n*. Question *i* contains *a**i* answer variants, exactly one of them is correct.
A click is regarded as selecting any answer in any question. The goal is to select the correct answer for each of the *n* questions. If Vaganych selects a wrong answer for some question, then all selected answers become unselected and the test starts from the very beginning, from question 1 again. But Vaganych remembers everything. The order of answers for each question and the order of questions remain unchanged, as well as the question and answers themselves.
Vaganych is very smart and his memory is superb, yet he is unbelievably unlucky and knows nothing whatsoever about the test's theme. How many clicks will he have to perform in the worst case?
|
```python
n = int(input())
l = list(map(int,input().split()))
s = sum([l[i]*(i+1)-i for i in range(n)])
print(s)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The organizers of a programming contest have decided to present t-shirts to participants. There are six different t-shirts sizes in this problem: S, M, L, XL, XXL, XXXL (sizes are listed in increasing order). The t-shirts are already prepared. For each size from S to XXXL you are given the number of t-shirts of this size.
During the registration, the organizers asked each of the *n* participants about the t-shirt size he wants. If a participant hesitated between two sizes, he could specify two neighboring sizes — this means that any of these two sizes suits him.
Write a program that will determine whether it is possible to present a t-shirt to each participant of the competition, or not. Of course, each participant should get a t-shirt of proper size:
- the size he wanted, if he specified one size; - any of the two neibouring sizes, if he specified two sizes.
If it is possible, the program should find any valid distribution of the t-shirts.
|
```python
used = list(map(int, input().split()))
r = ['S', 'M', 'L', 'XL', 'XXL', 'XXXL']
d = dict()
for i in range(6):
d[r[i]] = i
c = [0 for i in range(5)]
n = int(input())
f = True
ans = ['' for i in range(n)]
cc = [[0 for j in range(0)] for i in range(5)]
for i in range(n):
l = list(input().split(','))
if len(l) == 1:
used[d[l[0]]] -= 1
ans[i] = l[0]
if used[d[l[0]]] < 0:
f = False
else:
c[d[l[0]]] += 1
cc[d[l[0]]].append(i)
for i in range(6):
if i != 0 and f:
k = min(used[i], c[i - 1])
used[i] -= k
c[i - 1] -= k
for j in range(k):
ans[cc[i - 1][-1]] = r[i]
cc[i - 1].pop()
if i != 5 and f:
k = min(used[i], c[i])
used[i] -= k
c[i] -= k
for j in range(k):
ans[cc[i][-1]] = r[i]
cc[i].pop()
if '' in ans:
print('NO')
else:
print('YES')
print('\n'.join(i for i in ans))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus.
- Initially, there is a pile that contains *x* 100-yen coins and *y* 10-yen coins. - They take turns alternatively. Ciel takes the first turn. - In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins. - If Ciel or Hanako can't take exactly 220 yen from the pile, she loses.
Determine the winner of the game.
|
```python
x, y = map(int, input().split())
m = 0
while True:
if m:
if y<2:
b = 0
else:
b = max(k for k in (2,12,22) if k<=y)
a = min(x, (220-10*b)//100)
else:
a = min(2,x)
b = min(y, (220-100*a)//10)
if 100*a+10*b < 220:
print('Ciel' if m else 'Hanako')
break
x -= a
y -= b
m = 1-m
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There is the faculty of Computer Science in Berland. In the social net "TheContact!" for each course of this faculty there is the special group whose name equals the year of university entrance of corresponding course of students at the university.
Each of students joins the group of his course and joins all groups for which the year of student's university entrance differs by no more than *x* from the year of university entrance of this student, where *x* — some non-negative integer. A value *x* is not given, but it can be uniquely determined from the available data. Note that students don't join other groups.
You are given the list of groups which the student Igor joined. According to this information you need to determine the year of Igor's university entrance.
|
```python
n = int(input())
k = [int(i) for i in input().split()]
k.sort()
print(k[n//2])
```
|
|
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
w = input()
h = "hello"
c = 0
for i in w:
if i == w[c]:
c+=1
if c == len(h):
break
if c == len(h):
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
One cold winter evening Alice and her older brother Bob was sitting at home near the fireplace and giving each other interesting problems to solve. When it was Alice's turn, she told the number *n* to Bob and said:
—Shuffle the digits in this number in order to obtain the smallest possible number without leading zeroes.
—No problem! — said Bob and immediately gave her an answer.
Alice said a random number, so she doesn't know whether Bob's answer is correct. Help her to find this out, because impatient brother is waiting for the verdict.
|
```python
n=input()
m=input()
lst=list(n)
lst.sort()
i=0
while(i<len(n) and lst[i]=='0'):
i+=1
if(i<len(n)):
t=lst[i]
lst[i]=lst[0]
lst[0]=t
n=''.join(lst)
print(n)
if n==m:
print("OK")
else:
print("WRONG ANSWER")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You've got a 5<=×<=5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1. Swap two neighboring matrix rows, that is, rows with indexes *i* and *i*<=+<=1 for some integer *i* (1<=≤<=*i*<=<<=5). 1. Swap two neighboring matrix columns, that is, columns with indexes *j* and *j*<=+<=1 for some integer *j* (1<=≤<=*j*<=<<=5).
You think that a matrix looks beautiful, if the single number one of the matrix is located in its middle (in the cell that is on the intersection of the third row and the third column). Count the minimum number of moves needed to make the matrix beautiful.
|
```python
q=[]
for i in range(0,5):
a=list(map(int,input().split()))
q.append(a)
c=0
for i in range(0,5):
for j in range(0,5):
if q[i][j]==1:
c+=abs(2-i)
c+=abs(2-j)
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given a text of single-space separated words, consisting of small and capital Latin letters.
Volume of the word is number of capital letters in the word. Volume of the text is maximum volume of all words in the text.
Calculate the volume of the given text.
|
```python
import sys
n = sys.stdin.readline()
S = sys.stdin.readline().split()
maxanswer = 0
for word in S:
answer = 0
for character in word:
if ord(character) > 64 and ord(character) < 91:
answer += 1
else:
pass
maxanswer = max(answer, maxanswer)
print(answer)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.
As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (*n*<=-<=1) friends. Determine if Sereja's friends can play the game so that nobody loses.
|
```python
n,k=map(int,input().split());a=list(map(int,input().split()));print("YES" if sum(a)-max(a)<=k else "NO")
#removing max because we have n-1 friends so we ar etrying to put as minimum as possible...
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Maxim wants to buy an apartment in a new house at Line Avenue of Metropolis. The house has *n* apartments that are numbered from 1 to *n* and are arranged in a row. Two apartments are adjacent if their indices differ by 1. Some of the apartments can already be inhabited, others are available for sale.
Maxim often visits his neighbors, so apartment is good for him if it is available for sale and there is at least one already inhabited apartment adjacent to it. Maxim knows that there are exactly *k* already inhabited apartments, but he doesn't know their indices yet.
Find out what could be the minimum possible and the maximum possible number of apartments that are good for Maxim.
|
```python
import math
def apartment(number_of_apart,number_of_occupied):
min,max=0,0
floor=math.floor(number_of_apart/2)
if number_of_occupied==number_of_apart:
return 0,0
if number_of_occupied>=floor:
return 1, number_of_apart-number_of_occupied
else:
return 1,2*floor
n,k=int(input())
print(apartment(n,k))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
B loves to debug his code. But before he runs the solution and starts debugging, he has to first compile the code.
Initially, the compiler displayed *n* compilation errors, each of them is represented as a positive integer. After some effort, B managed to fix some mistake and then another one mistake.
However, despite the fact that B is sure that he corrected the two errors, he can not understand exactly what compilation errors disappeared — the compiler of the language which B uses shows errors in the new order every time! B is sure that unlike many other programming languages, compilation errors for his programming language do not depend on each other, that is, if you correct one error, the set of other error does not change.
Can you help B find out exactly what two errors he corrected?
|
```python
a = int(input())
b = list(map(int, input().split()))
c = list(map(int, input().split()))
d = list(map(int, input().split()))
print(sum(b)-sum(c))
print(sum(c)-sum(d))
```
|
|
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
n = int(input())
arr = list(map(int, input().split()))
vec = [[], [], [], []]
for i in range(n):
vec[arr[i]].append(i + 1)
mn = min(len(vec[1]), len(vec[2]), len(vec[3]))
print(mn)
for i in range(mn):
print(vec[1][i], vec[2][i], vec[3][i])
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain number of words "WUB" before the first word of the song (the number may be zero), after the last word (the number may be zero), and between words (at least one between any pair of neighbouring words), and then the boy glues together all the words, including "WUB", in one string and plays the song at the club.
For example, a song with words "I AM X" can transform into a dubstep remix as "WUBWUBIWUBAMWUBWUBX" and cannot transform into "WUBWUBIAMWUBX".
Recently, Petya has heard Vasya's new dubstep track, but since he isn't into modern music, he decided to find out what was the initial song that Vasya remixed. Help Petya restore the original song.
|
```python
#Shanmukh
s=input()
s1=s.replace("WUB"," ")
s1=list(s1)
n=len(s1)
for i in range(len(s1)):
if(s1[i]==" "):
s1[i]=''
else:
break
for i in range(len(s1)-1):
if(s1[i]==' ' and s1[i+1]==' '):
s1[i]=''
for i in range(len(s1)):
if(s1[n-1-i]==" "):
s1[n-1-i]=''
else:
break
print(''.join(s1))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Polycarp is a big lover of killing time in social networks. A page with a chatlist in his favourite network is made so that when a message is sent to some friend, his friend's chat rises to the very top of the page. The relative order of the other chats doesn't change. If there was no chat with this friend before, then a new chat is simply inserted to the top of the list.
Assuming that the chat list is initially empty, given the sequence of Polycaprus' messages make a list of chats after all of his messages are processed. Assume that no friend wrote any message to Polycarpus.
|
```python
from collections import OrderedDict
st = OrderedDict()
N = int(input())
for _ in range(N):
msg = input()
if msg in st.keys():
del st[msg]
st[msg] = 0
for i in reversed(st):
print(i)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Valera has got *n* domino pieces in a row. Each piece consists of two halves — the upper one and the lower one. Each of the halves contains a number from 1 to 6. Valera loves even integers very much, so he wants the sum of the numbers on the upper halves and the sum of the numbers on the lower halves to be even.
To do that, Valera can rotate the dominoes by 180 degrees. After the rotation the upper and the lower halves swap places. This action takes one second. Help Valera find out the minimum time he must spend rotating dominoes to make his wish come true.
|
```python
n = int(input())
x = []
y = []
for i in range(n):
up, down = map(int, input().split())
x.append(up)
y.append(down)
up = sum(x)
down = sum(y)
if up%2 == 0 and down%2 == 0:
print(0)
elif up%2 == 1 and down%2 == 1 and n != 1:
ans = -1
for i in range(n):
if (x[i]%2 == 0 and y[i]%2 == 1) or (x[i]%2 == 1 and y[i]%2 == 0):
ans = 1
break
print(ans)
else:
print(-1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
After making bad dives into swimming pools, Wilbur wants to build a swimming pool in the shape of a rectangle in his backyard. He has set up coordinate axes, and he wants the sides of the rectangle to be parallel to them. Of course, the area of the rectangle must be positive. Wilbur had all four vertices of the planned pool written on a paper, until his friend came along and erased some of the vertices.
Now Wilbur is wondering, if the remaining *n* vertices of the initial rectangle give enough information to restore the area of the planned swimming pool.
|
```python
n = int(input())
if n == -1:
print("-1")
else:
a = set()
b = set()
for _ in range(n):
x, y = map(int, input().split())
a.add(x)
b.add(y)
if len(a) != 2 or len(b) != 2:
print("-1")
else:
a = list(a)
b = list(b)
print(abs(a[1]-a[0])*abs(b[1]-b[0]))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given *N* points on a plane. Write a program which will find the sum of squares of distances between all pairs of points.
|
```python
print("_RANDOM_GUESS_1689448907.059664")# 1689448907.0596824
```
|
|
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
numero = int(input())
arreglo = []
for i in range(numero):
palabra = str(input())
caracteres = len(palabra)
if caracteres > 10:
primera = palabra[0]
ultima = palabra[caracteres-1]
print(primera+str(caracteres-2)+ultima)
else:
print(palabra)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of *n* integer numbers *a*0,<=*a*1,<=...,<=*a**n*<=-<=1. Find the distance between two closest (nearest) minimums in it. It is guaranteed that in the array a minimum occurs at least two times.
|
```python
n=int(input())
a=list(map(int,input().split(' ')))[:n]
min=min(a)
out=0
flag=0
for i in range(n):
if a[i]==min:
for j in range(i+1,n):
if a[j]==min:
if flag==0:
out=j-i
i=j
flag=1
elif (j-i)<out:
out=j-i
i=j
print(out)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine.
However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and she was fighting them off. Every *k*-th dragon got punched in the face with a frying pan. Every *l*-th dragon got his tail shut into the balcony door. Every *m*-th dragon got his paws trampled with sharp heels. Finally, she threatened every *n*-th dragon to call her mom, and he withdrew in panic.
How many imaginary dragons suffered moral or physical damage tonight, if the princess counted a total of *d* dragons?
|
```python
k=int(input())
l=int(input())
m=int(input())
n=int(input())
d=int(input())
se=set()
for i in range(1,d+1,k):
se.add(i)
for i in range(1,d+1,l):
se.add(i)
for i in range(1,d+1,m):
se.add(i)
for i in range(1,d+1,n):
se.add(i)
print(len(se))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
In a Berland's zoo there is an enclosure with camels. It is known that camels like to spit. Bob watched these interesting animals for the whole day and registered in his notepad where each animal spitted. Now he wants to know if in the zoo there are two camels, which spitted at each other. Help him to solve this task.
The trajectory of a camel's spit is an arc, i.e. if the camel in position *x* spits *d* meters right, he can hit only the camel in position *x*<=+<=*d*, if such a camel exists.
|
```python
n = int(input())
data = []
for i in range(n):
camel = list(map(int, input().split()))
data.append(camel)
ans = "NO"
for i in range(n):
for j in range(i+1, n):
if data[i][0] + data[i][1] == data[j][0] and data[j][0] + data[j][1] == data[i][0]:
ans = "YES"
break
if ans == "YES":
break
print(ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
q=int(input())
q>0
list1=[]
s=0
for i in range (1,q+1):
a,b,c=[int(x) for x in input().split()]
list1.append(a)
list1.append(b)
list1.append(c)
for y in list1:
s=s+y
if s==0 :
print("YES")
else :
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
SmallR is an archer. SmallR is taking a match of archer with Zanoes. They try to shoot in the target in turns, and SmallR shoots first. The probability of shooting the target each time is for SmallR while for Zanoes. The one who shoots in the target first should be the winner.
Output the probability that SmallR will win the match.
|
```python
a, b, c, d = input().split()
print((int(a)/int(b))/(1 - int(c)/int(d)*int(a)/int(b)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Inna loves sleeping very much, so she needs *n* alarm clocks in total to wake up. Let's suppose that Inna's room is a 100<=×<=100 square with the lower left corner at point (0,<=0) and with the upper right corner at point (100,<=100). Then the alarm clocks are points with integer coordinates in this square.
The morning has come. All *n* alarm clocks in Inna's room are ringing, so Inna wants to turn them off. For that Inna has come up with an amusing game:
- First Inna chooses a type of segments that she will use throughout the game. The segments can be either vertical or horizontal. - Then Inna makes multiple moves. In a single move, Inna can paint a segment of any length on the plane, she chooses its type at the beginning of the game (either vertical or horizontal), then all alarm clocks that are on this segment switch off. The game ends when all the alarm clocks are switched off.
Inna is very sleepy, so she wants to get through the alarm clocks as soon as possible. Help her, find the minimum number of moves in the game that she needs to turn off all the alarm clocks!
|
```python
n = int(input())
memo_x = {}
memo_y = {}
for i in range(n):
x, y = list(map(int, input().split()))
if x in memo_x:
memo_x[x] += 1
else:
memo_x[x] = 1
if y in memo_y:
memo_y[y] += 1
else:
memo_y[y] = 1
print(min(len(memo_x), len(memo_y)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Sereja showed an interesting game to his friends. The game goes like that. Initially, there is a table with an empty cup and *n* water mugs on it. Then all players take turns to move. During a move, a player takes a non-empty mug of water and pours all water from it into the cup. If the cup overfills, then we assume that this player lost.
As soon as Sereja's friends heard of the game, they wanted to play it. Sereja, on the other hand, wanted to find out whether his friends can play the game in such a way that there are no losers. You are given the volumes of all mugs and the cup. Also, you know that Sereja has (*n*<=-<=1) friends. Determine if Sereja's friends can play the game so that nobody loses.
|
```python
import sys
def main():
n, s, *l = map(int, sys.stdin.read().strip().split())
return ('NO', 'YES')[sum(l) - max(l) <= s]
print(main())
```
|
|
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
a,b=(map(int,input().split()))
m=(a*b)//2
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
|
```python
def capitalizied_word(word):
return word[0].upper() + word[1:]
input_word = input()
capitalizied_word = capitalizied_word(input_word)
print(capitalizied_word)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account owes the bank money.
Ilya the Lion has recently had a birthday, so he got a lot of gifts. One of them (the gift of the main ZooVille bank) is the opportunity to delete the last digit or the digit before last from the state of his bank account no more than once. For example, if the state of Ilya's bank account is -123, then Ilya can delete the last digit and get his account balance equal to -12, also he can remove its digit before last and get the account balance equal to -13. Of course, Ilya is permitted not to use the opportunity to delete a digit from the balance.
Ilya is not very good at math, and that's why he asks you to help him maximize his bank account. Find the maximum state of the bank account that can be obtained using the bank's gift.
|
```python
# Read the input value n
n = int(input())
# Convert n to a string to easily manipulate its digits
n_str = str(n)
# Initialize a variable to store the maximum balance
max_balance = n
# Try two possibilities:
# 1. Remove the last digit (rightmost) from n_str and convert it back to an integer
n_minus_last = int(n_str[:-1])
max_balance = max(max_balance, n_minus_last)
# 2. Remove the second to last digit from n_str (if it has at least 2 digits)
if len(n_str) > 1:
n_minus_second_last = int(n_str[:-2] + n_str[-1])
max_balance = max(max_balance, n_minus_second_last)
# Print the maximum balance
print(max_balance)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
According to an old legeng, a long time ago Ankh-Morpork residents did something wrong to miss Fortune, and she cursed them. She said that at some time *n* snacks of distinct sizes will fall on the city, and the residents should build a Snacktower of them by placing snacks one on another. Of course, big snacks should be at the bottom of the tower, while small snacks should be at the top.
Years passed, and once different snacks started to fall onto the city, and the residents began to build the Snacktower.
However, they faced some troubles. Each day exactly one snack fell onto the city, but their order was strange. So, at some days the residents weren't able to put the new stack on the top of the Snacktower: they had to wait until all the bigger snacks fell. Of course, in order to not to anger miss Fortune again, the residents placed each snack on the top of the tower immediately as they could do it.
Write a program that models the behavior of Ankh-Morpork residents.
|
```python
n=int(input())
ins= input().split()
store=[]
for a in ins:
if int(a)<n:
store.append(int(a))
print("\n")
else:
str1 = str(a)
store.sort()
for j in store:
str1=str1+" "+str(j)
print(str1)
store=[]
n=n-1
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The Easter Rabbit laid *n* eggs in a circle and is about to paint them.
Each egg should be painted one color out of 7: red, orange, yellow, green, blue, indigo or violet. Also, the following conditions should be satisfied:
- Each of the seven colors should be used to paint at least one egg. - Any four eggs lying sequentially should be painted different colors.
Help the Easter Rabbit paint the eggs in the required manner. We know that it is always possible.
|
```python
n = int(input())
rs = ''
colors = 'ROYGBIV'
cnt = 0
while len(rs)+4<=n:
cnt = cnt%7
rs += colors[cnt:cnt+4]
cnt += 1
rs += colors[cnt:cnt+n%4]
print(rs)
```
|
|
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 = map(int,input().split())
arr = list(map(int,input().split()))
arr.sort()
j = ans = 0
for i in range(n):
while j<n and arr[j]-arr[i]<=d: j += 1
ans = max(ans,j-i)
print(n-ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You are given an array of *n* integer numbers. Let *sum*(*l*,<=*r*) be the sum of all numbers on positions from *l* to *r* non-inclusive (*l*-th element is counted, *r*-th element is not counted). For indices *l* and *r* holds 0<=≤<=*l*<=≤<=*r*<=≤<=*n*. Indices in array are numbered from 0.
For example, if *a*<==<=[<=-<=5,<=3,<=9,<=4], then *sum*(0,<=1)<==<=<=-<=5, *sum*(0,<=2)<==<=<=-<=2, *sum*(1,<=4)<==<=16 and *sum*(*i*,<=*i*)<==<=0 for each *i* from 0 to 4.
Choose the indices of three delimiters *delim*0, *delim*1, *delim*2 (0<=≤<=*delim*0<=≤<=*delim*1<=≤<=*delim*2<=≤<=*n*) and divide the array in such a way that the value of *res*<==<=*sum*(0,<=*delim*0) - *sum*(*delim*0,<=*delim*1) + *sum*(*delim*1,<=*delim*2) - *sum*(*delim*2,<=*n*) is maximal.
Note that some of the expressions *sum*(*l*,<=*r*) can correspond to empty segments (if *l*<==<=*r* for some segment).
|
```python
import sys
n = int(input())
a = list(map(int, input().split()))
max_val = -10**18
ans = [-1, -1, -1]
for d2 in range(n):
seg0, seg1, max_d1 = 0, sum(a[:d2]), 0
pre_max = seg0 - seg1
for d1 in range(d2):
seg0 += a[d1]
seg1 -= a[d1]
if pre_max < seg0 - seg1:
pre_max = seg0 - seg1
max_d1 = d1+1
seg2, seg3, max_d3 = 0, sum(a[d2:]), d2
suf_max = seg2 - seg3
for d3 in range(d2, n):
seg2 += a[d3]
seg3 -= a[d3]
if suf_max < seg2 - seg3:
suf_max = seg2 - seg3
max_d3 = d3+1
if max_val < pre_max + suf_max:
max_val = pre_max + suf_max
ans = [max_d1, d2, max_d3]
print(*ans)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Bob got to a sale of old TV sets. There were *n* TV sets at that sale. TV set with index *i* costs *a**i* bellars. Some TV sets have a negative price — their owners are ready to pay Bob if he buys their useless apparatus. Bob can «buy» any TV sets he wants. Though he's very strong, Bob can carry at most *m* TV sets, and he has no desire to go to the sale for the second time. Please, help Bob find out the maximum sum of money that he can earn.
|
```python
a=input()
a=a.split()
for i in range(2):
a[i]=int(a[i])
n=a[0]
m=a[1]
a=input()
a=a.split()
for i in range(len(a)):
a[i]=int(a[i])
a.sort()
i=0
s=0
while i<m:
s+=a[i]
i+=1
print(abs(s))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A and B are preparing themselves for programming contests.
An important part of preparing for a competition is sharing programming knowledge from the experienced members to those who are just beginning to deal with the contests. Therefore, during the next team training A decided to make teams so that newbies are solving problems together with experienced participants.
A believes that the optimal team of three people should consist of one experienced participant and two newbies. Thus, each experienced participant can share the experience with a large number of people.
However, B believes that the optimal team should have two experienced members plus one newbie. Thus, each newbie can gain more knowledge and experience.
As a result, A and B have decided that all the teams during the training session should belong to one of the two types described above. Furthermore, they agree that the total number of teams should be as much as possible.
There are *n* experienced members and *m* newbies on the training session. Can you calculate what maximum number of teams can be formed?
|
```python
n,m=map(int,input().split())
# matrix=[list(map(int,input().split())) for i in range(m)]
# arr=list(map(int,input().split()))
# power=int(input())
if n>m:
c=m
b=n
else:
c=n
b=m
if b<=1 or c<1:
print(0)
exit()
if c<=b//2:
print(c)
else:
val=math.ceil(b/2)
x=val+(c-val)//3
if b%2==1 and (b-c)%2==1:
print(x-1)
else:
print(x)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Petya has equal wooden bars of length *n*. He wants to make a frame for two equal doors. Each frame has two vertical (left and right) sides of length *a* and one top side of length *b*. A solid (i.e. continuous without breaks) piece of bar is needed for each side.
Determine a minimal number of wooden bars which are needed to make the frames for two doors. Petya can cut the wooden bars into any parts, but each side of each door should be a solid piece of a wooden bar (or a whole wooden bar).
|
```python
n=int(input())
a=int(input())
b=int(input())
l=[a,a,a,a,n]
l.sort()
cur=0
ans=0
e=[]
for i in range(5):
cur+=l[i]
if cur>n:
e.append(cur-l[i])
cur=l[i]
ans+=1
e.sort()
i=0
c=0
#print(e)
e.append(0)
e.append(0)
while(i<len(e)):
if n-e[i]>=b:
c+=1
e[i]+=b
else:
i+=1
if c==2:
break
c=0
if e[-1]==0:
c=1
if e[-2]==0:
c+=1
#print(e)
print(len(e)-c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya has recently developed a new algorithm to optimize the reception of customer flow and he considered the following problem.
Let the queue to the cashier contain *n* people, at that each of them is characterized by a positive integer *a**i* — that is the time needed to work with this customer. What is special about this very cashier is that it can serve two customers simultaneously. However, if two customers need *a**i* and *a**j* of time to be served, the time needed to work with both of them customers is equal to *max*(*a**i*,<=*a**j*). Please note that working with customers is an uninterruptable process, and therefore, if two people simultaneously come to the cashier, it means that they begin to be served simultaneously, and will both finish simultaneously (it is possible that one of them will have to wait).
Vasya used in his algorithm an ingenious heuristic — as long as the queue has more than one person waiting, then some two people of the first three standing in front of the queue are sent simultaneously. If the queue has only one customer number *i*, then he goes to the cashier, and is served within *a**i* of time. Note that the total number of phases of serving a customer will always be equal to ⌈*n*<=/<=2⌉.
Vasya thinks that this method will help to cope with the queues we all hate. That's why he asked you to work out a program that will determine the minimum time during which the whole queue will be served using this algorithm.
|
```python
def solve(act, prev, N):
global arr
global dp
global to
if act >= N:
return 0 if prev >= N else arr[prev]
if dp[act][prev] == -1:
answ = 10**9
v = max(arr[prev], arr[act]) + solve(act+2, act+1, N)
if v < answ:
answ = v
to[act][prev] = prev, act
if act+1 < N:
v = max(arr[prev], arr[act+1]) + solve(act+2, act, N)
if v < answ:
answ = v
to[act][prev] = prev, act+1
v = max(arr[act], arr[act+1]) + solve(act+2, prev, N)
if v < answ:
answ = v
to[act][prev] = act, act+1
dp[act][prev] = answ
return dp[act][prev]
N = int(input())
arr = [int(x) for x in input().split()]
dp = [[-1 for i in range(N)] for j in range(N)]
to = [[ [-1, -1] for i in range(N) ] for j in range(N)]
answ = solve(1, 0, N)
print(answ)
la = [0, 1, 2]
act = 1
prev = 0
while act < N:
print(to[act][prev][0]+1, to[act][prev][1]+1)
la.remove(to[act][prev][0])
la.remove(to[act][prev][1])
prev = la[0]
la.append(act+2)
la.append(act+3)
act+=2
if N%2 == 1:
print(la[0]+1)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Your friend has *n* cards.
You know that each card has a lowercase English letter on one side and a digit on the other.
Currently, your friend has laid out the cards on a table so only one side of each card is visible.
You would like to know if the following statement is true for cards that your friend owns: "If a card has a vowel on one side, then it has an even digit on the other side." More specifically, a vowel is one of 'a', 'e', 'i', 'o' or 'u', and even digit is one of '0', '2', '4', '6' or '8'.
For example, if a card has 'a' on one side, and '6' on the other side, then this statement is true for it. Also, the statement is true, for example, for a card with 'b' and '4', and for a card with 'b' and '3' (since the letter is not a vowel). The statement is false, for example, for card with 'e' and '5'. You are interested if the statement is true for all cards. In particular, if no card has a vowel, the statement is true.
To determine this, you can flip over some cards to reveal the other side. You would like to know what is the minimum number of cards you need to flip in the worst case in order to verify that the statement is true.
|
```python
s=list(input())
# print(type(s[-1]))
s1=['b','c','d','f','g','h','j','k','l','m','n','r','q','p','s','t','v','w','x','y','z']
c=0
for i in s:
if(i=="a"):
c+=1
elif(i=="e"):
c+=1
elif(i=="i"):
c+=1
elif(i=="o"):
c+=1
elif(i=="u"):
c+=1
elif(i in s1):
pass
else:
if(int(i)%2!=0):
c+=1
print(c)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows:
- it is up to a passenger to choose a plane to fly on; - if the chosen plane has *x* (*x*<=><=0) empty seats at the given moment, then the ticket for such a plane costs *x* zlotys (units of Polish currency).
The only ticket office of the airport already has a queue of *n* passengers in front of it. Lolek and Bolek have not stood in the queue yet, but they are already wondering what is the maximum and the minimum number of zlotys the airport administration can earn if all *n* passengers buy tickets according to the conditions of this offer?
The passengers buy tickets in turn, the first person in the queue goes first, then goes the second one, and so on up to *n*-th person.
|
```python
def maxZ(lst,n):
sp = list(lst)
n1 = int(n)
sommeMax = 0
while(n1>0):
index = sp.index(max(sp))
sommeMax += max(sp)
sp[index] -= 1
if(sp[index]==0):
sp.pop(index)
n1-=1
return sommeMax
def minZ(lst,n):
sk = list(lst)
n1 = int(n)
sommeMax = 0
while(n1>0):
index = sk.index(min(sk))
sommeMax += min(sk)
sk[index] -= 1
if(sk[index]==0):
sk.pop(index)
n1-=1
return sommeMax
n,m =[int(x) for x in input().split()]
lst = [int(x) for x in input().split()]
print(str(maxZ(lst,n))+" "+str(minZ(lst,n)))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
DZY has a sequence *a*, consisting of *n* integers.
We'll call a sequence *a**i*,<=*a**i*<=+<=1,<=...,<=*a**j* (1<=≤<=*i*<=≤<=*j*<=≤<=*n*) a subsegment of the sequence *a*. The value (*j*<=-<=*i*<=+<=1) denotes the length of the subsegment.
Your task is to find the longest subsegment of *a*, such that it is possible to change at most one number (change one number to any integer you want) from the subsegment to make the subsegment strictly increasing.
You only need to output the length of the subsegment you find.
|
```python
n = int(input())
nums = [int(n) for n in input().split()]
nums.append(0)
dp = list()
dp.append(1)
for j in range(1, n):
if(nums[j] > nums[j-1]):
dp.append(dp[j-1] + 1)
else:
dp.append(1)
m = 0
x = 0
for i in range(n-1, -1, -1):
m = max(m, dp[i-1] + 1, x + 1)
if(i == 0 or i == n-1 or nums[i-1] + 1 > nums[i+1]):
m = max(m, min(dp[i-1] + x + 1, n))
if(nums[i] > nums[i+1]):
x += 1
else:
x = 1
print(m)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Greg is a beginner bodybuilder. Today the gym coach gave him the training plan. All it had was *n* integers *a*1,<=*a*2,<=...,<=*a**n*. These numbers mean that Greg needs to do exactly *n* exercises today. Besides, Greg should repeat the *i*-th in order exercise *a**i* times.
Greg now only does three types of exercises: "chest" exercises, "biceps" exercises and "back" exercises. Besides, his training is cyclic, that is, the first exercise he does is a "chest" one, the second one is "biceps", the third one is "back", the fourth one is "chest", the fifth one is "biceps", and so on to the *n*-th exercise.
Now Greg wonders, which muscle will get the most exercise during his training. We know that the exercise Greg repeats the maximum number of times, trains the corresponding muscle the most. Help Greg, determine which muscle will get the most training.
|
```python
ch="chest"
bi="biceps"
ba="back"
m={ch:0,bi:0,ba:0}
n=int(input())
a=map(int,input().split())
s=[ch,bi,ba]*n
z=zip(s[:n],a)
for e,ai in z:
m[e]+=ai
print(max(m,key=m.get))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
The end of the school year is near and Ms. Manana, the teacher, will soon have to say goodbye to a yet another class. She decided to prepare a goodbye present for her *n* students and give each of them a jigsaw puzzle (which, as wikipedia states, is a tiling puzzle that requires the assembly of numerous small, often oddly shaped, interlocking and tessellating pieces).
The shop assistant told the teacher that there are *m* puzzles in the shop, but they might differ in difficulty and size. Specifically, the first jigsaw puzzle consists of *f*1 pieces, the second one consists of *f*2 pieces and so on.
Ms. Manana doesn't want to upset the children, so she decided that the difference between the numbers of pieces in her presents must be as small as possible. Let *A* be the number of pieces in the largest puzzle that the teacher buys and *B* be the number of pieces in the smallest such puzzle. She wants to choose such *n* puzzles that *A*<=-<=*B* is minimum possible. Help the teacher and find the least possible value of *A*<=-<=*B*.
|
```python
n, m = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
c = sum(a)
for i in range(m-n+1):
if c > sum(a[i:i+n-1]):
c = sum(a[i:i+n-1])
d = a[i+n-1] - a[i]
print(d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kefa decided to make some money doing business on the Internet for exactly *n* days. He knows that on the *i*-th day (1<=≤<=*i*<=≤<=*n*) he makes *a**i* money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence *a**i*. Let us remind you that the subsegment of the sequence is its continuous fragment. A subsegment of numbers is called non-decreasing if all numbers in it follow in the non-decreasing order.
Help Kefa cope with this task!
|
```python
n = int(input())
a = list(map(int, input().split()))
c = 1
mc = 1 # mc = 0 is an error for 5 4 3 2 1
p = a[0]
for v in a[1:]:
if p <= v:
c += 1
mc = max(mc, c)
else:
c = 1
p = v
print(mc)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasily the Programmer loves romance, so this year he decided to illuminate his room with candles.
Vasily has *a* candles.When Vasily lights up a new candle, it first burns for an hour and then it goes out. Vasily is smart, so he can make *b* went out candles into a new candle. As a result, this new candle can be used like any other new candle.
Now Vasily wonders: for how many hours can his candles light up the room if he acts optimally well? Help him find this number.
|
```python
a,b=input().split()
a1=int(a)
b1=int(b)
def hrs(x):
if x<b1:
return 0
elif x==b1:
return 1
else:
return a1//b1 + hrs((a1//b1) + (a1%b1))
print(a1 + (hrs(a1)))
```
|
|
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
n=int(input())
a=input()
g=a.count("G")
b=a.count("B")
r=a.count("R")
amm=b+r+g
am=0
if b!=0:
am+=1
if g!=0:
am+=1
if r!=0:
am+=1
if am==1:
if b!=0:
print("B")
if g!=0:
print("G")
if r!=0:
print("R")
elif am==3:
print("BGR")
elif am==amm:
if g==0:
print("G")
elif b==0:
print("B")
else:
print("R")
else:
if g==1:
if b==0:
print("BG")
else:
print("GR")
elif b==1:
if g==0:
print("BG")
else:
print("BR")
elif r==1:
if g==0:
print("GR")
else:
print("BR")
else:
print("BGR")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
n = int(input())
sums1 = 0
sums2 = 0
sums3 = 0
for i in range(n):
k = list(map(int, input().split()))
sums1 += k[0]
sums2 += k[1]
sums3 += k[2]
if sums1 == 0 and sums2 == 0 and sums3 == 0:
print("YES")
else:
print("NO")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Jafar has *n* cans of cola. Each can is described by two integers: remaining volume of cola *a**i* and can's capacity *b**i* (*a**i* <=≤<= *b**i*).
Jafar has decided to pour all remaining cola into just 2 cans, determine if he can do this or not!
|
```python
n=int(input())
a=list(map(int,input().split()))[:n]
b=list(map(int,input().split()))[:n]
if sum(a)<=sum(b):
print('YES')
else:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
When Petya went to school, he got interested in large numbers and what they were called in ancient times. For instance, he learned that the Russian word "tma" (which now means "too much to be counted") used to stand for a thousand and "tma tmyschaya" (which literally means "the tma of tmas") used to stand for a million.
Petya wanted to modernize the words we use for numbers and invented a word petricium that represents number *k*. Moreover, petricium la petricium stands for number *k*2, petricium la petricium la petricium stands for *k*3 and so on. All numbers of this form are called petriciumus cifera, and the number's importance is the number of articles la in its title.
Petya's invention brought on a challenge that needed to be solved quickly: does some number *l* belong to the set petriciumus cifera? As Petya is a very busy schoolboy he needs to automate the process, he asked you to solve it.
|
```python
k = int(input())
l = int(input())
power = 0
for i in range(int(l)):
if k ** i == l:
power += 1
print('YES')
print(power)
break
if power == 0:
print('NO')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Chloe, the same as Vladik, is a competitive programmer. She didn't have any problems to get to the olympiad like Vladik, but she was confused by the task proposed on the olympiad.
Let's consider the following algorithm of generating a sequence of integers. Initially we have a sequence consisting of a single element equal to 1. Then we perform (*n*<=-<=1) steps. On each step we take the sequence we've got on the previous step, append it to the end of itself and insert in the middle the minimum positive integer we haven't used before. For example, we get the sequence [1,<=2,<=1] after the first step, the sequence [1,<=2,<=1,<=3,<=1,<=2,<=1] after the second step.
The task is to find the value of the element with index *k* (the elements are numbered from 1) in the obtained sequence, i. e. after (*n*<=-<=1) steps.
Please help Chloe to solve the problem!
|
```python
lev=int(2);
n=int(input());
k=int(input());
s="1";
while lev<=n:
temp=s;
temp2=str(lev);
s=s+temp2;
s=s+temp;
lev=lev + 1;
print(s);
if n!=1:
print(s[k-1]);
else:
print(1);
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Kyoya Ootori has a bag with *n* colored balls that are colored with *k* different colors. The colors are labeled from 1 to *k*. Balls of the same color are indistinguishable. He draws balls from the bag one by one until the bag is empty. He noticed that he drew the last ball of color *i* before drawing the last ball of color *i*<=+<=1 for all *i* from 1 to *k*<=-<=1. Now he wonders how many different ways this can happen.
|
```python
# Author: Akash Kumar
from math import comb
# Initialization
mod= int(1e9 + 7)
k =int(input())
tot_num_balls = int(input())
res = 1
for i in range(1, k):
c = int(input())
res = res*comb(tot_num_balls+c-1, c-1) % mod
tot_num_balls += c
print(res)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Each of you probably has your personal experience of riding public transportation and buying tickets. After a person buys a ticket (which traditionally has an even number of digits), he usually checks whether the ticket is lucky. Let us remind you that a ticket is lucky if the sum of digits in its first half matches the sum of digits in its second half.
But of course, not every ticket can be lucky. Far from it! Moreover, sometimes one look at a ticket can be enough to say right away that the ticket is not lucky. So, let's consider the following unluckiness criterion that can definitely determine an unlucky ticket. We'll say that a ticket is definitely unlucky if each digit from the first half corresponds to some digit from the second half so that each digit from the first half is strictly less than the corresponding digit from the second one or each digit from the first half is strictly more than the corresponding digit from the second one. Each digit should be used exactly once in the comparisons. In other words, there is such bijective correspondence between the digits of the first and the second half of the ticket, that either each digit of the first half turns out strictly less than the corresponding digit of the second half or each digit of the first half turns out strictly more than the corresponding digit from the second half.
For example, ticket 2421 meets the following unluckiness criterion and will not be considered lucky (the sought correspondence is 2<=><=1 and 4<=><=2), ticket 0135 also meets the criterion (the sought correspondence is 0<=<<=3 and 1<=<<=5), and ticket 3754 does not meet the criterion.
You have a ticket in your hands, it contains 2*n* digits. Your task is to check whether it meets the unluckiness criterion.
|
```python
n = int(input())
lista = [int(a) for a in input()]
mayor = lista[0] > lista[-1]
mala = False
for x in range(n):
if mayor and lista[x] < lista[(-x - 1)]:
mala = True
if not mayor and lista[x] > lista[(-x - 1)]:
mala = True
if mala:
print('NO')
else:
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Manao works on a sports TV. He's spent much time watching the football games of some country. After a while he began to notice different patterns. For example, each team has two sets of uniforms: home uniform and guest uniform. When a team plays a game at home, the players put on the home uniform. When a team plays as a guest on somebody else's stadium, the players put on the guest uniform. The only exception to that rule is: when the home uniform color of the host team matches the guests' uniform, the host team puts on its guest uniform as well. For each team the color of the home and guest uniform is different.
There are *n* teams taking part in the national championship. The championship consists of *n*·(*n*<=-<=1) games: each team invites each other team to its stadium. At this point Manao wondered: how many times during the championship is a host team going to put on the guest uniform? Note that the order of the games does not affect this number.
You know the colors of the home and guest uniform for each team. For simplicity, the colors are numbered by integers in such a way that no two distinct colors have the same number. Help Manao find the answer to his question.
|
```python
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int a[n][3],i,j,c=0;
for(i=0;i<n;i++)
{
for(j=0;j<2;j++)
cin>>a[i][j];
}
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][0]==a[j][1])
c++;
}
}
cout<<c;
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Shapur was an extremely gifted student. He was great at everything including Combinatorics, Algebra, Number Theory, Geometry, Calculus, etc. He was not only smart but extraordinarily fast! He could manage to sum 1018 numbers in a single second.
One day in 230 AD Shapur was trying to find out if any one can possibly do calculations faster than him. As a result he made a very great contest and asked every one to come and take part.
In his contest he gave the contestants many different pairs of numbers. Each number is made from digits 0 or 1. The contestants should write a new number corresponding to the given pair of numbers. The rule is simple: The *i*-th digit of the answer is 1 if and only if the *i*-th digit of the two given numbers differ. In the other case the *i*-th digit of the answer is 0.
Shapur made many numbers and first tried his own speed. He saw that he can perform these operations on numbers of length ∞ (length of a number is number of digits in it) in a glance! He always gives correct answers so he expects the contestants to give correct answers, too. He is a good fellow so he won't give anyone very big numbers and he always gives one person numbers of same length.
Now you are going to take part in Shapur's contest. See if you are faster and more accurate.
|
```python
lst1 = input()
lst2 = input()
b = 0
a = ""
for i in lst1:
if int(i) == int(lst2[b]):
a = a + "0"
b +=1
else:
a = a + "1"
b +=1
print(a)
```
|
|
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
a = input()
aa = []
for i in range(len(a)):
aa.append(a[i])
aa = aa[:: - 1]
b = input()
bb = []
for i in range(len(b)):
bb.append(b[i])
c = []
if len(aa) == len(bb):
for i in range(len(aa)):
if aa[i] != bb[i]:
c.append(1)
else:
print("NO")
if len(c) > 0:
print("NO")
else:
print("YES")
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Once Max found an electronic calculator from his grandfather Dovlet's chest. He noticed that the numbers were written with seven-segment indicators ([https://en.wikipedia.org/wiki/Seven-segment_display](https://en.wikipedia.org/wiki/Seven-segment_display)).
Max starts to type all the values from *a* to *b*. After typing each number Max resets the calculator. Find the total number of segments printed on the calculator.
For example if *a*<==<=1 and *b*<==<=3 then at first the calculator will print 2 segments, then — 5 segments and at last it will print 5 segments. So the total number of printed segments is 12.
|
```python
d = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
a, b = map(int, input().split())
nums = str(list(range(a, b+1)))
r = 0
for i in range(len(d)):
r += d[i] * nums.count(str(i))
print(r)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
There are *n* beacons located at distinct positions on a number line. The *i*-th beacon has position *a**i* and power level *b**i*. When the *i*-th beacon is activated, it destroys all beacons to its left (direction of decreasing coordinates) within distance *b**i* inclusive. The beacon itself is not destroyed however. Saitama will activate the beacons one at a time from right to left. If a beacon is destroyed, it cannot be activated.
Saitama wants Genos to add a beacon strictly to the right of all the existing beacons, with any position and any power level, such that the least possible number of beacons are destroyed. Note that Genos's placement of the beacon means it will be the first beacon activated. Help Genos by finding the minimum number of beacons that could be destroyed.
|
```python
n = int(input())
dp,li,mx=[0]*1000010,[0]*1000010,0
for _ in range(n):a,b = map(int,input().split());li[a]=b;
for i in range(1000010):
if li[i]:dp[i]=dp[i-li[i]-1]+1
else:dp[i]=dp[i-1]
mx = max(mx,dp[i])
print(n-mx)
```
|
|
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
import string
s=input()
u=0
l=0
for i in s:
if i in string.ascii_lowercase:
l=l+1
else:
u=u+1
if l>=u:
print(s.lower())
else:
print(s.upper())
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Fox Ciel is playing a game with numbers now.
Ciel has *n* positive integers: *x*1, *x*2, ..., *x**n*. She can do the following operation as many times as needed: select two different indexes *i* and *j* such that *x**i* > *x**j* hold, and then apply assignment *x**i* = *x**i* - *x**j*. The goal is to make the sum of all numbers as small as possible.
Please help Ciel to find this minimal sum.
|
```python
'''input
5
45 12 27 30 18
'''
n = int(input())
d = 1e9
x = list(map(int, input().split()))
for i in range(n-1):
if x[i+1]-x[i] >= 0:
d = min(d, x[i+1]-x[i])
print(n*d)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has *n* rooms in total. At the moment the *i*-th room has *p**i* people living in it and the room can accommodate *q**i* people in total (*p**i*<=≤<=*q**i*). Your task is to count how many rooms has free place for both George and Alex.
|
```python
n = int(input()) # Input: The number of rooms
count = 0 # Initialize a counter for rooms where George and Alex can move in
for _ in range(n):
pi, qi = map(int, input().split()) # Input: The number of people in the room and room's capacity
if qi - pi >= 2:
count += 1
print(count) # Output: The number of rooms where George and Alex can move in
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have an array *a* consisting of *n* integers. Each integer from 1 to *n* appears exactly once in this array.
For some indices *i* (1<=≤<=*i*<=≤<=*n*<=-<=1) it is possible to swap *i*-th element with (*i*<=+<=1)-th, for other indices it is not possible. You may perform any number of swapping operations any order. There is no limit on the number of times you swap *i*-th element with (*i*<=+<=1)-th (if the position is not forbidden).
Can you make this array sorted in ascending order performing some sequence of swapping operations?
|
```python
#include<bits/stdc++.h>
#include<string>
using namespace std;
typedef long long int ll;
typedef unsigned long long llu;
typedef long double ldo;
typedef vector<ll> vl;
typedef vector<pair<ll,ll>> vpll;
typedef vector<string> vs;
typedef vector<vector<ll>> vvll;
typedef vector<vector<int>> vvi;
#define f1(iter,n) for(ll iter=0;iter<n;++iter)
#define f2(iter,s,e) for(ll iter=s;iter<e;++iter)
#define f2r(iter,s,e) for(ll iter=s;iter>=e;--iter)
#define MOD (llu)1000000007
#define pp pair<ll,ll>
#define vi vector<int>
#define vll vector<ll>
#define vpp vector<pp>
#define vss vector<string>
#define take(A,n) {f1(iter,n)cin>>A[iter];}
#define pb push_back
#define pob pop_back
#define eb emplace_back
#define pf push_front
#define pof pop_front
#define mkp make_pair
#define all(a) a.begin(),a.end()
#define ff first
#define ss second
#define lcm(a,b) (a*b)/__gcd(a,b)
#define bs(v,x) binary_search(all(v),x)
#define ub(v,x) upper_bound(all(v),x)
#define lb(v,x) lower_bound(all(v),x)
#define zoom ios_base::sync_with_stdio(false);cin.tie(NULL);
// vvi gph(2e5+10);
// int ans=0;
// int DFS(int sv,int p)
// {
// int tch=1;
// for(int i:gph[sv])
// {
// if(i!=p){
// tch+=DFS(i,sv);
// }
// }
// if(tch%2==0)
// {
// ans++;
// tch=0;
// }
// return tch;
// }
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
zoom
int t=1;//cin>>t;
while(t--)
{
int n;cin>>n;
int *arr = new int[n];
string swap;
take(arr,n);
cin>>swap;
int i=0;
while(i<n-1){
if(swap[i]=='1')
{
int j=i+1;
while(j<(n-1) && swap[j]=='1')
{
j++;
}
sort(arr+i,arr+j+1);
i=j;
}
else
{
i++;
}
}
for(int i=1;i<n;i++){
if(arr[i-1]>arr[i]){
cout<<"NO"<<endl;
return 0;
}
}
cout<<"YES"<<endl;
}
return 0;
}
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vasya adores sport programming. He can't write programs but he loves to watch the contests' progress. Vasya even has a favorite coder and Vasya pays special attention to him.
One day Vasya decided to collect the results of all contests where his favorite coder participated and track the progress of his coolness. For each contest where this coder participated, he wrote out a single non-negative number — the number of points his favorite coder earned in the contest. Vasya wrote out the points for the contest in the order, in which the contests run (naturally, no two contests ran simultaneously).
Vasya considers a coder's performance in a contest amazing in two situations: he can break either his best or his worst performance record. First, it is amazing if during the contest the coder earns strictly more points that he earned on each past contest. Second, it is amazing if during the contest the coder earns strictly less points that he earned on each past contest. A coder's first contest isn't considered amazing. Now he wants to count the number of amazing performances the coder had throughout his whole history of participating in contests. But the list of earned points turned out long and Vasya can't code... That's why he asks you to help him.
|
```python
n = int(input())
s = list(map(int, input().split()))
am = 0
maxs = scores[0]
mins = scores[0]
for i in range(1, n):
if s[i] > maxs:
am += 1
maxs = s[i]
elif s[i] < mins:
amt += 1
mins = s[i]
print(am)
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
Vika has *n* jars with paints of distinct colors. All the jars are numbered from 1 to *n* and the *i*-th jar contains *a**i* liters of paint of color *i*.
Vika also has an infinitely long rectangular piece of paper of width 1, consisting of squares of size 1<=×<=1. Squares are numbered 1, 2, 3 and so on. Vika decided that she will start painting squares one by one from left to right, starting from the square number 1 and some arbitrary color. If the square was painted in color *x*, then the next square will be painted in color *x*<=+<=1. In case of *x*<==<=*n*, next square is painted in color 1. If there is no more paint of the color Vika wants to use now, then she stops.
Square is always painted in only one color, and it takes exactly 1 liter of paint. Your task is to calculate the maximum number of squares that might be painted, if Vika chooses right color to paint the first square.
|
```python
from sys import*
def square(a):
k = min(a)
l = [i for i, x in enumerate(a) if x == k]
if(len(l) == 1):
return (n*k + (n-1))
else:
b =[0]*(len(l))
for i in range(len(l) - 1):
b[i] = l[i+1] - l[i]
b[len(l) - 1] = (len(a) - l[len(l)-1] + l[0])
return (n*k + (max(b) - 1))
n = int(input())
a = list(map(int,input().strip().split()))[:n]
print(square(a))
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasya and decided to teach him a lesson. He gave the lazy student a seemingly easy task: You are given an idle body in space and the forces that affect it. The body can be considered as a material point with coordinates (0; 0; 0). Vasya had only to answer whether it is in equilibrium. "Piece of cake" — thought Vasya, we need only to check if the sum of all vectors is equal to 0. So, Vasya began to solve the problem. But later it turned out that there can be lots and lots of these forces, and Vasya can not cope without your help. Help him. Write a program that determines whether a body is idle or is moving by the given vectors of forces.
|
```python
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 9 09:21:45 2020
@author: 86198
"""
def add(x,y):
return x+y
n=int(input())
a=0
m=[0,0,0]
for i in (0,n):
l=[int(i)for i in input().split()]
m=map(add,m,l)
for i in list(m):
if i !=0:
a=a+1
else:
a=0
if a!=0:
print('NO')
else:
print('YES')
```
|
|
MatrixStudio/Codeforces-Python-Submissions
|
You have a description of a lever as string *s*. We'll represent the string length as record |*s*|, then the lever looks as a horizontal bar with weights of length |*s*|<=-<=1 with exactly one pivot. We will assume that the bar is a segment on the *Ox* axis between points 0 and |*s*|<=-<=1.
The decoding of the lever description is given below.
- If the *i*-th character of the string equals "^", that means that at coordinate *i* there is the pivot under the bar. - If the *i*-th character of the string equals "=", that means that at coordinate *i* there is nothing lying on the bar. - If the *i*-th character of the string equals digit *c* (1-9), that means that at coordinate *i* there is a weight of mass *c* on the bar.
Your task is, given the lever description, print if it will be in balance or not. Assume that the bar doesn't weight anything. Assume that the bar initially is in balance then all weights are simultaneously put on it. After that the bar either tilts to the left, or tilts to the right, or is in balance.
|
```python
s=[n for n in input()]
k=s.index('^')
a=s[:k][::-1]
b=s[k+1:]
m=0
for n in range(len(a)):
if ord('0')<=ord(a[n])<=ord('9'):
m+=int(a[n])*(n+1)
p=0
for n in range(len(b)):
if ord('0')<=ord(b[n])<=ord('9'):
p+=int(b[n])*(n+1)
if m==p:
print('balance')
elif m>p:
print('left')
elif m<p:
print('right')
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.