problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
problem
Given a sequence $ a_i $ of length $ N $. Output all integers $ K (1 \ le K \ le N) $ that satisfy the following conditions.
Condition: Well sorted $ a_1, \ cdots, a_K $ matches $ a_ {N-K + 1}, \ cdots, a_N $.
Example
Input
8
5 2 4 9 4 9 2 5
Output
1 2 4 6 7 8 | 3 | import sys,queue,math,copy,itertools,bisect
from fractions import gcd
sys.setrecursionlimit(10**7)
INF = 10**18
MOD = 10**9 + 7
LI = lambda : [int(x) for x in sys.stdin.readline().split()]
_LI = lambda : [int(x)-1 for x in sys.stdin.readline().split()]
NI = lambda : int(sys.stdin.readline())
N = NI()
A = LI()
A_sort ... |
Our good friend Mole is trying to code a big message. He is typing on an unusual keyboard with characters arranged in following way:
qwertyuiop
asdfghjkl;
zxcvbnm,./
Unfortunately Mole is blind, so sometimes it is problem for him to put his hands accurately. He accidentally move... | 3 | def solve(loc, seq):
keys = "qwertyuiopasdfghjkl;zxcvbnm,./"
ans = ''
for i in seq:
for j in range(len(keys)):
if i == keys[j]:
if loc == "R":
ans += keys[j-1]
else:
ans += keys[j+1]
return ans
loc = input()
seq = input()
print(solve(loc,seq))
|
Ichihime is the current priestess of the Mahjong Soul Temple. She claims to be human, despite her cat ears.
These days the temple is holding a math contest. Usually, Ichihime lacks interest in these things, but this time the prize for the winner is her favorite — cookies. Ichihime decides to attend the contest. Now sh... | 3 | t=int(input())
for a in range(t):
a,b,c,d=map(int,input().split())
print(b,c,c)
|
HQ9+ is a joke programming language which has only four one-character instructions:
* "H" prints "Hello, World!",
* "Q" prints the source code of the program itself,
* "9" prints the lyrics of "99 Bottles of Beer" song,
* "+" increments the value stored in the internal accumulator.
Instructions "H" and "Q"... | 3 | import sys
inputstring =input()
lan = ['H','Q','9']
for letter in inputstring:
if letter in lan:
print("YES")
sys.exit()
print("NO") |
Snuke has come to a store that sells boxes containing balls. The store sells the following three kinds of boxes:
* Red boxes, each containing R red balls
* Green boxes, each containing G green balls
* Blue boxes, each containing B blue balls
Snuke wants to get a total of exactly N balls by buying r red boxes, g gre... | 3 | r,g,b,n=map(int,input().split())
cnt=0
for i in range(n//r+1):
for j in range((n-r*i)//g+1):
if (n-r*i-g*j)%b==0:
cnt+=1
print(cnt) |
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 3 | n,m=map(int,input().split())
a=[]
b=[]
for i in range(m):
x,y=input().split()
a.append(x)
b.append(y)
s=list(input().split())
#print(len(s))
ans=[]
for i in range(len(s)):
bs=a.index(s[i])
if(len(a[bs])>len(b[bs])):
ans.append(b[bs])
else:
ans.append(a[bs])
fo... |
Kostya is a genial sculptor, he has an idea: to carve a marble sculpture in the shape of a sphere. Kostya has a friend Zahar who works at a career. Zahar knows about Kostya's idea and wants to present him a rectangular parallelepiped of marble from which he can carve the sphere.
Zahar has n stones which are rectangul... | 1 | v={}
t=(0,0)
def go(k,c,i):
global t
if k in v:
x=min(k[0],k[1],c+v[k][0])
if x>t[0]:
t=(x,v[k][1],i)
def up(k,c,i):
if k not in v or v[k][0]<c:
v[k]=(c,i)
for i in range(input()):
a,b,c=sorted(map(int,raw_input().split()))
x=min(a,b,c)
if x>t[0]:
t=(x,i)
go((a,b),c,i)
go((a,c),b,i... |
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got?
Jeff must make the number without leading zero. At that, we assume that number ... | 3 | n=int(input())
l=list(map(int,input().split()))
c1=l.count(5)
c2=n-c1
# print(c1)
# print(c2)
if c2==0:
print("-1")
elif c1>=9 and c2>0:
print("5"*(c1-(c1%9))+"0"*c2)
elif c1<9 and c2>0:
print("0") |
Maria is the most active old lady in her house. She was tired of sitting at home. She decided to organize a ceremony against the coronavirus.
She has n friends who are also grannies (Maria is not included in this number). The i-th granny is ready to attend the ceremony, provided that at the time of her appearance in t... | 3 | import sys
t = int(sys.stdin.readline())
while t:
n = int(sys.stdin.readline())
arr = sorted(list(map(int,sys.stdin.readline().split())))
count = 0
for i in range(len(arr)):
if i+1>=arr[i]:
count = i+1
print(max(1,count+1))
t-=1 |
There are N children, numbered 1, 2, ..., N.
Snuke has decided to distribute x sweets among them. He needs to give out all the x sweets, but some of the children may get zero sweets.
For each i (1 \leq i \leq N), Child i will be happy if he/she gets exactly a_i sweets. Snuke is trying to maximize the number of happy ... | 3 | N,x = map(int,input().split())
A = sorted(list(map(int,input().split())))
i = 0
while x >= A[i]:
x += -A[i]
i += 1
if i == N:
i = (i-1 if x > 0 else i)
break
print(i) |
The only difference between problems C1 and C2 is that all values in input of problem C1 are distinct (this condition may be false for problem C2).
You are given a sequence a consisting of n integers.
You are making a sequence of moves. During each move you must take either the leftmost element of the sequence or the... | 3 | # -*- coding: utf-8 -*-
import sys
from collections import deque
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j... |
After you had helped George and Alex to move in the dorm, they went to help their friend Fedor play a new computer game «Call of Soldiers 3».
The game has (m + 1) players and n types of soldiers in total. Players «Call of Soldiers 3» are numbered form 1 to (m + 1). Types of soldiers are numbered from 0 to n - 1. Each ... | 3 |
n, m, k = map(int, input().split())
l = []
for i in range(m+1):
q = int(input())
l.append(q)
g = l[-1]
ans = 0
for i in range(m):
mask = g ^ l[i]
n = 0
while mask != 0:
mask = mask & (mask-1)
n += 1
if n <= k:
ans += 1
print(ans)
|
Due to the coronavirus pandemic, city authorities obligated citizens to keep a social distance. The mayor of the city Semyon wants to light up Gluharniki park so that people could see each other even at night to keep the social distance.
The park is a rectangular table with n rows and m columns, where the cells of the... | 3 | from sys import stdin,stderr
def rl():
return [int(w) for w in stdin.readline().split()]
t, = rl()
for _ in range(t):
n, m = rl()
print((n * m + 1) // 2)
|
Captain Flint and his crew keep heading to a savage shore of Byteland for several months already, drinking rum and telling stories. In such moments uncle Bogdan often remembers his nephew Denis. Today, he has told a story about how Denis helped him to come up with an interesting problem and asked the crew to solve it.
... | 3 | t = int(input())
Ans = []
for i in range(t):
n = int(input())
dev_ok = 3*n // 4
vosm_ok = n - dev_ok
x = '9'*dev_ok + '8'*vosm_ok
Ans.append(x)
for i in Ans:
print(int(i)) |
Mishka started participating in a programming contest. There are n problems in the contest. Mishka's problem-solving skill is equal to k.
Mishka arranges all problems from the contest into a list. Because of his weird principles, Mishka only solves problems from one of the ends of the list. Every time, he chooses whic... | 3 | NK = [int(x) for x in input().split()]
list = [int(x) for x in input().split()]
n=NK[0]
k=NK[1]
leftPointer=0
rightPointer = n
maxPL=0
maxPR=0
maxT = 0
if k >= max(list):
print (n)
else :
for i in list :
if k>=i:
maxPL+=1
else:
break
for i in range (n-1,0,-1) :
... |
The classic programming language of Bitland is Bit++. This language is so peculiar and complicated.
The language is that peculiar as it has exactly one variable, called x. Also, there are two operations:
* Operation ++ increases the value of variable x by 1.
* Operation -- decreases the value of variable x by 1.... | 3 | n=int(input());
val=0;
for i in range(n):
op=input();
if(op[0]=="+" or op[1]=="+"):
val+=1;
else:
val-=1;
print(val); |
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 squa... | 3 | a=input().split()
m=int(a[0])
n=int(a[1])
print(int(m*n/2)) |
The Smart Beaver from ABBYY got hooked on square matrices. Now he is busy studying an n × n size matrix, where n is odd. The Smart Beaver considers the following matrix elements good:
* Elements of the main diagonal.
* Elements of the secondary diagonal.
* Elements of the "middle" row — the row which has exac... | 1 | n = input()
a = [map(int, raw_input().split()) for _ in range(n)]
print sum(a[x][y] for x in range(n) for y in range(n) if x == n / 2 or y == n / 2 or x == y or x + y == n - 1) |
M-kun is a brilliant air traffic controller.
On the display of his radar, there are N airplanes numbered 1, 2, ..., N, all flying at the same altitude.
Each of the airplanes flies at a constant speed of 0.1 per second in a constant direction. The current coordinates of the airplane numbered i are (X_i, Y_i), and the d... | 3 | import sys
from collections import defaultdict
from bisect import bisect_right
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in ra... |
Three years have passes and nothing changed. It is still raining in London, and Mr. Black has to close all the doors in his home in order to not be flooded. Once, however, Mr. Black became so nervous that he opened one door, then another, then one more and so on until he opened all the doors in his house.
There are ex... | 3 | #------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
# from fractions import *
# from heapq import*
from bisect import *
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')... |
Anton likes to play chess, and so does his friend Danik.
Once they have played n games in a row. For each game it's known who was the winner — Anton or Danik. None of the games ended with a tie.
Now Anton wonders, who won more games, he or Danik? Help him determine this.
Input
The first line of the input contains a... | 3 | numgames = int(input())
winner = input()
A=0
D=0
for i in range (numgames):
if winner[i] == "A": A+=1
if winner[i] == "D": D+=1
if A>D: print ('Anton')
if D>A: print ('Danik')
if A==D: print ('Friendship') |
You are given a sequence of integers of length n and integer number k. You should print any integer number x in the range of [1; 10^9] (i.e. 1 ≤ x ≤ 10^9) such that exactly k elements of given sequence are less than or equal to x.
Note that the sequence can contain equal elements.
If there is no such x, print "-1" (w... | 3 | [n, k] = list(map(int, input().split(" ")))
a = list(map(int, input().split(" ")))
a.sort()
if k == 0:
print(-1 if a[0] == 1 else 1)
else:
print(-1 if (k <= n-1 and a[k-1] == a[k]) else a[k-1])
|
Finally, a basketball court has been opened in SIS, so Demid has decided to hold a basketball exercise session. 2 ⋅ n students have come to Demid's exercise session, and he lined up them into two rows of the same size (there are exactly n people in each row). Students are numbered from 1 to n in each row in order from ... | 3 | import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools
# import time,random,resource
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
mod2 = 998244353
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI():... |
n soldiers stand in a circle. For each soldier his height ai is known. A reconnaissance unit can be made of such two neighbouring soldiers, whose heights difference is minimal, i.e. |ai - aj| is minimal. So each of them will be less noticeable with the other. Output any pair of soldiers that can form a reconnaissance u... | 3 | n = int(input())
string = input()
heights = list(map(int, string.split()))
differences = []
for x in range(n):
if x == n - 1:
differences.append(abs(heights[0] - heights[x]))
else:
differences.append(abs(heights[x + 1] - heights[x]))
a = differences.index(min(differences))
if a == n - 1:
pri... |
You are given two positive integers n and k. Print the k-th positive integer that is not divisible by n.
For example, if n=3, and k=7, then all numbers that are not divisible by 3 are: 1, 2, 4, 5, 7, 8, 10, 11, 13 .... The 7-th number among them is 10.
Input
The first line contains an integer t (1 ≤ t ≤ 1000) — the ... | 3 | from sys import stdin
input=lambda : stdin.readline().strip()
from math import ceil,sqrt,factorial,gcd
for _ in range(int(input())):
n,k=map(int,input().split())
if k<n:
print(k)
elif k==n:
print(n+1)
else:
t=(k//(n-1))*n
f=k%(n-1)
if f==0:
print(t-1)
else:
print(t+f) |
Petya started to attend programming lessons. On the first lesson his task was to write a simple program. The program was supposed to do the following: in the given string, consisting if uppercase and lowercase Latin letters, it:
* deletes all the vowels,
* inserts a character "." before each consonant,
* repl... | 3 | word = str(input()).lower()
arr = list(word)
fin = []
for w in arr:
if w=='a' or w=='e' or w=='i' or w=='o' or w=='u' or w=='y':
continue
else:
fin.append(w)
str='.'
for i in range(len(fin)):
if i!=len(fin)-1:
str+=fin[i]
str+='.'
if i==len(fin)-1:
str+=fin[i]
pri... |
Little girl Susie accidentally found her elder brother's notebook. She has many things to do, more important than solving problems, but she found this problem too interesting, so she wanted to know its solution and decided to ask you about it. So, the problem statement is as follows.
Let's assume that we are given a c... | 1 | from collections import defaultdict,deque,Counter,OrderedDict
from heapq import heappop,heappush
def main():
n,m = map(int,raw_input().split())
adj = [[] for i in xrange(n+1)]
for i in range(m):
a,b,c = map(int,raw_input().split())
adj[a].append((b, c, i))
adj[b].append((a, c, i))... |
It's been almost a week since Polycarp couldn't get rid of insomnia. And as you may already know, one week in Berland lasts k days!
When Polycarp went to a doctor with his problem, the doctor asked him about his sleeping schedule (more specifically, the average amount of hours of sleep per week). Luckily, Polycarp kep... | 3 | n, k = [int(p) for p in input().split()]
w = n - k + 1
arr = [int(p) for p in input().split()]
s = sum(arr[:k])
curr = s
j = k
i = 0
while j < len(arr):
s -= arr[i]
i += 1
s += arr[j]
j += 1
curr += s
print(curr/w) |
There are n cards numbered 1, …, n. The card i has a red digit r_i and a blue digit b_i written on it.
We arrange all n cards in random order from left to right, with all permutations of 1, …, n having the same probability. We then read all red digits on the cards from left to right, and obtain an integer R. In the sa... | 3 | t=int(input(''))
for i in range(0,t):
n=int(input(''))
p=list(input(''))
q=list(input(''))
r=0
b=0
for j in range(0,n):
if p[j]>q[j]:
r=r+1
elif q[j]>p[j]:
b=b+1
if r==b:
print('EQUAL')
elif r<b:
print('BLUE')
elif r>b:
... |
During their New Year holidays, Alice and Bob play the following game using an array a of n integers:
* Players take turns, Alice moves first.
* Each turn a player chooses any element and removes it from the array.
* If Alice chooses even value, then she adds it to her score. If the chosen value is odd, Alice... | 3 | for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
arr=sorted(arr)[::-1];Alice=0;Bob=0
for i in range(n):
if i%2==0:#ALice turn
if arr[i]%2==0:Alice+=arr[i]
else:
if arr[i]%2==1:Bob+=arr[i]
if Alice==Bob:print("Tie")
elif Alice>Bob:print("Alice")
else:print("B... |
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 using ... | 3 | # author="_rabbit"
def pw(a,b):
ans=1
while(b!=0):
if(b%2==1):
ans=(ans*a)%100;
#print("a=%d,b=%d,ans=%d" %(a,b,ans))
a=(a*a)%100
b//=2
return ans
if __name__=="__main__":
n=(int)(input())
ans=pw(5,n)
print(ans)
|
A large banner with word CODEFORCES was ordered for the 1000-th onsite round of Codeforcesω that takes place on the Miami beach. Unfortunately, the company that made the banner mixed up two orders and delivered somebody else's banner that contains someone else's word. The word on the banner consists only of upper-case ... | 1 | s = raw_input()
n = len(s)
found = False
for i in xrange(n):
for j in xrange(i, n):
sub = s[:i] + s[j+1:]
if sub == 'CODEFORCES':
found = True
if found:
print "YES"
else:
print "NO"
|
This morning, Roman woke up and opened the browser with n opened tabs numbered from 1 to n. There are two kinds of tabs: those with the information required for the test and those with social network sites. Roman decided that there are too many tabs open so he wants to close some of them.
He decided to accomplish this... | 1 | n, k = map(int, raw_input().split())
a = map(int, raw_input().split())
m = 0
for i in range(k):
j = i
c = 0
while j < n:
c += a[j]
j += k
m = max(m, abs(c - sum(a)))
print m
|
We have a tree with N vertices numbered 1 to N. The i-th edge in the tree connects Vertex u_i and Vertex v_i, and its length is w_i. Your objective is to paint each vertex in the tree white or black (it is fine to paint all vertices the same color) so that the following condition is satisfied:
* For any two vertices p... | 3 | n = int(input())
l = [[]for i in range(n)]
for i in range(n-1):
u, v, w = map(int, input().split())
u -= 1
v -= 1
l[u].append([v, w])
l[v].append([u, w])
c = [-1] * (n-1)
color = [0] + c
x = [0]
while x:
current = x.pop(0)
for y, d in l[current]:
if color[y] > -1:
continu... |
A string is said to be complete if it contains all the characters from a to z. Given a string, check if it complete or not.
Input
First line of the input contains the number of strings N. It is followed by N lines each contains a single string.
Output
For each test case print "YES" if the string is complete, else pri... | 1 | y = "YES"
n = "NO"
di = {'a' : 0,'b' : 1,'c' : 2,'d' : 3,'e' : 4,'f' : 5,'g' : 6,'h' : 7,'i' : 8,'j' : 9,'k' : 10,'l' : 11,'m' : 12,'n' : 13,'o' : 14,'p' : 15,'q' : 16,'r' : 17,'s' : 18,'t' : 19,'u' : 20,'v' : 21,'w' : 22,'x' : 23,'y' : 24,'z' : 25}
for t in range(input()) :
s = raw_input()
flag = True
li = [0]*26... |
Polycarp plays a well-known computer game (we won't mention its name). In this game, he can craft tools of two types — shovels and swords. To craft a shovel, Polycarp spends two sticks and one diamond; to craft a sword, Polycarp spends two diamonds and one stick.
Each tool can be sold for exactly one emerald. How many... | 3 | t=int(input())
while t>0:
t-=1
s,d=[int(x) for x in input().split()]
print(min(s,d,(s+d)//3))
|
Recently Vova found n candy wrappers. He remembers that he bought x candies during the first day, 2x candies during the second day, 4x candies during the third day, ..., 2^{k-1} x candies during the k-th day. But there is an issue: Vova remembers neither x nor k but he is sure that x and k are positive integers and k >... | 3 | ppp=int(input())
for tika in range(0,ppp):
n=int(input())
for i in range(2,1000000000):
if(n/(2**i -1 )%1==0):
print(int(n/(2**i -1 )))
break |
Little Petya loves presents. His mum bought him two strings of the same size for his birthday. The strings consist of uppercase and lowercase Latin letters. Now Petya wants to compare those two strings lexicographically. The letters' case does not matter, that is an uppercase letter is considered equivalent to the corr... | 3 | a = input().lower()
b = input().lower()
if a == b:
print(0)
elif a > b:
print(1)
elif a < b:
print(-1)
|
You are given two integers n and m. You have to construct the array a of length n consisting of non-negative integers (i.e. integers greater than or equal to zero) such that the sum of elements of this array is exactly m and the value ∑_{i=1}^{n-1} |a_i - a_{i+1}| is the maximum possible. Recall that |x| is the absolut... | 3 | for x in range(int(input())):
li=list(map(int,input().split()))
if(li[0]==1):
print(0)
elif(li[0]==2):
print(li[1])
else:
print(li[1]*2) |
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.... | 3 | first = input()
translation = input()
if translation == first[::-1]:
print("YES")
else:
print("NO")
|
Suppose you are performing the following algorithm. There is an array v_1, v_2, ..., v_n filled with zeroes at start. The following operation is applied to the array several times — at i-th step (0-indexed) you can:
* either choose position pos (1 ≤ pos ≤ n) and increase v_{pos} by k^i;
* or not choose any posit... | 3 | def ternary(n, k):
l = []
while(n>0):
l.append(n%k)
n = n//k
return l
t = int(input())
from collections import defaultdict
for _ in range(t):
d = defaultdict(int)
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
f = False
for x in a:
l = tern... |
You are given an array a of length n.
You are also given a set of distinct positions p_1, p_2, ..., p_m, where 1 ≤ p_i < n. The position p_i means that you can swap elements a[p_i] and a[p_i + 1]. You can apply this operation any number of times for each of the given positions.
Your task is to determine if it is poss... | 3 |
def fun(a,n,q):
for i in range(0,n-1):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
q[j+1]=0
for _ in range(int(input())):
n,m=map(int,input().split())
a=[int(n) for n in input().split()]
p=[int(n) for n in input().split()]
y={... |
Dr. Bruce Banner hates his enemies (like others don't). As we all know, he can barely talk when he turns into the incredible Hulk. That's why he asked you to help him to express his feelings.
Hulk likes the Inception so much, and like that his feelings are complicated. They have n layers. The first layer is hate, seco... | 3 | n = int(input())
love = "I love "
hate = "I hate "
it = "it "
result = ""
for i in range(1, n+1):
if i%2 == 1:
result += hate
if i == n:
result += it
else:
result += "that "
else:
result += love
if i == n:
result += it
else:... |
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... | 3 | from sys import stdin,stdout
s=stdin.readline().rstrip()
c=1
q=s[0]
f=0
for i in range(1,len(s)):
if s[i]==q:
c+=1
else:
q=s[i]
c=1
if c==7:
f=1
break
if f==0:
stdout.write("NO")
else:
stdout.write("YES") |
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... | 1 | cadena = raw_input()
def peligro(cadena):
contador=1
for x in range(1,len(cadena)):
if cadena[x]==cadena[x-1]:
contador+=1
else:
contador=1
if contador==7:
print "YES"
return 0
print "NO"
peligro(cadena) |
Write a program which reads an integer $S$ [second] and converts it to $h:m:s$ where $h$, $m$, $s$ denote hours, minutes (less than 60) and seconds (less than 60) respectively.
Constraints
* $0 \leq S \leq 86400$
Input
An integer $S$ is given in a line.
Output
Print $h$, $m$ and $s$ separated by ':'. You do not n... | 3 | a=int(input())
print(a//3600,":",a%3600//60,":",a%3600%60,sep="") |
There are n models in the shop numbered from 1 to n, with sizes s_1, s_2, …, s_n.
Orac will buy some of the models and will arrange them in the order of increasing numbers (i.e. indices, but not sizes).
Orac thinks that the obtained arrangement is beatiful, if for any two adjacent models with indices i_j and i_{j+1} ... | 3 | # May the Speedforce be with us...
'''
for _ in range(int(input())):
arr=list(map(int,input().split()))
n,k=map(int,input().split())
n=int(input())
s=input()
from collections import defaultdict
d=defaultdict()
d=dict()
s=set()
s.intersection()
s.union()
s.difference()
problem statement achhe se padhna hai
age se bh... |
Peter likes to travel by train. He likes it so much that on the train he falls asleep.
Once in summer Peter was going by train from city A to city B, and as usual, was sleeping. Then he woke up, started to look through the window and noticed that every railway station has a flag of a particular colour.
The boy start... | 3 | #!/usr/bin/env python
'''
' Author: Cheng-Shih Wong
' Email: mob5566@gmail.com
' Date:
'''
def main():
def check(seq, A, B):
fA = seq.find(A)
return fA >= 0 and seq.find(B, fA+len(A)) >= 0
flags = input()
fmem = input()
smem = input()
forw = check(flags, fmem, smem)
... |
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 car... | 3 | #!/usr/bin/env python3
inf = float('inf')
read_ints = lambda : list(map(int, input().split()))
def solve(arr):
return 42
if __name__ == '__main__':
special = 'aeiou13579'
print(len(list(filter(lambda l: l in special, input()))))
|
You are given two arrays a and b both consisting of n positive (greater than zero) integers. You are also given an integer k.
In one move, you can choose two indices i and j (1 ≤ i, j ≤ n) and swap a_i and b_j (i.e. a_i becomes b_j and vice versa). Note that i and j can be equal or different (in particular, swap a_2 w... | 3 | t=int(input())
for i in range(t):
n,k=map(int,input().split())
arr=list(map(int, input().split()))
brr=list(map(int, input().split()))
while k and min(arr)<max(brr) :
m=min(arr)
i=arr.index(m)
mn=max(brr)
j=brr.index(mn)
arr[i]=max(brr)
brr[j]=m
k-... |
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network.
Bu... | 3 | m = input()
seen = set()
for char in m:
seen.add(char)
l = len(seen)
if l % 2 == 0:
print('CHAT WITH HER!')
else:
print('IGNORE HIM!')
|
You are given an array a with n elements. Each element of a is either 0 or 1.
Let's denote the length of the longest subsegment of consecutive elements in a, consisting of only numbers one, as f(a). You can change no more than k zeroes to ones to maximize f(a).
Input
The first line contains two integers n and k (1 ≤... | 3 | s=list(map(int,input().split()))
s1=list(map(int,input().split()))
start=0
end=0
c=0
s2=0
x=0
y=0
while(end<s[0]):
if(s1[end]==0):
c+=1
while(c>s[1]):
c+=s1[start]-1
start+=1
if(end-start+1>s2):
s2=end-start+1
x=start
y=end
end+=1
print(s2)
for i in range... |
Little girl Tanya is learning how to decrease a number by one, but she does it wrong with a number consisting of two or more digits. Tanya subtracts one from a number by the following algorithm:
* if the last digit of the number is non-zero, she decreases the number by one;
* if the last digit of the number is ze... | 3 | x,y = map(int, (input()).split())
for i in range(y):
if(x%10==0):
x/=10
else:
x-=1
print(int(x))
|
You are given two strings s and t. The string s consists of lowercase Latin letters and at most one wildcard character '*', the string t consists only of lowercase Latin letters. The length of the string s equals n, the length of the string t equals m.
The wildcard character '*' in the string s (if any) can be replace... | 1 | from fractions import gcd
from math import factorial, ceil, sqrt, atan2, log, pi, e, asin, acos, cos, sin, floor
from itertools import *
from fractions import Fraction
import string
import copy
import random
import bisect
from decimal import *
from collections import deque
from sys import *
digs = string.digits + strin... |
You are given a broken clock. You know, that it is supposed to show time in 12- or 24-hours HH:MM format. In 12-hours format hours change from 1 to 12, while in 24-hours it changes from 0 to 23. In both formats minutes change from 0 to 59.
You are given a time in format HH:MM that is currently displayed on the broken ... | 3 | #!/usr/bin/python3
form = int(input())
time = input()
if (form == 24):
if (int(time[0:2]) >= 24):
time = '0' + time[1:5]
if (int(time[3:5]) >= 60):
time = time[0:3] + '0' + time[4]
elif (form == 12):
if (int(time[0:2]) > 12 and not(int(time[1]) == 0)):
time = '0' + time[1:]
elif (int(time[0:2]) > 12 and int(t... |
Btoh yuo adn yuor roomatme lhoate wianshg disehs, btu stlil sdmoeboy msut peorrfm tihs cohre dialy. Oen dya yuo decdie to idourtcne smoe syestm. Yuor rmmotaoe sstgegus teh fooniwllg dael. Yuo argee on tow arayrs of ientgres M adn R, nmebur upmicnog dyas (induiclng teh cunrret oen) wtih sicsescuve irnegets (teh ceurrnt ... | 3 | N = int(input())
M = list(map(int,input().split()))
R = list(map(int,input().split()))
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
lcm = 1
for i in range(N):
lcm = lcm * M[i] / gcd(lcm, M[i])
rec = set()
for i in range(N):
j = R[i]
while j < lcm:
rec.add(j)
j += M[i]
print(len(... |
AtCoDeer the deer and his friend TopCoDeer is playing a game. The game consists of N turns. In each turn, each player plays one of the two gestures, Rock and Paper, as in Rock-paper-scissors, under the following condition:
(※) After each turn, (the number of times the player has played Paper)≦(the number of times the ... | 3 | S = input()
N = len(S)
P = S.count('p')
print(N // 2 - P)
|
Chef and Roma are playing a game. Rules of the game are quite simple.
Initially there are N piles of stones on the table.
In each turn, a player can choose one pile and remove it from the table.
Each player want to maximize the total number of stones removed by him.
Chef takes the first turn.
Please tell Chef the max... | 1 | #This Is an Important Message that is meaningless. <VigzMv/>
for i in range(0,int(raw_input())):
n=int(raw_input())
l=list(map(int,raw_input().split()))
l.sort()
print sum(l[len(l)-1::-2]) |
Snuke is having a barbeque party.
At the party, he will make N servings of Skewer Meal.
<image>
Example of a serving of Skewer Meal
He has a stock of 2N skewers, all of which will be used in Skewer Meal. The length of the i-th skewer is L_i. Also, he has an infinite supply of ingredients.
To make a serving of Skew... | 3 | n=int(input())
l=list(map(int,input().split()))
l.sort()
ans=0
i=0
while i<n*2-1:
ans+=l[i]
i+=2
print(ans) |
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n.
Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance... | 1 | n = input()
l = map(int,raw_input().split())
pos_min = l.index(1)
pos_max = l.index(n)
latter = max(pos_min,pos_max)
former = min(pos_min,pos_max)
if(n-1-latter > former):
latter = n-1
else:
former = 0
print latter-former
|
You have a new professor of graph theory and he speaks very quickly. You come up with the following plan to keep up with his lecture and make notes.
You know two languages, and the professor is giving the lecture in the first one. The words in both languages consist of lowercase English characters, each language consi... | 3 | n,m=map(int,input().split())
d={}
for _ in range(m):
i,j=input().split()
le=len(i)
lj=len(j)
if(le<lj):
d[i]=i
elif(le>lj):
d[i]=j
else:
d[i]=i
string=input().split()
for j in string:
x=d[j]
print(x,end='')
print(" ",end='')
|
We have A apples and P pieces of apple.
We can cut an apple into three pieces of apple, and make one apple pie by simmering two pieces of apple in a pan.
Find the maximum number of apple pies we can make with what we have now.
Constraints
* All values in input are integers.
* 0 \leq A, P \leq 100
Input
Input is g... | 3 | a,p=map(int,input().split())
k=a*3+p
ans=k//2
print(ans) |
Given is a string S. Replace every character in S with `x` and print the result.
Constraints
* S is a string consisting of lowercase English letters.
* The length of S is between 1 and 100 (inclusive).
Input
Input is given from Standard Input in the following format:
S
Output
Replace every character in S with ... | 3 | n=input()
l=len(n)
print('x'*l) |
Toastman came up with a very easy task. He gives it to Appleman, but Appleman doesn't know how to solve it. Can you help him?
Given a n × n checkerboard. Each cell of the board has either character 'x', or character 'o'. Is it true that each cell of the board has even number of adjacent cells with 'o'? Two cells of th... | 3 | n = int(input())
s = ""
for i in range(n):
s += str(input())
if s == s[::-1]:
print("YES")
else:
print("NO")
|
Let's define logical OR as an operation on two logical values (i. e. values that belong to the set {0, 1}) that is equal to 1 if either or both of the logical values is set to 1, otherwise it is 0. We can define logical OR of three or more logical values in the same manner:
<image> where <image> is equal to 1 if some ... | 1 | l=lambda:map(int,raw_input().split())
m, n = l()
table = [ l() for _ in range(m)]
r = [all(row) for row in table]
c = [all(col) for col in zip(*table)]
sum_r=sum(r)
sum_c=sum(c)
for i in range(m):
for j in range(n):
if table[i][j]:
if r[i]+c[j]==0 or sum_r==0 or sum_c==0:
print "... |
The numbers of all offices in the new building of the Tax Office of IT City will have lucky numbers.
Lucky number is a number that consists of digits 7 and 8 only. Find the maximum number of offices in the new building of the Tax Office given that a door-plate can hold a number not longer than n digits.
Input
The on... | 3 | num = input()
num = int(num)
total1 = 0
def ways(n, total):
if n == 0:
return total
total += (2**n)
return ways(n-1, total)
print(ways(num, total1)) |
Pasha loves to send strictly positive integers to his friends. Pasha cares about security, therefore when he wants to send an integer n, he encrypts it in the following way: he picks three integers a, b and c such that l ≤ a,b,c ≤ r, and then he computes the encrypted value m = n ⋅ a + b - c.
Unfortunately, an adversa... | 3 | import sys
inp=sys.stdin.readline
def linp(x):
return list(map(int,x.split()))
def minp(x):
return map(int,x.split())
def main():
t=int(inp())
while t>0:
l,r,m=minp(inp())
ma = r-l
for i in range(l,r+1):
mm = m%i
if m>=i and mm<=ma :
prin... |
In this problem you are to calculate the sum of all integers from 1 to n, but you should take all powers of two with minus in the sum.
For example, for n = 4 the sum is equal to - 1 - 2 + 3 - 4 = - 4, because 1, 2 and 4 are 20, 21 and 22 respectively.
Calculate the answer for t values of n.
Input
The first line of... | 3 | t = int(input())
for i in range(t):
n = int(input())
summ = (n + 1) * (n // 2)
if (n % 2 != 0): summ += (n + 1) // 2
x = 1
while x <= n:
summ -= 2 * x
x *= 2
print(summ)
|
Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.
A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase ha... | 3 | a=[1]
for i in range (2,10000):
b=2**i - 1
ans=b*(b+1)//2
a.append(ans)
t=int(input())
for i in range (0,t):
x=int(input())
for i in range(0,len(a)):
if x - a[i] < 0:
print(i)
break
x-=a[i]
|
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round.
For example, the following numbers are roun... | 3 | t = int(input())
while t:
t -= 1
n= int(input())
ans = []
mul = 1
while n:
x = n%10
n = n//10
if x >0 :
ans.append(x*mul)
mul = mul *10
print(len(ans))
print(*ans) |
There are N+1 towns. The i-th town is being attacked by A_i monsters.
We have N heroes. The i-th hero can defeat monsters attacking the i-th or (i+1)-th town, for a total of at most B_i monsters.
What is the maximum total number of monsters the heroes can cooperate to defeat?
Constraints
* All values in input are i... | 3 | from itertools import tee
R = lambda: map(int, input().split())
input()
(a, b), c = tee(R()), R()
next(b)
r = y = 0
for u, v, w in zip(c, a, b):
x = min(v - y, u)
y = min(w, u - x)
r += x + y
print(r)
|
Lee was cleaning his house for the party when he found a messy string under the carpets. Now he'd like to make it clean accurately and in a stylish way...
The string s he found is a binary string of length n (i. e. string consists only of 0-s and 1-s).
In one move he can choose two consecutive characters s_i and s_{i... | 3 | # cook your dish here
n=int(input())
for _ in range(n):
b=int(input())
a=(input())
k=0
s=""
r=""
for i in range(len(a)):
if(a[i]=="0" and k==0):
s=s+"0"
elif(a[i]=="1"):
k=1
r=r+"1"
elif(a[i]=="0" and k==1):
r="0"
print(... |
The city park of IT City contains n east to west paths and n north to south paths. Each east to west path crosses each north to south path, so there are n2 intersections.
The city funded purchase of five benches. To make it seems that there are many benches it was decided to place them on as many paths as possible. Ob... | 3 | # @author Nayara Souza
# UFCG - Universidade Federal de Campina Grande
# AA - Basico
import math
n = int(input())
b1 = n**2
b2 = (n-1)**2
b3 = (n-2)**2
b4 = (n-3)**2
b5 = (n-4)**2
r = (b1*b2*b3*b4*b5)//math.factorial(5)
print(r)
|
Vanya is managed to enter his favourite site Codehorses. Vanya uses n distinct passwords for sites at all, however he can't remember which one exactly he specified during Codehorses registration.
Vanya will enter passwords in order of non-decreasing their lengths, and he will enter passwords of same length in arbitrar... | 3 | n,k=map(int,input().split())
count=[0]*101
for _ in range(n):
s=input()
count[len(s)]+=1
l=len(input())
Sum=sum(count[:l])
Best=Sum+(Sum//k)*5+1
Sum=Sum+count[l]-1
Worst=Sum+(Sum//k)*5+1
print("%s %s"%(Best,Worst)) |
There is a robot on a coordinate plane. Initially, the robot is located at the point (0, 0). Its path is described as a string s of length n consisting of characters 'L', 'R', 'U', 'D'.
Each of these characters corresponds to some move:
* 'L' (left): means that the robot moves from the point (x, y) to the point (x... | 3 | t = int(input())
for _ in range(t):
n = int(input())
s = input()
cp = [0, 0]
p = []
kp = { "0/0": 0 }
idx = []
for i in range(n):
if s[i] == "L":
cp[0] -= 1
elif s[i] == "R":
cp[0] += 1
elif s[i] == "U":
cp[1] += 1
else :... |
You are given nonnegative integers a and b (a ≤ b), and a positive integer x. Among the integers between a and b, inclusive, how many are divisible by x?
Constraints
* 0 ≤ a ≤ b ≤ 10^{18}
* 1 ≤ x ≤ 10^{18}
Input
The input is given from Standard Input in the following format:
a b x
Output
Print the number of th... | 3 | a,b,n = map(int,input().split())
print(b//n-(a-1)//n)
|
Write a program which manipulates a sequence A = {a1, a2, . . . , an} with the following operations:
* add(i, x): add x to ai.
* getSum(s, t): print the sum of as, as+1,...,at.
Note that the initial values of ai (i = 1, 2, . . . , n) are 0.
Constraints
* 1 ≤ n ≤ 100000
* 1 ≤ q ≤ 100000
* If comi is 0, then 1 ≤ xi... | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
input:
3 5
0 1 1
0 2 2
0 3 3
1 1 2
1 2 2
output:
3
2
"""
import sys
class BinaryIndexedTree(object):
__slots__ = ('length', 'dat')
def __init__(self, n):
"""
Init a BIT with update and find for range sum queries.
"""
self.le... |
Being stuck at home, Ray became extremely bored. To pass time, he asks Lord Omkar to use his time bending power: Infinity Clock! However, Lord Omkar will only listen to mortals who can solve the following problem:
You are given an array a of n integers. You are also given an integer k. Lord Omkar wants you to do k ope... | 3 | t = int(input())
for i in range(t):
n,k = map(int,input().split())
l = list(map(int,input().split()))
if k%2 == 1:
p = max(l)
for j in range(n):
q = l[j]
l[j] = p - q
else:
for num in range(2):
p = max(l)
for j in range(n):
... |
The territory of Berland is represented by a rectangular field n × m in size. The king of Berland lives in the capital, located on the upper left square (1, 1). The lower right square has coordinates (n, m). One day the king decided to travel through the whole country and return back to the capital, having visited ever... | 3 | def inRows():
print(0)
row = 1
column = 1
print(row, column)
while row <= n:
if row % 2 == 1:
column = 2
while column <= m:
print(row, column)
column += 1
else:
column = m
while column >= 2:
... |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | n = int(input())
def c(x):
return min(n - x, x + 1) * 2 - 1
for i in range(n):
m = (n - c(i)) // 2
print('*' * m, end = "")
print('D' * c(i), end = "")
print('*' * m) |
Zookeeper is playing a game. In this game, Zookeeper must use bombs to bomb a string that consists of letters 'A' and 'B'. He can use bombs to bomb a substring which is either "AB" or "BB". When he bombs such a substring, the substring gets deleted from the string and the remaining parts of the string get concatenated.... | 3 | T=int(input())
for _ in range(0,T):
s=input()
n=len(s)
cb=0
ans=0
for i in range(len(s)-1,-1,-1):
if(s[i]=='B'):
cb+=1
else:
if(cb>0):
cb-=1
ans+=2
ans+=cb
if(cb%2!=0):
ans-=1
print(len(s)-ans)
... |
You are given two polynomials:
* P(x) = a0·xn + a1·xn - 1 + ... + an - 1·x + an and
* Q(x) = b0·xm + b1·xm - 1 + ... + bm - 1·x + bm.
Calculate limit <image>.
Input
The first line contains two space-separated integers n and m (0 ≤ n, m ≤ 100) — degrees of polynomials P(x) and Q(x) correspondingly.
The seco... | 3 | from math import gcd
n,m = map(int,input().split())
l1 = list(map(int,input().split()))
l2 = list(map(int,input().split()))
if n<m:
print('0/1')
else:
if n>m:
if (l1[0]<0 and l2[0]<0) or (l1[0]>0 and l2[0]>0):
print('Infinity')
else:
print('-Infinity')
else:
... |
Drazil has many friends. Some of them are happy and some of them are unhappy. Drazil wants to make all his friends become happy. So he invented the following plan.
There are n boys and m girls among his friends. Let's number them from 0 to n - 1 and 0 to m - 1 separately. In i-th day, Drazil invites <image>-th boy and... | 1 | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
if __name__ == '__main__':
n, m = map(int, raw_input().split())
a = set(map(int, raw_input().split())[1:])
b = set(map(int, raw_input().split())[1:])
lcm = 200*n*m
for i in range(lcm):
ia = i % n
ib = i % m
... |
«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 ... | 3 | a,b,c,d,e = map(int,[input() for i in range(5)])
s = set()
for i in range(e+1):
if (i%a==0 or i%b==0 or i%c==0 or i%d==0):s.add(i)
print(len(s)-1) |
Let's say string s has period k if s_i = s_{i + k} for all i from 1 to |s| - k (|s| means length of string s) and k is the minimum positive integer with this property.
Some examples of a period: for s="0101" the period is k=2, for s="0000" the period is k=1, for s="010" the period is k=2, for s="0011" the period is k=... | 3 | t=int(input())
for i in range(t):
b=input()
f=0
k=len(b)
for j in range(k-1):
if b[j]!=b[j+1]:
f=1
break
if f==0:
print(b)
else:
p=["10"]*(k)
print("".join(p))
|
Ayush and Ashish play a game on an unrooted tree consisting of n nodes numbered 1 to n. Players make the following move in turns:
* Select any leaf node in the tree and remove it together with any edge which has this node as one of its endpoints. A leaf node is a node with degree less than or equal to 1.
A tree... | 1 | from sys import stdin
from collections import *
rints = lambda: [int(x) for x in stdin.readline().split()]
class graph:
# initialize graph
def __init__(self, gdict=None):
if gdict is None:
gdict = defaultdict(list)
self.gdict, self.edges, self.l = gdict, [], defaultdict(int)
... |
Phoenix has n coins with weights 2^1, 2^2, ..., 2^n. He knows that n is even.
He wants to split the coins into two piles such that each pile has exactly n/2 coins and the difference of weights between the two piles is minimized. Formally, let a denote the sum of weights in the first pile, and b denote the sum of weigh... | 3 | tc = int(input())
cases = []
for _ in range(tc):
cases.append(int(input()))
for num_coins in cases:
weights = []
for i in range(1, num_coins + 1):
weights.append(2**i)
first_pile = weights[:num_coins//2 - 1]
first_pile.append(weights[-1])
second_pile = weights[(num_coins//2)-1 : -1]
print (sum(first_pile... |
Leha is planning his journey from Moscow to Saratov. He hates trains, so he has decided to get from one city to another by car.
The path from Moscow to Saratov can be represented as a straight line (well, it's not that straight in reality, but in this problem we will consider it to be straight), and the distance betwe... | 3 | n = int(input())
data = list(map(int,input().split()))
answer = 0
prefix_data_sum = 0
prefix_answer_sum = 0
prefix = 0
mod = 998244353
for i in range(n):
prefix+=data[i]
prefix %= mod
answer = (prefix + prefix_data_sum + prefix_answer_sum) % mod
prefix_data_sum *= 2
prefix_data_sum = (prefi... |
The capital of Berland has n multifloor buildings. The architect who built up the capital was very creative, so all the houses were built in one row.
Let's enumerate all the houses from left to right, starting with one. A house is considered to be luxurious if the number of floors in it is strictly greater than in all... | 3 | n = int(input())
houses = [int(x) for x in input().split(' ')]
max_sizes = [0] * n
current_max = 0
for i in reversed(range(n)):
max_sizes[i] = current_max
if houses[i] > current_max:
current_max = houses[i]
for i in range(n):
floors_added = max_sizes[i] - houses[i] + 1
if floors_added < 0:
floors_added = 0
i... |
You are given a problemset consisting of n problems. The difficulty of the i-th problem is a_i. It is guaranteed that all difficulties are distinct and are given in the increasing order.
You have to assemble the contest which consists of some problems of the given problemset. In other words, the contest you have to as... | 3 | #!/usr/bin/python3
n = int(input())
nums = [int(s) for s in input().split(' ')]
max_count = 1
start = 0
while start < n-1:
#print(start)
current = nums[start]
for end in range(start+1, n):
#print(current,start, end)
count = end - start + 1
prev = nums[end-1]
last = nums[end... |
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 Bi... | 3 | n=int(input())
if n<4:
print("No")
else:
if n%2==0:
print("YES")
else:
print("NO") |
Friends are going to play console. They have two joysticks and only one charger for them. Initially first joystick is charged at a1 percent and second one is charged at a2 percent. You can connect charger to a joystick only at the beginning of each minute. In one minute joystick either discharges by 2 percent (if not c... | 3 | a1, a2 = map(int, input().split())
i = 0
while min(a1,a2)>=1 and max(a1,a2) >= 2:
if a1 > a2:
a1, a2 = a1-2, a2+1
else:
a1, a2 = a1+1, a2-2
i += 1
print(i) |
Shubham has an array a of size n, and wants to select exactly x elements from it, such that their sum is odd. These elements do not have to be consecutive. The elements of the array are not guaranteed to be distinct.
Tell him whether he can do so.
Input
The first line of the input contains a single integer t (1≤ t ≤... | 3 | for _ in range(int(input())):
n,k=map(int, input().split())
a=list(map(int, input().split()))
odd=even=0
for i in a:
if i%2==0: even+=1
else: odd+=1
left=max(0,k-even)
if odd==0: print("No")
elif n==k and odd%2==0: print("No")
elif even==0 and k%2==0: print("No")
else: print("Yes") |
Two-gram is an ordered pair (i.e. string of length two) of capital Latin letters. For example, "AZ", "AA", "ZA" — three distinct two-grams.
You are given a string s consisting of n capital Latin letters. Your task is to find any two-gram contained in the given string as a substring (i.e. two consecutive characters of ... | 3 | def count(w, key):
c = 0
for i in range(len(w)-1):
if w[i:i+2]==key:
c += 1
return c
a = {}
n = int(input())
w = input()
for _ in range(n-1):
key = w[_:_+2]
a[key] = count(w, key)
if _ > 0:
if a[p] < a[key]:
p = key
else:
p = key
print(p) |
Limak is going to participate in a contest on the last day of the 2016. The contest will start at 20:00 and will last four hours, exactly until midnight. There will be n problems, sorted by difficulty, i.e. problem 1 is the easiest and problem n is the hardest. Limak knows it will take him 5·i minutes to solve the i-th... | 3 | n,k=map(int,input().split())
k=240-k
x=0
while not((5*(x+1)*x)/2>k):
x+=1
x-=1
if x<=n:
print(x)
else:
print(n) |
A word or a sentence in some language is called a pangram if all the characters of the alphabet of this language appear in it at least once. Pangrams are often used to demonstrate fonts in printing or test the output devices.
You are given a string consisting of lowercase and uppercase Latin letters. Check whether thi... | 3 | a = int(input())
b = input().lower()
def P(b):
c = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
for i in range (26):
for j in range (a):
if c[i] == b[j]:
break
if j == a - 1 and c[i]... |
You found a useless array a of 2n positive integers. You have realized that you actually don't need this array, so you decided to throw out all elements of a.
It could have been an easy task, but it turned out that you should follow some rules:
1. In the beginning, you select any positive integer x.
2. Then you ... | 3 | import math,sys,bisect,heapq
from collections import defaultdict,Counter,deque
from itertools import groupby,accumulate
from functools import lru_cache
#sys.setrecursionlimit(200000000)
int1 = lambda x: int(x) - 1
#def input(): return sys.stdin.readline().strip()
input = iter(sys.stdin.buffer.read().decode().splitlines... |
Twilight Sparkle once got a crystal from the Crystal Mine. A crystal of size n (n is odd; n > 1) is an n × n matrix with a diamond inscribed into it.
You are given an odd integer n. You need to draw a crystal of size n. The diamond cells of the matrix should be represented by character "D". All other cells of the matr... | 3 | n = int(input())
for i in range(n // 2):
print((n - (2 * i + 1)) // 2 * '*' + (1 + 2 * i) * 'D' + (n - (2 * i + 1)) // 2 * '*')
print(n * 'D')
for i in range(n // 2 - 1, -1, -1):
print((n - (2 * i + 1)) // 2 * '*' + (1 + 2 * i) * 'D' + (n - (2 * i + 1)) // 2 * '*')
|
In Berland the opposition is going to arrange mass walking on the boulevard. The boulevard consists of n tiles that are lain in a row and are numbered from 1 to n from right to left. The opposition should start walking on the tile number 1 and the finish on the tile number n. During the walk it is allowed to move from ... | 1 | import sys
sys.setrecursionlimit(100000)
f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin
n = int(f.readline())
a = [int(num) for num in f.readline().split()]
def my_min(seq):
res = sys.maxint
for el in seq:
if el < res:
res = el
return res if res != sys.maxint else 0
def n... |
Input
The input contains a single integer a (1 ≤ a ≤ 30).
Output
Output a single integer.
Example
Input
3
Output
27 | 3 | s = ['4', '22', '27', '58', '85', '94', '121', '166', '202', '265', '274', '319', '346', '355', '378', '382', '391', '438', '454', '483', '517', '526', '535', '562', '576', '588', '627', '634', '636', '645', '648', '654', '663', '666', '690', '706', '728', '729', '762', '778', '825']
print(s[int(input()) - 1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.