source stringclasses 3
values | instruction stringlengths 23 3.97k | input stringclasses 1
value | output stringlengths 1 3.75k |
|---|---|---|---|
MatrixStudio/Codeforces-Python-Submissions | Is it rated?
Here it is. The Ultimate Question of Competitive Programming, Codeforces, and Everything. And you are here to answer it.
Another Codeforces round has been conducted. No two participants have the same number of points. For each participant, from the top to the bottom of the standings, their rating before ... | ```python
n=int(input())
l=0
r=0
ll=[]
ll1=[]
for i in range(n):
a=input().split(" ")
l+=int(a[0])
r+=int(a[1])
ll.append(list(map(int,a)))
ll1=list(ll)
flag=0
if(l!=r):
print("rated")
else:
ll.sort(reverse=True)
for j in range(n):
#print(ll[j],ll1[j])
... | |
MatrixStudio/Codeforces-Python-Submissions | One day Vasya painted a Cartesian coordinate system on a piece of paper and marked some set of points (*x*1,<=*y*1),<=(*x*2,<=*y*2),<=...,<=(*x**n*,<=*y**n*). Let's define neighbors for some fixed point from the given set (*x*,<=*y*):
- point (*x*',<=*y*') is (*x*,<=*y*)'s right neighbor, if *x*'<=><=*x* and *y*'... | ```python
def process(A):
d_x = {}
d_y = {}
for x,y in A:
if x not in d_x:
d_x[x] = [y, y]
else:
d_x[x][0] = min(d_x[x][0], y)
d_x[x][1] = max(d_x[x][1], y)
if y not in d_y:
d_y[y] = [x, x]
else:
d_y[y][0... | |
MatrixStudio/Codeforces-Python-Submissions | Vasiliy likes to rest after a hard work, so you may often meet him in some bar nearby. As all programmers do, he loves the famous drink "Beecola", which can be bought in *n* different shops in the city. It's known that the price of one bottle in the shop *i* is equal to *x**i* coins.
Vasiliy plans to buy his favorite ... | ```python
from bisect import *
N = int(input())
a = sorted(list(map(int, input().split())))
Q = int(input())
for _ in range(Q):
budget = int(input())
print(bisect_right(a, budget))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves football very much. One day, as he was watching a football match, he was writing the players' current positions on a piece of paper. To simplify the situation he depicted it as a string consisting of zeroes and ones. A zero corresponds to players of one team; a one corresponds to players of another team. If... | ```python
players = input()
if "1" * 7 in players or "0" * 7 in players:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | A Ministry for Defense sent a general to inspect the Super Secret Military Squad under the command of the Colonel SuperDuper. Having learned the news, the colonel ordered to all *n* squad soldiers to line up on the parade ground.
By the military charter the soldiers should stand in the order of non-increasing of their... | ```python
import sys
num = int(sys.stdin.readline().strip())
lst = sys.stdin.readline().strip().split()
# print(lst)
lst1 = map(int, lst)
mp = list(lst1)
# print(mp)
maxi = max(mp)
mini = min(mp)
# print(maxi)
# print(mini)
maxi_inx = []
mini_inx = []
for i in range(len(mp)):
if mp[i] == maxi:
... | |
MatrixStudio/Codeforces-Python-Submissions | There are *n* students living in the campus. Every morning all students wake up at the same time and go to wash. There are *m* rooms with wash basins. The *i*-th of these rooms contains *a**i* wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selecte... | ```python
import functools,math,itertools,time
u=functools.lru_cache(maxsize=None)
n,m=map(int,input().split())
s=[*map(int,input().split())]
t=u(lambda x:1 if x<2 else x*t(x-1))
c=u(lambda r,n:t(n)/t(r)/t(n-r))
p=u(lambda n,k:n**k)
w=u(lambda n,k:math.ceil(n/k))
r=u(lambda k,n:max(k,n))
h=u(lambda i,j,l:c(l,i)*p(j-1,i... | |
MatrixStudio/Codeforces-Python-Submissions | Johnny has a younger sister Anne, who is very clever and smart. As she came home from the kindergarten, she told his brother about the task that her kindergartener asked her to solve. The task was just to construct a triangle out of four sticks of different colours. Naturally, one of the sticks is extra. It is not allo... | ```python
l=list(map(int,input().split()))
l.sort(reverse=True)
a=l[0]
b=l[1]
c=l[2]
d=l[3]
if(b+c>a or b+d>a or c+d>a or c+d>b):
print("TRIANGLE")
elif(b+c==a or b+d==a or c+d==a or c+d==b):
print("SEGMENT")
else:
print("IMPOSSIBLE")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Allen has a LOT of money. He has $n$ dollars in the bank. For security reasons, he wants to withdraw it in cash (we will not disclose the reasons here). The denominations for dollar bills are $1$, $5$, $10$, $20$, $100$. What is the minimum number of bills Allen could receive after withdrawing his entire balance? | ```python
# https://codeforces.com/problemset/problem/996/A
def main():
n = int(input())
sum = 0
bills = [100, 20, 10, 5, 1]
for i in bills:
sum += n // i
n %= i
print(sum)
if __name__ == "__main__":
main()
``` | |
MatrixStudio/Codeforces-Python-Submissions | There is a fence in front of Polycarpus's home. The fence consists of *n* planks of the same width which go one after another from left to right. The height of the *i*-th plank is *h**i* meters, distinct planks can have distinct heights.
Polycarpus has bought a posh piano and is thinking about how to get it into the h... | ```python
planksAmount, k = map(int, input().split())
planksHeight = list(map(int, input().split()))
planksHeight.sort()
if len(planksAmount) == 1:
print(1)
else:
print(sum(planksHeight[:k]))
``` | |
MatrixStudio/Codeforces-Python-Submissions | All cities of Lineland are located on the *Ox* coordinate axis. Thus, each city is associated with its position *x**i* — a coordinate on the *Ox* axis. No two cities are located at a single point.
Lineland residents love to send letters to each other. A person may send a letter only if the recipient lives in another c... | ```python
n = int(input()) # number of cities
x = list(map(int, input().split())) # list of city coordinates
mini = [0]*n
maxi = [0]*n
# calculate mini values
for i in range(n):
if i == 0:
mini[i] = x[1] - x[0]
elif i == n-1:
mini[i] = x[n-1] - x[n-2]
else:
mini[i] = m... | |
MatrixStudio/Codeforces-Python-Submissions | Nikolay has *a* lemons, *b* apples and *c* pears. He decided to cook a compote. According to the recipe the fruits should be in the ratio 1:<=2:<=4. It means that for each lemon in the compote should be exactly 2 apples and exactly 4 pears. You can't crumble up, break up or cut these fruits into pieces. These fruits — ... | ```python
a = int(input())
b = int(input())
c = int(input())
if (b < 2*a):
# Constraint is b, rather than a
if (c < 2*b):
# Constraint is c, not a or b
a = c//4
b = 2*a
c = 2*b
else:
# c >= 2b, so constraint is b, not a or c
a = b//2
... | |
MatrixStudio/Codeforces-Python-Submissions | Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes acco... | ```python
a = int(input())
b = int(input())
b, a = max(a, b), min(a, b)
if (b - a) % 2 == 0:
print((1 + (b - a) // 2) * (b - a) // 2)
else:
print((1 + (b - a + 1) // 2) * ((b - a + 1) // 2) // 2 + (1 + (b - a - 1) // 2) * ((b - a - 1) // 2) // 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 th... | ```python
n=input()
c=0
for i in n:
if i.isupper():
c=c+1
if c>len(n)//2:
n=n.upper()
else:
n=n.lower()
print(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Polycarpus has a ribbon, its length is *n*. He wants to cut the ribbon in a way that fulfils the following two conditions:
- After the cutting each ribbon piece should have length *a*, *b* or *c*. - After the cutting the number of ribbon pieces should be maximum.
Help Polycarpus and find the number of ribbon piece... | ```python
# https://codeforces.com/problemset/problem/189/A
from functools import lru_cache
import sys
sys.setrecursionlimit(4000)
def helper() -> int:
n, a, b, c = [int(s) for s in input().split(" ")]
a, b, c = sorted([a, b, c])
dp = [0] * n
dp[-a] = 1
dp[-b] = 1
dp[-c] = 1
for i in ran... | |
MatrixStudio/Codeforces-Python-Submissions | Sean is trying to save a large file to a USB flash drive. He has *n* USB flash drives with capacities equal to *a*1,<=*a*2,<=...,<=*a**n* megabytes. The file size is equal to *m* megabytes.
Find the minimum number of USB flash drives needed to write Sean's file, if he can split the file between drives. | ```python
n = int(input())
file_size = int(input())
flash_size = [int(input()) for i in range(n)]
flash_size.sort(reverse=True)
i = 0
s = 0
while i < n:
s += flash_size[i]
i += 1
if s >= file_size:
break
print(i)
``` | |
MatrixStudio/Codeforces-Python-Submissions | ZS the Coder and Chris the Baboon are travelling to Udayland! To get there, they have to get on the special IOI bus. The IOI bus has *n* rows of seats. There are 4 seats in each row, and the seats are separated into pairs by a walkway. When ZS and Chris came, some places in the bus was already occupied.
ZS and Chris a... | ```python
n=int(input())
li_st=[]
for i in range(0,n-1):
m=input()
li_st.append(m)
ans = "NO"
for i in range(0,n-1):
m = li_st[i]
if ans=="NO":
for j in range(0,4):
if m[j]==m[j+1] and m[j]=='O':
m=m.replace("OO","++")
ans = "YES"
... | |
MatrixStudio/Codeforces-Python-Submissions | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ... | ```python
s=input()
t=s.split()
n=int(t[0])
h=int(t[1])
s=input()
t=s.split()
w=0
for i in t:
if int(i)>h:
w+=2
else:
w+=1
print(w)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Gennady is one of the best child dentists in Berland. Today *n* children got an appointment with him, they lined up in front of his office.
All children love to cry loudly at the reception at the dentist. We enumerate the children with integers from 1 to *n* in the order they go in the line. Every child is associated ... | ```python
n = int(input())
list_child = []
list_output = []
for i in range(n):
s = [int(j) for j in input().split()]
list_child.append([s[0],s[1],s[2],i+1])
t = 0
while t < n:
if list_child[t][2] >= 0:
for i in range(list_child[t][0]):
if t+i < n-1:
list_child[... | |
MatrixStudio/Codeforces-Python-Submissions | Eugeny has array *a*<==<=*a*1,<=*a*2,<=...,<=*a**n*, consisting of *n* integers. Each integer *a**i* equals to -1, or to 1. Also, he has *m* queries:
- Query number *i* is given as a pair of integers *l**i*, *r**i* (1<=≤<=*l**i*<=≤<=*r**i*<=≤<=*n*). - The response to the query will be integer 1, if the elements of a... | ```python
n , m = map(int,input().split())
arr = input().split()
x = arr.count('1')
y = n - x
ans = ''
for j in range(m):
l , r = map(int,input().split())
if (r - l + 1) % 2 == 0 and min(x , y) >= (r - l + 1)//2 :
ans += '1\n'
else:
ans += '0\n'
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Small, but very brave, mouse Brain was not accepted to summer school of young villains. He was upset and decided to postpone his plans of taking over the world, but to become a photographer instead.
As you may know, the coolest photos are on the film (because you can specify the hashtag #film for such).
Brain took a ... | ```python
#!/usr/bin/env python3
# coding:utf-8
if __name__ == "__main__":
n, m = [int(item) for item in input().split()]
for i in n:
arr = input().split()
if "C" in arr or "Y" in arr or "M" in arr:
print("#Color")
exit(0)
print("#Black&White")
``` | |
MatrixStudio/Codeforces-Python-Submissions | After a hard day Vitaly got very hungry and he wants to eat his favorite potato pie. But it's not that simple. Vitaly is in the first room of the house with *n* room located in a line and numbered starting from one from left to right. You can go from the first room to the second room, from the second room to the third ... | ```python
n = int(input())
p = []
a = list(input())
sum = 0
for i in range(len(a)):
if i % 2 == 0:
p.append((chr(ord(a[i]) - 32)))
else:
if a[i] in p:
p.remove(a[i])
else:
sum += 1
print(sum)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A + B is often used as an example of the easiest problem possible to show some contest platform. However, some scientists have observed that sometimes this problem is not so easy to get accepted. Want to try? | ```python
a, b = map(int,input().split(" "))
print(str(a+b))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Iahub isn't well prepared on geometry problems, but he heard that this year there will be a lot of geometry problems on the IOI selection camp. Scared, Iahub locked himself in the basement and started thinking of new problems of this kind. One of them is the following.
Iahub wants to draw *n* distinct points and *m* s... | ```python
#input
n,m=map(int,input().split())
xlist=[int(x) for x in input().split()]
for i in range(m):
segment=[int(x) for x in input().split()]
#variables
color=''
#main
for i in range(n):
if i%2==0:
color+='0 '
else:
color+='1 '
print(color)
``` | |
MatrixStudio/Codeforces-Python-Submissions | One foggy Stockholm morning, Karlsson decided to snack on some jam in his friend Lillebror Svantenson's house. Fortunately for Karlsson, there wasn't anybody in his friend's house. Karlsson was not going to be hungry any longer, so he decided to get some food in the house.
Karlsson's gaze immediately fell on *n* woode... | ```python
from sys import stdin,stdout
from math import gcd,sqrt,floor,ceil
# Fast I/O
input = stdin.readline
print = stdout.write
def list_inp(x):return list(map(x,input().split()))
def map_inp(x):return map(x,input().split())
def lcm(a,b): return (a*b)/gcd(a,b)
def solve(x):
return x[len(x)//2]-x[(len(x)-1)//2... | |
MatrixStudio/Codeforces-Python-Submissions | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits.... | ```python
import sys, threading
import math
from math import log2,floor
import heapq
from collections import defaultdict,deque
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr(... | |
MatrixStudio/Codeforces-Python-Submissions | Petya and Vasya are playing a game. Petya's got *n* non-transparent glasses, standing in a row. The glasses' positions are indexed with integers from 1 to *n* from left to right. Note that the positions are indexed but the glasses are not.
First Petya puts a marble under the glass in position *s*. Then he performs som... | ```python
#B. Find Marble
n,s,t = map(int,input().split())
p = list(map(int,input().split()))
a = list(range(1,n+1))
m = a[s-1]
x = 0
if s == t:
print(0)
else:
while True:
tmp = [0]*n
for i in range(n):
tmp[p[i]-1] = a[i]
x += 1
if tmp[t-1] == m:
... | |
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... | ```python
from sys import stdin
from collections import Counter,defaultdict,deque
import sys
import math
import os
import operator
import random
from fractions import Fraction
import functools
import bisect
import itertools
from heapq import *
import copy
ans = []
for _ in range(int(input())):
ans.append(input())... | |
MatrixStudio/Codeforces-Python-Submissions | Natasha is going to fly to Mars. She needs to build a rocket, which consists of several stages in some order. Each of the stages is defined by a lowercase Latin letter. This way, the rocket can be described by the string — concatenation of letters, which correspond to the stages.
There are $n$ stages available. The ro... | ```python
import sys
import math
def scan(input_type='int'):
return list(map(int, sys.stdin.readline().strip().split()))
def solution():
# for _ in range(int(input())):
n, k = scan()
s = input()
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',... | |
MatrixStudio/Codeforces-Python-Submissions | In the popular spreadsheets systems (for example, in Excel) the following numeration of columns is used. The first column has number A, the second — number B, etc. till column 26 that is marked by Z. Then there are two-letter numbers: column 27 has number AA, 28 — AB, column 52 is marked by AZ. After ZZ there follow th... | ```python
t = int(input())
l = []
for i in range(t):
m = input()
l.append(m)
for i in range(len(l) , 0 , -1):
print(l[i-1])
``` | |
MatrixStudio/Codeforces-Python-Submissions | One day *n* cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1). Also each cell determined it's favourite number. On it's move *i*-th cell can exchange it's value with the value of some other *j*-th cell, if |*i*<=-<=*j*|<... | ```python
from __future__ import division
from sys import stdin, stdout
from queue import PriorityQueue
from heapq import *
from collections import deque, defaultdict, Counter
from bitarray import bitarray
input_int = lambda: int(stdin.readline())
input_1D_int = lambda: [int(x) for x in stdin.readline().split()]... | |
MatrixStudio/Codeforces-Python-Submissions | wHAT DO WE NEED cAPS LOCK FOR?
Caps lock is a computer keyboard key. Pressing it sets an input mode in which typed letters are capital by default. If it is pressed by accident, it leads to accidents like the one we had in the first passage.
Let's consider that a word has been typed with the Caps lock key accidentall... | ```python
s = input()
s1 = ''
if s.isupper():
s1 += s[0]
s= s[1:].lower()
s1 += s
print(s1)
elif s[0] >= 'a' and s[0] <= 'z':
s1 += s[0]
s1 = s1.upper()
if s[1:].isupper():
s = s[1:].lower()
s1 += s
print(s1)
else:
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Two friends are on the coordinate axis *Ox* in points with integer coordinates. One of them is in the point *x*1<==<=*a*, another one is in the point *x*2<==<=*b*.
Each of the friends can move by one along the line in any direction unlimited number of times. When a friend moves, the tiredness of a friend changes acco... | ```python
a = int(input())
b = int(input())
c = abs(a - b)
ans = 0
for i in range(c // 2 + 1):
ans += 2 * i
if c % 2 == 1:
ans += i + 1
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | DZY loves collecting special strings which only contain lowercase letters. For each lowercase letter *c* DZY knows its value *w**c*. For each special string *s*<==<=*s*1*s*2... *s*|*s*| (|*s*| is the length of the string) he represents its value with a function *f*(*s*), where
Now DZY has a string *s*. He wants to in... | ```python
n = input()
k = int(input())
a = list(map(int , input().split()))
s = 0
for i in range(len(n)):
s+=(a[ord(n[i])-97])*(i+1)
x = max(a)
j = len(n)+1
for i in range(k):
s+=j*x
j+=1
print(s)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Caisa solved the problem with the sugar and now he is on the way back to home.
Caisa is playing a mobile game during his path. There are (*n*<=+<=1) pylons numbered from 0 to *n* in this game. The pylon with number 0 has zero height, the pylon with number *i* (*i*<=><=0) has height *h**i*. The goal of the game is ... | ```python
def ii(): return int(input())
def mi(): return map(int,input().split())
def li(): return list(mi())
def main():
n=ii()
v=li()
c=0
ans=v[0]
for i in range(0,n-1):
c+=v[i]-v[i+1]
if(c<=0):
ans+=(-c)
c=0
print(ans)
if __n... | |
MatrixStudio/Codeforces-Python-Submissions | Let's call a number *k*-good if it contains all digits not exceeding *k* (0,<=...,<=*k*). You've got a number *k* and an array *a* containing *n* numbers. Find out how many *k*-good numbers are in *a* (count each number every time it occurs in array *a*). | ```python
n,k=map(int,input().split())
c=0
for i in range (n):
a = input()
m = 0
for j in range (k+7):
if str(j) in a:
m = m+1
if m == k+1:
c=c+1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given a rectangular cake, represented as an *r*<=×<=*c* grid. Each cell either has an evil strawberry, or is empty. For example, a 3<=×<=4 cake may look as follows:
The cakeminator is going to eat the cake! Each time he eats, he chooses a row or a column that does not contain any evil strawberries and contains... | ```python
r, c = map(int, input().split())
cake = []
cc = [True for i in range(c)]
cr = [True for i in range(r)]
t = 0
for i in range(r):
cake.append(input())
for row in range(r):
for col in range(c):
if cake[row][col] == 'S':
cc[col] = False
cr[row] = False
for i in range(r):... | |
MatrixStudio/Codeforces-Python-Submissions | Calculate the minimum number of characters you need to change in the string *s*, so that it contains at least *k* different letters, or print that it is impossible.
String *s* consists only of lowercase Latin letters, and it is allowed to change characters only to lowercase Latin letters too. | ```python
a = input()
b = int(input())
if len(a) >= b and b - len(set(list(a))) <= 0 and len(set(list(a))) < 26:
if b - len(set(list(a))) > 0:
print(b - len(set(list(a))))
else:
print(0)
else:
print("impossible")
``` | |
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 set... | ```python
n,m=map(int,input().split())
li=list(map(int,input().split()))
li.sort()
t=0
for x in range(m):
if li[x]<0:
t+=-li[x]
else:
t-=li[x]
print(t)
``` | |
MatrixStudio/Codeforces-Python-Submissions | An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a... | ```python
from collections import defaultdict
def main():
n, m = map(int, input().split())
matrix = []
for i in range(n):
matrix.append(input())
row_freq = defaultdict(dict)
col_freq = defaultdict(dict)
for i in range(... | |
MatrixStudio/Codeforces-Python-Submissions | So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | ```python
s1 = input()
s2 = input()
s3 = input()
s11 = s1+s2
def checking(s1,s2):
count1 = {}
count2 = {}
for char in s1:
count1[char] = count1.get(char,0) + 1
for char in s2:
count2[char] = count2.get(char,0) +1
if count2 == count1:
print('YES')
else:
... | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya has a number consisting of *n* digits without leading zeroes. He represented it as an array of... | ```python
n,k = map(int,input().split())
arr = list(input())
while k>0:
flag=True
for i in range(n-1):
if arr[i]=='4' and arr[i+1]=='7':
if (i+1)%2==1:
arr[i]='4'
arr[i+1]='4'
else:
arr[i]='7'
... | |
MatrixStudio/Codeforces-Python-Submissions | Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of *n* bits. These bits are numbered from 1 to *n*. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored... | ```python
n = int(input())
c = input()[::-1]
nc = format(int(c, 2)+1, f"0{len(c)}b")[::-1]
o = 0
print(nc)
for cb, ncb in zip(c, nc):
if cb != ncb:
o += 1
print(o)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vanya and his friends are walking along the fence of height *h* and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed *h*. If the height of some person is greater than *h* he can bend down and then he surely won't be noticed by the guard. The height ... | ```python
a,b=map(int,input().split())
c=list(map(int,input().split()))
l=0
for i in range(a):
if b>=c[i]:
l=l+1
else:
l=l+(c[i]//b)
print(l)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Dima and his friends have been playing hide and seek at Dima's place all night. As a result, Dima's place got messy. In the morning they decided that they need to clean the place.
To decide who exactly would clean the apartment, the friends want to play a counting-out game. First, all the guys stand in a circle, and t... | ```python
n = int(input())
l = [int(i) for i in input().split()]
total = n+1
s = sum(l)
ans = 0
for i in range(5):
s+=1
if(s%(n+1)==1):
pass
else:
ans+=1
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | A newspaper is published in Walrusland. Its heading is *s*1, it consists of lowercase Latin letters. Fangy the little walrus wants to buy several such newspapers, cut out their headings, glue them one to another in order to get one big string. After that walrus erase several letters from this string in order to get a n... | ```python
from math import *
from sys import stdin, stdout, setrecursionlimit
from bisect import *
from collections import *
input = lambda: stdin.readline().strip()
print = stdout.write
s1=input()
s2=input()
al=defaultdict(list)
count=1;index=0;count=0
for i in range(len(s1)):
al[s1[i]].append(i)
... | |
MatrixStudio/Codeforces-Python-Submissions | "QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth.
Now Diamond has given Bort a string consisting of only uppercase English letters of length *n*. There is a great number of "QAQ" in the string (Diamond is so cute!).
Bort wants to know how many subsequences "QAQ" are... | ```python
import math
cnt=0
st=""
from itertools import combinations
def powerset(string):
global cnt
for i in range(0,len(string)+1):
for element in combinations(string,i):
if(''.join(element)=="QAQ"):
cnt+=1
def powerSet(arr, n) :
global cnt
global st
... | |
MatrixStudio/Codeforces-Python-Submissions | There will be a launch of a new, powerful and unusual collider very soon, which located along a straight line. *n* particles will be launched inside it. All of them are located in a straight line and there can not be two or more particles located in the same point. The coordinates of the particles coincide with the dis... | ```python
# Author : //- kibrom Hailu -\\
from sys import stdin,stdout
from collections import Counter,defaultdict , deque
from bisect import bisect , bisect_left ,bisect_right
from itertools import accumulate
from heapq import heapify , heappop , heappush , heappushpop , heapreplace
def I(): return int(s... | |
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 th... | ```python
word = list(str(input()))
count_caps = 0
for letter in word:
if letter.upper() == letter:
count_caps += 1
if count_caps > len(word) - count_caps:
for i in range(len(word)):
char = word[i].upper()
word[i] = char
else:
for i in range(len(word)):
char = ... | |
MatrixStudio/Codeforces-Python-Submissions | Luke Skywalker gave Chewbacca an integer number *x*. Chewbacca isn't good at numbers but he loves inverting digits in them. Inverting digit *t* means replacing it with digit 9<=-<=*t*.
Help Chewbacca to transform the initial number *x* to the minimum possible positive number by inverting some (possibly, zero) digits.... | ```python
n=int(input())
res=0
arr=[int(x) for x in str(n)]
for i in range(0,len(arr)-1):
if(i==0 and arr[i]==9):
continue
elif(arr[i]>=5):
arr[i]=9-arr[i]
for i in range(0,len(arr)):
res=res+(10**(len(arr)-1-i))*arr[i]
print(res)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given an array *a*1,<=*a*2,<=...,<=*a**n* consisting of *n* integers, and an integer *k*. You have to split the array into exactly *k* non-empty subsegments. You'll then compute the minimum integer on each subsegment, and take the maximum integer over the *k* obtained minimums. What is the maximum possible inte... | ```python
n,k=map(int,input().split())
ip=list(map(int,input().split()))
a=max(ip)
b=min(ip)
if k==1:
print(b)
elif k>2:
print(a)
else:
if ip[0]==a or ip[-1]==a:
print(a)
else:
if ip[0]>ip[-1]:
print(max(ip[0], min(ip[1:])))
else:
print(max(ip[-1], min(ip[... | |
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.
... | ```python
n = int(input())
a = 0
m = []
for i in range(n):
x, d = map(int, input().split())
a = x + d
m.append(a)
if m.count(d) == True:
print('YES')
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set *S*:
- its elements were distinct integers from 1 to *limit*; - the value of wa... | ```python
s,t = map(int,input().split())
c = {}
for i in range(1,t+1):
l = 0
tmp = i
while tmp%2==0:
tmp /= 2
l += 1
if l in c:
c[l] += 1
else:
c[l] = 1
b = bin(s)[2:][::-1]
used = {}
for i in range(len(b)):
if b[i] == '1':
if i in c a... | |
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, ... | ```python
s = input()
check = False
while s.count("h") > 1:
s = s.replace("h", "",1)
while s.count("h") == 1:
for i in s:
if i == "h":
a , b = s.split(i)
s = b
if s[0] == "e":
while s.count("e") > 1:
s = s.replace("e", "... | |
MatrixStudio/Codeforces-Python-Submissions | The last stage of Football World Cup is played using the play-off system.
There are *n* teams left in this stage, they are enumerated from 1 to *n*. Several rounds are held, in each round the remaining teams are sorted in the order of their ids, then the first in this order plays with the second, the third — with the ... | ```python
n, a, b = map(int, input().split())
ans = 0
a -= 1
b -= 1
while n > 2:
n //= 2
a //= 2
b //= 2
ans += 1
if a == b:
print(ans)
break
else:
print("Final!")
``` | |
MatrixStudio/Codeforces-Python-Submissions | It is lunch time for Mole. His friend, Marmot, prepared him a nice game for lunch.
Marmot brought Mole *n* ordered piles of worms such that *i*-th pile contains *a**i* worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to *a*1, worms in second pile are labeled w... | ```python
def solucion(num_W, label_j_W):
lista_int = []
valor = 0
lista_2 = []
for i in range(len(num_W)):
lista_int.append(valor+num_W[i])
valor += num_W[i]
label_j_W_2 = sorted(label_j_W)
for i in range(len(label_j_W_2)):
contador = lista_int[0]
for j... | |
MatrixStudio/Codeforces-Python-Submissions | Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
No... | ```python
n,m=map(int,input().split())
x=list(map(int,input().split()))
if n in x:
print("NO")
else:
for i in range(1,len(x)):
if x[i]-x[i-1]>3:
print("NO")
break
else:
print("YES")
``` | |
MatrixStudio/Codeforces-Python-Submissions | Two positive integers *a* and *b* have a sum of *s* and a bitwise XOR of *x*. How many possible values are there for the ordered pair (*a*,<=*b*)? | ```python
for _ in range(1):
add,xor_n=map(int,input().split())
if add < xor_n:
print(0)
continue
d=add-xor_n
if d % 2==1:
print(0)
continue
d//=2
xor=bin(xor_n).replace("0b","")
sub=0
if xor_n & d==0:
if add==xor_n:
sub=2... | |
MatrixStudio/Codeforces-Python-Submissions | An African crossword is a rectangular table *n*<=×<=*m* in size. Each cell of the table contains exactly one letter. This table (it is also referred to as grid) contains some encrypted word that needs to be decoded.
To solve the crossword you should cross out all repeated letters in rows and columns. In other words, a... | ```python
n,m=map(int,input().split()) ; arr=[]
for i in range(n):
x=input()
arr.append(x)
for h in range(n):
for i in range(m):
c=0
let=arr[h][i]
if let.isalpha():
for j in range(h+1,n):
if arr[j][i]==let:
arr[j]=arr[j].repl... | |
MatrixStudio/Codeforces-Python-Submissions | The winner of the card game popular in Berland "Berlogging" is determined according to the following rules. If at the end of the game there is only one player with the maximum number of points, he is the winner. The situation becomes more difficult if the number of such players is more than one. During each round a pla... | ```python
import sys
def parse_line(line):
line = line.strip().split()
name = line[0]
score = int(line[1])
return name, score
def update_scores(name, score, scores, winner):
if name not in scores:
scores[name] = score
else:
scores[name] += score
if winner =... | |
MatrixStudio/Codeforces-Python-Submissions | Lenny is playing a game on a 3<=×<=3 grid of lights. In the beginning of the game all lights are switched on. Pressing any of the lights will toggle it and all side-adjacent lights. The goal of the game is to switch all the lights off. We consider the toggling as follows: if the light was switched on then it will be sw... | ```python
n = int(input())
def dd(n):
if len(str(n)) != len(set(list(str(n)))):
return False
else:
return True
n += 1
while not dd(n):
n += 1
print(n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two arrays *A* and *B* consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose *k* numbers in array *A* and choose *m* numbers in array *B* so that any number chosen in the first array is strictly less than any number chosen in the second array. | ```python
from sys import stdin
_input = stdin.readline
_int = int
count, cnt = [_int(i) for i in _input().split()]
k, m = [_int(i) for i in _input().split()]
a = [_int(i) for i in _input().split()]
b = [_int(i) for i in _input().split()]
a = a[k-1]
b = b[cnt - m]
if a < b:
print('YES')
else:
print(... | |
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 od... | ```python
n,m=map(int,input().split())
f=list(map(int,input().split()))
f.sort()
least=f[n-1]-f[0]
for i in range(1,m-n+1):
dif=f[i+n-1]-f[i]
if dif<least:
least=dif
print(least)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Imp likes his plush toy a lot.
Recently, he found a machine that can clone plush toys. Imp knows that if he applies the machine to an original toy, he additionally gets one more original toy and one copy, and if he applies the machine to a copied toy, he gets two additional copies.
Initially, Imp has only one origina... | ```python
# -*- coding:utf-8 -*-
if __name__ == '__main__':
x, y = map(int, input().split())
def get_res(x, y):
if y < 0:
return "No"
r = x - y + 1
if r < 0:
return "No"
if r % 2 != 0:
return "No"
return "Yes"
print(get_res(x... | |
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 t... | ```python
n,m=map(int,input().split())
ans=m-n
sum=0
if n==2 and m==3:
print('YES')
else:
for i in range(1,m+1):
if m%i==0:
sum+=1
if sum>2:
print('NO')
else:
if ans==2 or ans==4:
print('YES')
else:
print('NO')
``` | |
MatrixStudio/Codeforces-Python-Submissions | The HR manager was disappointed again. The last applicant failed the interview the same way as 24 previous ones. "Do I give such a hard task?" — the HR manager thought. "Just raise number 5 to the power of *n* and get last two digits of the number. Yes, of course, *n* can be rather big, and one cannot find the power us... | ```python
a=input()
b=5**int(a)
lasttwodigit=b%100
print(lasttwodigit)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya and Vasya are brothers. Today is a special day for them as their parents left them home alone and commissioned them to do *n* chores. Each chore is characterized by a single parameter — its complexity. The complexity of the *i*-th chore equals *h**i*.
As Petya is older, he wants to take the chores with complexit... | ```python
# Wadea #
n,a,b=map(int ,input().split())
arr=list(map(int ,input().split()))
arr.sort()
k=arr[b-1]
g=arr[b]
print(int(abs(k-g)))
``` | |
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 ... | ```python
N,M = input().split()
print(int(N)*int(M)//2)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya, or Mr. Vasily Petrov is a dean of a department in a local university. After the winter exams he got his hands on a group's gradebook.
Overall the group has *n* students. They received marks for *m* subjects. Each student got a mark from 1 to 9 (inclusive) for each subject.
Let's consider a student the best at ... | ```python
n,m = map(int,input().split())
ll = []
l = [0] * m
for i in range(n):
ll.append(input().strip())
for j in range(m):
l[j] = max(l[j],int(ll[-1][j]))
ans = 0
for i in ll:
for j in range(m):
if int(i[j]) == l[j]:
ans += 1
break
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | So, the New Year holidays are over. Santa Claus and his colleagues can take a rest and have guests at last. When two "New Year and Christmas Men" meet, thear assistants cut out of cardboard the letters from the guest's name and the host's name in honor of this event. Then the hung the letters above the main entrance. O... | ```python
a=input()
a=list(a)
b=input()
b=list(b)
c=input()
l=list(c)
for i in a:
if i in l:
l.remove(i)
a.remove(i)
for i in b:
if i in l:
l.remove(i)
b.remove(i)
print('YES' if len(l)==0 and len(a)==0 and len(b)==0 else 'NO')
``` | |
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 set... | ```python
# -*- coding: utf-8 -*-
"""Codeforce
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1vkqd1IDYYeIi4VIH6yqQEhbS4qcGMzLO
"""
n , m = map(int , input().split())
tv_price = list(map(int , input().split()))
tv_price = sorted(tv_price)
earning = ... | |
MatrixStudio/Codeforces-Python-Submissions | Being a programmer, you like arrays a lot. For your birthday, your friends have given you an array *a* consisting of *n* distinct integers.
Unfortunately, the size of *a* is too small. You want a bigger array! Your friends agree to give you a bigger array, but only if you are able to answer the following question corr... | ```python
n=int(input())
A=input().split()
N={}
for x in range(n):
N[int(A[x])]=x
M=sorted(N.items())
P=[]
Q=[]
for x in range(n):
if x!=M[x][1]:
P.append(M[x][1])
Q.append(x)
if P==sorted(Q, reverse=True):
print('yes')
else:
print('no')
``` | |
MatrixStudio/Codeforces-Python-Submissions | Little boy Petya loves stairs very much. But he is bored from simple going up and down them — he loves jumping over several stairs at a time. As he stands on some stair, he can either jump to the next one or jump over one or two stairs at a time. But some stairs are too dirty and Petya doesn't want to step on them.
No... | ```python
n, m=map (int, input ().split ())
l=[]
if m>0:
k=list(map (int, input ().split ()))
l=k
if (1 in l) or (n in l):
print ('NO')
elif m==0:
print ('YES' )
else:
l.sort()
flag =0
for i in range(m-2):
if l[i+1]-l[i] ==1 and l[i+2]-l[i+1] ==1:
flag=1
break
if flag ==1:
print ('N... | |
MatrixStudio/Codeforces-Python-Submissions | Ted has a pineapple. This pineapple is able to bark like a bulldog! At time *t* (in seconds) it barks for the first time. Then every *s* seconds after it, it barks twice with 1 second interval. Thus it barks at times *t*, *t*<=+<=*s*, *t*<=+<=*s*<=+<=1, *t*<=+<=2*s*, *t*<=+<=2*s*<=+<=1, etc.
Barney woke up in the morn... | ```python
t,s,x=map(int,input().split())
i=1
while i<x:
if t==x or t+s==x or t+s+1==x or t+(i*s)==x or t+(i*s)+1)==x:
print("YES")
else:
print("NO")
i=i+1
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petr wants to make a calendar for current month. For this purpose he draws a table in which columns correspond to weeks (a week is seven consequent days from Monday to Sunday), rows correspond to weekdays, and cells contain dates. For example, a calendar for January 2017 should look like on the picture:
Petr wants to ... | ```python
m, d = map(int, input().split())
lst = [4,6,9,11]
lst1 = [1,3,5,7,8,10,12]
lst2 = [2]
if m in lst:
if d == 7:
print(6)
else:
print(5)
elif m in lst1:
if d >= 6:
print(6)
else:
print(5)
elif m in lst2:
if d == 1:
print(4)
else:
print(5)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Olga came to visit the twins Anna and Maria and saw that they have many cookies. The cookies are distributed into bags. As there are many cookies, Olga decided that it's no big deal if she steals a bag. However, she doesn't want the sisters to quarrel because of nothing when they divide the cookies. That's why Olga wan... | ```python
n=int(input())
a=list(map(int,input().split()))
k=sum(a)%2
c=0
for i in range(n):
if a[i]%2==k:
c+=1
print(c)
``` | |
MatrixStudio/Codeforces-Python-Submissions | As it's the first of April, Heidi is suspecting that the news she reads today are fake, and she does not want to look silly in front of all the contestants. She knows that a newspiece is fake if it contains heidi as a subsequence. Help Heidi assess whether the given piece is true, but please be discreet about it... | ```python
x = input()
if ("h" in x):
if ("e" in x):
if ("i" in x):
if ("d" in x):
if ("i" in x):
print ("YES")
else:
print ("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | The following problem is well-known: given integers *n* and *m*, calculate
where 2*n*<==<=2·2·...·2 (*n* factors), and denotes the remainder of division of *x* by *y*.
You are asked to solve the "reverse" problem. Given integers *n* and *m*, calculate | ```python
n = int(input())
m = int(input())
if m == 1:
print(1)
else:
x = str(bin(m))
print(int(x[-n:],2))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Vasya plays the sleuth with his friends. The rules of the game are as follows: those who play for the first time, that is Vasya is the sleuth, he should investigate a "crime" and find out what is happening. He can ask any questions whatsoever that can be answered with "Yes" or "No". All the rest agree beforehand to ans... | ```python
s = input()
c = len(s)-1
if (s[c].isalpha()):
if (s[c].upper()=='A' or s[c].upper()=='E' or s[c].upper()=='I' or s[c].upper()=='O' or s[c].upper()=='U' or s[c].upper()=='Y'):
print("YES")
exit()
else:
print("NO")
exit()
else:
if (s[c-1].upper()=='A' or s[c-1].upper()=='E' or s[c-1].upp... | |
MatrixStudio/Codeforces-Python-Submissions | Winnie-the-Pooh likes honey very much! That is why he decided to visit his friends. Winnie has got three best friends: Rabbit, Owl and Eeyore, each of them lives in his own house. There are winding paths between each pair of houses. The length of a path between Rabbit's and Owl's houses is *a* meters, between Rabbit's ... | ```python
from sys import stdin, stdout
from functools import reduce
def main():
n=int(stdin.readline().strip())-1
a=int(stdin.readline().strip())
b=int(stdin.readline().strip())
c=int(stdin.readline().strip())
if n<=0: return 0
x=min(a, min(b, c))
if x==a or x==b: return x*n
... | |
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 e... | ```python
n = int(input())
a = [int(x) for x in input().split()]
ans = 0
mn = mx = a[0]
for x in a:
if x > mx:
ans += 1
mx = x
if x < mn:
ans += 1
mn = x
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | The Saratov State University Olympiad Programmers Training Center (SSU OPTC) has *n* students. For each student you know the number of times he/she has participated in the ACM ICPC world programming championship. According to the ACM ICPC rules, each person can participate in the world championship at most 5 times.
Th... | ```python
n, k = map(int, input().split())
arr= list(map(int, input().split()))
count = 0
for i in arr:
if 5-i >= k:
count += 1
ans= count // 3
print(ans)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ... | ```python
s=input()
c=0
for i in s:
if i=='4' or i=='7':
c+=1
l=[4,7,47,74,447,444,474,744,747,774,477]
d=0
for j in l:
if int(s)>j:
if int(s)%j==0:
d+=1
if d!=0 or c==len(s):
print('YES')
else:
print('NO')
``` | |
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 Vasy... | ```python
a=int(input())
b=[]
for i in range(a):
b.append(list(map(int,input().split(" ")[:3])))
r=0
for j in range(len(b)):
r=r+sum(b[j])
if(r==0):
print("YES")
else:
print("NO")
``` | |
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... | ```python
import math
m,n,a=map(int,input().split())
x=math.ceil(m/a)
y=math.ceil(n/a)
if x>1 and y>1:
t=x+y
if x<=1 and y<=1:
t=1
if x>1 and y<=1:
t=x
if x<=1 and y>1:
t=y
print(t)
``` | |
MatrixStudio/Codeforces-Python-Submissions | There is a very secret base in Potatoland where potato mash is made according to a special recipe. The neighbours from Porridgia decided to seize this recipe and to sell it to Pilauland. For this mission they have been preparing special agent Pearlo for many years. When, finally, Pearlo learned all secrets of espionage... | ```python
a=input()
b=input()
c=input()
a=list(a)
b=list(b)
c=list(c)
if c[::-1]==a:
print("YES")
elif b[0]==b[2]:
print("YES")
else:
print("NO")
``` | |
MatrixStudio/Codeforces-Python-Submissions | One spring day on his way to university Lesha found an array *A*. Lesha likes to split arrays into several parts. This time Lesha decided to split the array *A* into several, possibly one, new arrays so that the sum of elements in each of the new arrays is not zero. One more condition is that if we place the new arrays... | ```python
#For fast I/O
import sys
input = lambda: sys.stdin.readline().strip()
n = int(input())
l = [int(i) for i in input().split()]
s = sum(l)
if s != 0:
print('YES')
print(1)
print(1,n)
else:
possible = False
for i in range(n):
if l[i] != 0:
possible = True
print('YES')
print(2... | |
MatrixStudio/Codeforces-Python-Submissions | Petya is preparing for IQ test and he has noticed that there many problems like: you are given a sequence, find the next number. Now Petya can solve only problems with arithmetic or geometric progressions.
Arithmetic progression is a sequence *a*1, *a*1<=+<=*d*, *a*1<=+<=2*d*, ..., *a*1<=+<=(*n*<=-<=1)*d*, where *a*1 ... | ```python
numbers = list(map(int,input().split()))
arithmetic_prog = numbers[1] - numbers[0]
geometric_prog = numbers[1] / numbers[0]
if numbers[3]-numbers[2] == arithmetic_prog and numbers[2]-numbers[1] == arithmetic_prog:
print(int(numbers[-1]+arithmetic_prog))
elif numbers[3]/numbers[2] == geometric_prog ... | |
MatrixStudio/Codeforces-Python-Submissions | A soldier wants to buy *w* bananas in the shop. He has to pay *k* dollars for the first banana, 2*k* dollars for the second one and so on (in other words, he has to pay *i*·*k* dollars for the *i*-th banana).
He has *n* dollars. How many dollars does he have to borrow from his friend soldier to buy *w* bananas? | ```python
k,n,w=map(int,input().split())
sum=0
tc=0
for i in range(w+1):
sum=sum+i
tc=sum*k
print(tc-n)
``` | |
MatrixStudio/Codeforces-Python-Submissions | Some days ago, I learned the concept of LCM (least common multiple). I've played with it for several times and I want to make a big number with it.
But I also don't want to use many numbers, so I'll choose three positive integers (they don't have to be distinct) which are not greater than *n*. Can you help me to find ... | ```python
from math import gcd
n = int(input())
if n <= 3:
print([0, 1, 2, 6][n])
exit()
print(
max(
n * (n-1) * (n-2) // gcd(n, n-2),
(n-1) * (n-2) * (n-3) // gcd(n-1, n-3)
)
)
``` | |
MatrixStudio/Codeforces-Python-Submissions | You helped Dima to have a great weekend, but it's time to work. Naturally, Dima, as all other men who have girlfriends, does everything wrong.
Inna and Dima are now in one room. Inna tells Dima off for everything he does in her presence. After Inna tells him off for something, she goes to another room, walks there in ... | ```python
def read():
n, k = list(map(int, input().split()))
powers = list(map(int, input().split()))
return n, k, powers
def get_min_power(n, k, powers):
start_task = 0
mins = []
for i in range(k):
s = 0
for j in range(i, n, k):
s += powers[j]
... | |
MatrixStudio/Codeforces-Python-Submissions | An *n*<=×<=*n* table *a* is defined as follows:
- The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the ... | ```python
n = int(input())
x = [0,1,2,6,20,70,252,924,3432,12870,48620]
print(x[n])
``` | |
MatrixStudio/Codeforces-Python-Submissions | A bracket sequence is a string, containing only characters "(", ")", "[" and "]".
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters "1" and "+" between the original characters of the sequence. For example, bracket sequences "()[]", "([... | ```python
'''input
((()))([]
'''
from sys import stdin
def check_valid(string):
stack = []
for i in string:
if i in ['(', '[']:
stack.append(i)
elif i == ')':
if len(stack) > 0:
if stack[-1] == '(':
stack.pop()
continue
return False
elif i == ']':
if len(stack) > 0:
if stack[-1]... | |
MatrixStudio/Codeforces-Python-Submissions | You are given the current time in 24-hour format hh:mm. Find and print the time after *a* minutes.
Note that you should find only the time after *a* minutes, see the examples to clarify the problem statement.
You can read more about 24-hour format here [https://en.wikipedia.org/wiki/24-hour_clock](https://en.wikipedi... | ```python
l1 = [int(x) for x in input().split(":")]
n = int(input())
final = l1[0]*60+l1[1]+n
total = 24*60
thing = final%total
print(str(int(thing/60))+str(":")+str(thing%60))
``` | |
MatrixStudio/Codeforces-Python-Submissions | Kitahara Haruki has bought *n* apples for Touma Kazusa and Ogiso Setsuna. Now he wants to divide all the apples between the friends.
Each apple weights 100 grams or 200 grams. Of course Kitahara Haruki doesn't want to offend any of his friend. Therefore the total weight of the apples given to Touma Kazusa must be equa... | ```python
x = int(input())
from collections import Counter
y = map(int,input().split())
y = Counter(y)
# print(y)
s = y[100]+y[200]*2
# print(s)
if s%2:
print("NO")
else:
print("YES")
``` | |
MatrixStudio/Codeforces-Python-Submissions | You are given two integers $a$ and $b$. Moreover, you are given a sequence $s_0, s_1, \dots, s_{n}$. All values in $s$ are integers $1$ or $-1$. It's known that sequence is $k$-periodic and $k$ divides $n+1$. In other words, for each $k \leq i \leq n$ it's satisfied that $s_{i} = s_{i - k}$.
Find out the non-negative ... | ```python
n, a, b, k = map(int,input().split())
s = input()
i = 0
su = []
for i in range(k):
t = 0
if s[i] == '+':
for j in range(n // k + 1):
if 0 <= n-k*j-i <= n:
t += pow(a, n-k*j-i, 10**9+9)*pow(b, k*j+i, 10**9+9)
else:
for j in range(n // k + 1... | |
MatrixStudio/Codeforces-Python-Submissions | Fox Ciel saw a large field while she was on a bus. The field was a *n*<=×<=*m* rectangle divided into 1<=×<=1 cells. Some cells were wasteland, and other each cell contained crop plants: either carrots or kiwis or grapes.
After seeing the field carefully, Ciel found that the crop plants of each cell were planted in f... | ```python
def mi():
return map(int, input().split())
n,m,k,t = mi()
wasterowscount = [0]*(n+1)
d = {0:'Carrots',1:'Kiwis',2:'Grapes'}
waste = [[]]*(n+1)
def fun(x,y):
global waste
if y in waste[x]:
print ('Waste')
return 0
cur = (((x-1)*m-wasterowscount[x-1]))
cur+=(y)
for i in range(wasterow... | |
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 th... | ```python
T=input()
countU=0
countL=0
for i in range(len(T)):
if T[i].islower()==True:
countL+=1
else:
countU+=1
if countL==countU:
print(T.lower())
if countL>countU:
print(T.lower())
if countL<countU:
print(T.upper())
``` | |
MatrixStudio/Codeforces-Python-Submissions | An *n*<=×<=*n* table *a* is defined as follows:
- The first row and the first column contain ones, that is: *a**i*,<=1<==<=*a*1,<=*i*<==<=1 for all *i*<==<=1,<=2,<=...,<=*n*. - Each of the remaining numbers in the table is equal to the sum of the number above it and the number to the left of it. In other words, the ... | ```python
#get input
#n=5
n=int(input())
table=[]
##Making the appropriate table
#make nxn table following the given rule
for i in range(n):
table.append([])
#appending 1s in the first row
for i in range(n):
table[0].append(1)
#appending 1s at first column of each row except the... | |
MatrixStudio/Codeforces-Python-Submissions | You are given a connected weighted undirected graph without any loops and multiple edges.
Let us remind you that a graph's spanning tree is defined as an acyclic connected subgraph of the given graph that includes all of the graph's vertexes. The weight of a tree is defined as the sum of weights of the edges that the... | ```python
N = 100010
n, m = map(int, input().split())
x = [0] * (N)
y = [0] * (N)
z = [0] * (N)
p = [0] * (N)
ans = [0] * (N)
f = [False] * (N)
h = [0] * (N)
pe = [0] * (N)
d = [0] * (N)
v = [[] for _ in range(N)]
# Função para comparar arestas com base em seus pesos (z)
def cmp(i, j):
return z[i]... | |
MatrixStudio/Codeforces-Python-Submissions | Unlike Knights of a Round Table, Knights of a Polygonal Table deprived of nobility and happy to kill each other. But each knight has some power and a knight can kill another knight if and only if his power is greater than the power of victim. However, even such a knight will torment his conscience, so he can kill no mo... | ```python
import heapq
if __name__ == '__main__':
rd = lambda: map(int, input().split())
n, k = rd()
a = sorted(zip(rd(), rd(), range(n)))
minH = []
total = 0
ans = [0] * n
for i in range(len(a)):
if len(minH) >= k + 1:
(coins, index) = heapq.heappop(minH)
t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.