problem stringlengths 29 9.39k | language int64 1 3 | solution stringlengths 7 465k |
|---|---|---|
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | #in the name of god
#Mr_Rubik
n=int(input())
s=list(map(int,input().split()))
cnt=mx=1
for i in range (n-1):
if s[i]<=s[i+1]:
cnt+=1
mx=max(cnt,mx)
if s[i]>s[i+1]:
cnt=1
print(mx) |
Ternary numeric notation is quite popular in Berland. To telegraph the ternary number the Borze alphabet is used. Digit 0 is transmitted as «.», 1 as «-.» and 2 as «--». You are to decode the Borze code, i.e. to find out the ternary number given its representation in Borze alphabet.
Input
The first line contains a nu... | 3 | s = str(input())
c = 0
l = []
while c!=len(s):
if s[c] == ".":
l.append(0)
c+=1
else:
if s[c+1] == "-":
l.append(2)
else:
l.append(1)
c+=2
for i in l:
print(i,end = "") |
New Year is coming in Line World! In this world, there are n cells numbered by integers from 1 to n, as a 1 × n board. People live in cells. However, it was hard to move between distinct cells, because of the difficulty of escaping the cell. People wanted to meet people who live in other cells.
So, user tncks0121 has ... | 3 | """
Nombre: New Year Trasnportation
id: 500A
Fuente: codeforces.com
Coder: Cgesu Coder """
n, t = map(int, input().split())
nis = list(map(int, input().split()))
visitar = set()
pos = 0
visitar.add(pos)
while pos < len(nis):
pos += nis[pos]
visitar.add(pos)
print("YES") if t-1 in visitar else p... |
Xenia the mathematician has a sequence consisting of n (n is divisible by 3) positive integers, each of them is at most 7. She wants to split the sequence into groups of three so that for each group of three a, b, c the following conditions held:
* a < b < c;
* a divides b, b divides c.
Naturally, Xenia wants... | 3 | n = int(input())
nums = list(map(int, input().split(" ")))
if 7 in nums or 5 in nums:
print(-1)
exit()
else:
one = nums.count(1)
two = nums.count(2)
three = nums.count(3)
four = nums.count(4)
six = nums.count(6)
if (one == n//3 and two+three == n//3 and four+six == n//3 and four<= two and six>=three):
for i... |
You have two integers l and r. Find an integer x which satisfies the conditions below:
* l ≤ x ≤ r.
* All digits of x are different.
If there are multiple answers, print any of them.
Input
The first line contains two integers l and r (1 ≤ l ≤ r ≤ 10^{5}).
Output
If an answer exists, print any of them. Oth... | 3 | arr = [x for x in input().split()]
l = arr[0]
r = arr[1]
il = int(l)
ir = int(r)
exists = False
ans = -1
for i in range(il,ir+1):
if len(set(str(i))) == len(str(i)):
ans = i
break
print(ans)
|
Takahashi is distributing N balls to K persons.
If each person has to receive at least one ball, what is the maximum possible difference in the number of balls received between the person with the most balls and the person with the fewest balls?
Constraints
* 1 \leq K \leq N \leq 100
* All values in input are intege... | 3 | N, K = map(int, input().split(" "))
if K == 1: print(0)
else: print(N - K) |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 3 | n,k=map(int,input().split())
a=n//2
if(n%2!=0):
a+= 1
if(k<=a):
print(2*k-1)
else:
print(2*(k-a)) |
There is a square painted on a piece of paper, the square's side equals n meters. John Doe draws crosses on the square's perimeter. John paints the first cross in the lower left corner of the square. Then John moves along the square's perimeter in the clockwise direction (first upwards, then to the right, then downward... | 1 | from fractions import *
input()
print '\n'.join(str(4 * n / gcd(4 * n, n + 1) + 1) for n in map(int, raw_input().split())) |
Takahashi and Aoki are playing a stone-taking game. Initially, there are N piles of stones, and the i-th pile contains A_i stones and has an associated integer K_i.
Starting from Takahashi, Takahashi and Aoki take alternate turns to perform the following operation:
* Choose a pile. If the i-th pile is selected and th... | 3 | import sys
input = sys.stdin.readline
N = int(input())
AK = [list(map(int, input().split())) for _ in range(N)]
# N = 40
# AK = [(i+1, 4) for i in range(N)]
def grundy(A, K):
if K == 1:
return A
X = (A+K-1)//K
num = X*K - A
while X*K-num > K*K:
#print(X, num)
if num%K == 0:
... |
In the city of Saint Petersburg, a day lasts for 2^{100} minutes. From the main station of Saint Petersburg, a train departs after 1 minute, 4 minutes, 16 minutes, and so on; in other words, the train departs at time 4^k for each integer k ≥ 0. Team BowWow has arrived at the station at the time s and it is trying to co... | 3 | t = int(input(),2)
tr = 1
count=0
while(True):
if (tr<t):
count+=1
tr*=4
else:
break
print(count)
|
Recently, Anton has found a set. The set consists of small English letters. Anton carefully wrote out all the letters from the set in one line, separated by a comma. He also added an opening curved bracket at the beginning of the line and a closing curved bracket at the end of the line.
Unfortunately, from time to ti... | 3 | s=input()
s=s[1:-1]
count=0
l=list()
s=s.replace(" ","")
s=s.replace(",","")
for i in s:
if i not in l:
count=count+1
l.append(i)
print(count)
|
Young wilderness explorers set off to their first expedition led by senior explorer Russell. Explorers went into a forest, set up a camp and decided to split into groups to explore as much interesting locations as possible. Russell was trying to form groups, but ran into some difficulties...
Most of the young explorer... | 3 | from sys import stdin
from collections import deque
mod = 10**9 + 7
import sys
import random
# sys.setrecursionlimit(10**6)
from queue import PriorityQueue
# def rl():
# return [int(w) for w in stdin.readline().split()]
from bisect import bisect_right
from bisect import bisect_left
from collections import defaultdi... |
You manage 4 buildings, each of which has 3 floors, each of which consists of 10 rooms. Write a program which reads a sequence of tenant/leaver notices, and reports the number of tenants for each room.
For each notice, you are given four integers b, f, r and v which represent that v persons entered to room r of fth fl... | 3 | n = int(input())
y = [[[0 for i in range(10)] for v in range(3)] for k in range(4)]
for i in range(0,n):
b,f,r,v = map(int,input().split(' '))
y[b-1][f-1][r-1] += v
for b in range(4):
for f in y[b]:
print('', *f)
if b != 3:
print('#' * 20)
|
Alice is playing with some stones.
Now there are three numbered heaps of stones. The first of them contains a stones, the second of them contains b stones and the third of them contains c stones.
Each time she can do one of two operations:
1. take one stone from the first heap and two stones from the second heap (... | 3 | t = int(input())
def min(a, b):
if(a < b):
return a
else:
return b
for i in range(t):
times = 0
a, b, c = input().split(' ')
a = int(a)
b = int(b)
c = int(c)
times = min(b, int(c/2))
b = b - times
if(b > 0):
times = times + min(a, int(b/2))
print(t... |
Mad scientist Mike entertains himself by arranging rows of dominoes. He doesn't need dominoes, though: he uses rectangular magnets instead. Each magnet has two poles, positive (a "plus") and negative (a "minus"). If two magnets are put together at a close distance, then the like poles will repel each other and the oppo... | 3 | i = int(input())
magnets = ""
for x in range(i):
magnets += input()
s = 0
s += magnets.count("00") + magnets.count("11") +1
print(s) |
There are N stones, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N), the height of Stone i is h_i.
There is a frog who is initially on Stone 1. He will repeat the following action some number of times to reach Stone N:
* If the frog is currently on Stone i, jump to Stone i + 1 or Stone i + 2. Here, a cost of |... | 3 | N = int(input())
H = list(map(int,input().split()))
C = [0]*N
C[1] = abs(H[0]-H[1])
for i in range(2,N):
C[i] = min(abs(H[i]-H[i-1])+C[i-1],abs(H[i]-H[i-2])+C[i-2])
print(C[-1]) |
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 math
import re
import time
a = input()
if len(re.sub("[^HQ9]", "", a)) == 0:
print("NO")
else:
print("YES") |
Ivan is a student at Berland State University (BSU). There are n days in Berland week, and each of these days Ivan might have some classes at the university.
There are m working hours during each Berland day, and each lesson at the university lasts exactly one hour. If at some day Ivan's first lesson is during i-th ho... | 3 | import sys
n, m, k = map(int, input().split())
table = [input() for _ in range(n)]
dp = [0]*(k+1)
for a in table:
one = []
for i in range(m):
if a[i] == '1':
one.append(i)
if not one:
continue
ni = len(one)
subdp = [10**9] * (ni+1)
subdp[-1] = 0
for i in ran... |
You can not just take the file and send it. When Polycarp trying to send a file in the social network "Codehorses", he encountered an unexpected problem. If the name of the file contains three or more "x" (lowercase Latin letters "x") in a row, the system considers that the file content does not correspond to the socia... | 1 | n=int(raw_input())
a=str(raw_input())
num=0
for i in range(len(a)-2):
if a[i]=='x' and a[i+1]=='x' and a[i+2]=='x':
num+=1
print num
|
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | def read_array():
x = []
x1 = []
x = input()
x = x.split(' ')
for r in range(len(x)):
x1.append(int(x[r]))
return x1
matrix=[]
for r in range(5):
x=read_array()
matrix.append(x)
i_f,j_f=0,0
for i in range(5):
for j in range(5):
if matrix[i][j]==1:
i_f=i
... |
Being a nonconformist, Volodya is displeased with the current state of things, particularly with the order of natural numbers (natural number is positive integer number). He is determined to rearrange them. But there are too many natural numbers, so Volodya decided to start with the first n. He writes down the followin... | 1 | n, k = map(int, raw_input().split());
m = (n >> 1) + (n & 1)
if k <= m:
print k + k - 1
else:
print (k - m) * 2
|
An n × n table a is defined as follows:
* The first row and the first column contain ones, that is: ai, 1 = a1, 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 remaining elements are defin... | 3 | n = int(input())
list1 = []
for i in range(n):
list1.append([])
for j in range(n):
list1[i].append(None)
for i in range(n):
list1[0][i] = 1
for i in range(n):
list1[i][0] = 1
for i in range(1, n):
for j in range(1, n):
list1[i][j] = list1[i-1][j] + list1[i][j-1]
print(list1[i][j]) |
Vanya and his friends are walking along the fence of height h and they do not want the guard to notice them. In order to achieve this the height of each of the friends should not exceed h. If the height of some person is greater than h he can bend down and then he surely won't be noticed by the guard. The height of the... | 3 | n, h = map(int, input().split())
s = tuple(map(int, input().split()))
ans = 0
for a in s:
if a > h:
ans = ans + 2
else:
ans = ans + 1
print(ans) |
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 | d = dict()
n, m = map(int, input().split()) # Читаем количество слов в лекции преподавателя и количество слов в каждом из языков
for i in range(m):
pair = input().split() # Пару слов на 2х языках
d[pair[0]] = pair[1] # Создаём эту пару в словаре
s = input().split() # Читаем лекцию
for word in s:
if l... |
Little Elephant loves magic squares very much.
A magic square is a 3 × 3 table, each cell contains some positive integer. At that the sums of integers in all rows, columns and diagonals of the table are equal. The figure below shows the magic square, the sum of integers in all its rows, columns and diagonals equals 15... | 1 | def MagicSq():
sq = []
for i in range(3):
sq.append(list(map(int,raw_input().split())))
s1 = sum(sq[0])
s2 = sum(sq[1])
s3 = sum(sq[2])
y = (s1+s3-s2)/2
z = s1-y
x = s3-y
sq[0][0] = x
sq[1][1] = y
sq[2][2] = z
for i in sq:
num_str = ''
for j in... |
Ron is a happy owner of a permutation a of length n.
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is... | 3 | for _ in range(int(input())):
n,m=list(map(int,input().split()))
a=list(map(int,input().split()))
exp=[]
for i in range(m):
x=input().split()
exp.append([int(x[0]),float(x[1])])
nm=-1
for i in range(n,0,-1):
if a[i-1]!=i:
nm=i
break
#print("nm"... |
We just discovered a new data structure in our research group: a suffix three!
It's very useful for natural language processing. Given three languages and three suffixes, a suffix three can determine which language a sentence is written in.
It's super simple, 100% accurate, and doesn't involve advanced machine learni... | 3 | t=int(input())
while t>0 :
s=input()
if s.endswith("po"):
print("FILIPINO")
elif s.endswith("desu") or s.endswith("masu"):
print("JAPANESE")
else :
print("KOREAN")
t=t-1
|
Capitalization is writing a word with its first letter as a capital letter. Your task is to capitalize the given word.
Note, that during capitalization all the letters except the first one remains unchanged.
Input
A single line contains a non-empty word. This word consists of lowercase and uppercase English letters.... | 3 | s = input()
b = s[0].upper()+s[1:]
print(b)
|
A telephone number is a sequence of exactly 11 digits such that its first digit is 8.
Vasya and Petya are playing a game. Initially they have a string s of length n (n is odd) consisting of digits. Vasya makes the first move, then players alternate turns. In one move the player must choose a character and erase it fro... | 3 | import math
n=int(input())
s=input()
s=list(map(int,list(s)))
f=(len(s)-11)//2
t=s[:(n-10)]
x=t.count(8)
if f<x:
print("YES")
else:
print("NO") |
Valerian was captured by Shapur. The victory was such a great one that Shapur decided to carve a scene of Valerian's defeat on a mountain. So he had to find the best place to make his victory eternal!
He decided to visit all n cities of Persia to find the best available mountain, but after the recent war he was too ti... | 1 |
n=int(raw_input())
g=[[] for _ in xrange(n)]
s=0
for _ in xrange(n-1):
u,v,w=map(int,raw_input().split())
u-=1
v-=1
g[u].append([v,w])
g[v].append([u,w])
s+=w
def dfs(u,f,x):
ret=x
for v,w in g[u]:
if f!=v:
ret=max(ret,dfs(v,u,w+x))
return ret
print 2*s-dfs(0,-1,0)
|
We have a string S consisting of uppercase English letters. Additionally, an integer N will be given.
Shift each character of S by N in alphabetical order (see below), and print the resulting string.
We assume that `A` follows `Z`. For example, shifting `A` by 2 results in `C` (`A` \to `B` \to `C`), and shifting `Y` ... | 3 | N = int(input())
S = input()
print(*[chr(((ord(s) - ord('A')) + N) % 26 + ord('A')) for s in S], sep='')
|
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-04-13 10:12:57
# @Author : Nathan (15330895@qq.com)
# @Link : ${link}
# @Version : $Id$
# import math
# n = int(input("n:"))
# m = int(input("m:"))
# a = int(input("a:"))
# n,m,a = (int(i) for i in input().split(" "))
c,d,e = input().split(" ")
n=int(... |
E869120 has A 1-yen coins and infinitely many 500-yen coins.
Determine if he can pay exactly N yen using only these coins.
Constraints
* N is an integer between 1 and 10000 (inclusive).
* A is an integer between 0 and 1000 (inclusive).
Input
Input is given from Standard Input in the following format:
N
A
Output... | 1 | n = input()
a = input()
tmp = n % 500
if tmp <= a:
print "Yes"
else:
print "No" |
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 xi coins.
Vasiliy plans to buy his favorite drink fo... | 3 | from bisect import bisect_right as bl
n = int(input())
a = sorted(list(map(int, input().split())))
q = int(input())
for _ in range(q):
m = int(input())
i = bl(a, m)
print(i) |
We have N points numbered 1 to N arranged in a line in this order.
Takahashi decides to make an undirected graph, using these points as the vertices. In the beginning, the graph has no edge. Takahashi will do M operations to add edges in this graph. The i-th operation is as follows:
* The operation uses integers L_i ... | 3 | from heapq import *
N,M=map(int,input().split())
G=[[] for i in range(N)]
for i in range(N-1):
G[i+1].append((i,0))
l,r,c=0,0,0
for i in range(M):
l,r,c=map(int,input().split())
G[l-1].append((r-1,c))
D=[0]*N
INF=10**20
def ijk(s):
global D,INF,G
for i in range(len(G)):
D[i]=INF
D[s]=0
Q=[]
heapify(... |
Your friend has recently learned about coprime numbers. A pair of numbers {a, b} is called coprime if the maximum number that divides both a and b is equal to one.
Your friend often comes up with different statements. He has recently supposed that if the pair (a, b) is coprime and the pair (b, c) is coprime, then the... | 3 | l, r = map(int, input().split(" "))
if (l%2==0 and r-l>=2):
print(l,l+1,l+2)
elif l%2!=0 and r-l>2:
print(l + 1, l + 2,l+3)
else:
print(-1) |
You are given the array a consisting of n positive (greater than zero) integers.
In one move, you can choose two indices i and j (i ≠ j) such that the absolute difference between a_i and a_j is no more than one (|a_i - a_j| ≤ 1) and remove the smallest of these two elements. If two elements are equal, you can remove a... | 3 | t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
arr.sort()
flag=True
for i in range(n-1):
if(abs(arr[i]-arr[i+1])>1):
flag=False
break
else:
flag=True
if(flag):
print('YES')
else:
print('N... |
You've got a 5 × 5 matrix, consisting of 24 zeroes and a single number one. Let's index the matrix rows by numbers from 1 to 5 from top to bottom, let's index the matrix columns by numbers from 1 to 5 from left to right. In one move, you are allowed to apply one of the two following transformations to the matrix:
1.... | 3 | row_1 = [int(i)for i in input().split()]
row_2 = [int(i)for i in input().split()]
row_3 = [int(i)for i in input().split()]
row_4 = [int(i)for i in input().split()]
row_5 = [int(i)for i in input().split()]
row = 0
column = 0
if 1 in row_1:
row = 1
column = row_1.index(1)+1
if 1 in row_2:
row = 2
column =... |
George has recently entered the BSUCP (Berland State University for Cool Programmers). George has a friend Alex who has also entered the university. Now they are moving into a dormitory.
George and Alex want to live in the same room. The dormitory has n rooms in total. At the moment the i-th room has pi people living... | 3 | n=int(input())
ans=0
while n>0:
s=[int(x) for x in input().strip().split()]
free=s[1]-s[0]
if free>=2:
ans+=1
n=n-1
print(ans) |
A string is called bracket sequence if it does not contain any characters other than "(" and ")". A bracket sequence is called regular if it it is possible to obtain correct arithmetic expression by inserting characters "+" and "1" into this sequence. For example, "", "(())" and "()()" are regular bracket sequences; ")... | 3 | a,b,c,d = int(input()),int(input()),int(input()),int(input())
chk = 1
if a==d:
if a==0 and c>0:chk=0
if a!=d:chk=0
print(chk) |
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... | 3 | a=[]
for i in range(3):
a.append(input())
if (a[0][0]!=a[2][2] or a[0][1]!=a[2][1] or a[0][2]!=a[2][0] or a[1][0]!=a[1][2]):
print('NO')
else:
print('YES')
|
Little girl Susie went shopping with her mom and she wondered how to improve service quality.
There are n people in the queue. For each person we know time ti needed to serve him. A person will be disappointed if the time he waits is more than the time needed to serve him. The time a person waits is the total time wh... | 3 | n = int(input())
L = sorted(list(map(int, input().split())))
w = 0
d = 0
for i in range(n):
if w <= L[i]:
w += L[i]
else:
d += 1
continue
print(n-d)
|
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n r... | 3 | n, m = [int(i) for i in input().split()]
def fib(n):
a, b = 1, 1
for i in range(n):
a, b = b, (a + b) % 1000000007
return a
res1 = 2 * (fib(n) + fib(m) - 1) % 1000000007
print(res1)
|
Kefa decided to make some money doing business on the Internet for exactly n days. He knows that on the i-th day (1 ≤ i ≤ n) he makes ai money. Kefa loves progress, that's why he wants to know the length of the maximum non-decreasing subsegment in sequence ai. Let us remind you that the subsegment of the sequence is it... | 3 | n = int(input())
ans = 1
res = 1
a = list(map(int,input().split()))
for i in range(1,n):
if a[i]<a[i-1]:
res=1
else:
res+=1
ans = max(res,ans)
print(ans) |
A matrix of size n × m is called nice, if all rows and columns of the matrix are palindromes. A sequence of integers (a_1, a_2, ... , a_k) is a palindrome, if for any integer i (1 ≤ i ≤ k) the equality a_i = a_{k - i + 1} holds.
Sasha owns a matrix a of size n × m. In one operation he can increase or decrease any numb... | 3 | from collections import deque
from math import ceil
t=int(input())
for T in range(t):
a=[]
n,m=map(int,input().split())
for i in range(n):
a.append(list(map(int,input().split())))
sum=[]
# for i in range((n//2)*(m//2)):
# sum.append([])
for i in range(n//2):
for j in ra... |
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 | s=input()
r=""
for i in s:
if i.isupper():
r+=i.lower()
else:
r+=i
r=r.split('a')
r=''.join(r)
r=r.split('e')
r=''.join(r)
r=r.split('i')
r=''.join(r)
r=r.split('o')
r=''.join(r)
r=r.split('u')
r=''.join(r)
r=r.split('y')
r=''.join(r)
s="."
for i in r:
s+=i
s+="."
print(s[:-1])
|
A permutation of length n is an array consisting of n distinct integers from 1 to n in arbitrary order. For example, [2,3,1,5,4] is a permutation, but [1,2,2] is not a permutation (2 appears twice in the array) and [1,3,4] is also not a permutation (n=3 but there is 4 in the array).
Consider a permutation p of length ... | 3 | def modFact(n, p):
if n >= p:
return 0
result = 1
for i in range(1, n + 1):
result = (result * i) % p
return result
n = int(input())
MOD = 1000000007
x = modFact(n, MOD)
y = pow(2, n-1, MOD)
ans = (x%MOD - y%MOD)%MOD
print(ans) |
In this problem, you should process T testcases.
For each testcase, you are given four integers N, M, A, B.
Calculate \sum_{i = 0}^{N - 1} floor((A \times i + B) / M).
Constraints
* 1 \leq T \leq 100,000
* 1 \leq N, M \leq 10^9
* 0 \leq A, B < M
Input
Input is given from Standard Input in the following format:
... | 3 | import sys
input = lambda : sys.stdin.readline().rstrip()
sys.setrecursionlimit(max(1000, 10**9))
write = lambda x: sys.stdout.write(x+"\n")
t = int(input())
def floor_sum(n,m,a,b):
"""sum(((a*i+b)//m) for i in range(n))
"""
ans = 0
if a>=m:
ans += (n-1)*n*(a//m)//2
a %= m
if b>=m... |
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.
The ... | 3 | a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
total = 0
for i in range(a[0]):
if b[i]+a[1] <=5:
total+=1
print(int(total/3)) |
You are given two integers a and b.
In one move, you can choose some integer k from 1 to 10 and add it to a or subtract it from a. In other words, you choose an integer k ∈ [1; 10] and perform a := a + k or a := a - k. You may use different values of k in different moves.
Your task is to find the minimum number of mo... | 3 | t=int(input())
for i in range(t):
a,b = input().split()
a,b = int(a),int(b)
c = 0
d = abs(a-b)
if(d//10 and d%10):
print((d//10)+1)
if((d//10)==0 and a==b):
print(0)
if((d//10)==0 and a!=b):
print(1)
if(d//10 and not d%10):
print(d//10)
... |
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 |
def solve(n, k):
for i in range (k):
if (n%10 == 0):
n //= 10
else:
n -= 1
return n
n,k = map (int, input().split())
print (solve(n,k)) |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | 3 | from copy import deepcopy as dc
for t in range(int(input())):
n = int(input())
wt = [int(y) for y in input().strip().split()]
lb = max(wt) + min(wt)
f = {}
for i in range(1, n+1): f[i] = wt.count(i)
dn = set()
def go(s):
ff = dc(f)
x = 0
for j in ff:
if (s - j) not in ff: continue
... |
Today is Sid’s birthday and he is very excited about this as he is giving a special birthday party to all his friends. In this party they are going to play a game for which Sid have to arrange all his friends in a row such that no two boys should be present which are adjacent to each other. There are total M girls and ... | 1 | '''
# Read input from stdin and provide input before running code
name = raw_input('What is your name?\n')
print 'Hi, %s.' % name
'''
c = 1000000007
def fact(cache):
cache[0] = 1
for i in range(1, 51+1):
cache[i] = cache[i-1] * i
cache = [i for i in range(0, 55)]
fact(cache)
t = input()
for i in range(0, t):
l =... |
Alice and Bob play a game. They have a binary string s (a string such that each character in it is either 0 or 1). Alice moves first, then Bob, then Alice again, and so on.
During their move, the player can choose any number (not less than one) of consecutive equal characters in s and delete them.
For example, if the... | 3 | for _ in range(int(input())):
s = input()
s = s.split('0')
arr = []
for i in s:
if len(i) > 0:
arr.append(i)
arr.sort()
ans = 0
for i in range(len(arr)-1, -1, -2):
ans += len(arr[i])
print(ans) |
You have probably registered on Internet sites many times. And each time you should enter your invented password. Usually the registration form automatically checks the password's crypt resistance. If the user's password isn't complex enough, a message is displayed. Today your task is to implement such an automatic che... | 1 | def isCorrect(password):
if len(password) < 5:
return False
for seg in [('A', 'Z'), ('a', 'z'), ('1', '9')]:
if sum([1 if ord(c) >= ord(seg[0]) and ord(c) <= ord(seg[1]) else 0 for c in password]) == 0:
return False
return True
print 'Correct' if isCorrect(raw_input()) else 'Too... |
You are given a positive integer x. Find any such 2 positive integers a and b such that GCD(a,b)+LCM(a,b)=x.
As a reminder, GCD(a,b) is the greatest integer that divides both a and b. Similarly, LCM(a,b) is the smallest integer such that both a and b divide it.
It's guaranteed that the solution always exists. If ther... | 3 | cases = int(input())
while cases > 0:
x = int(input())
print(x-1,1)
cases -= 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())
x = 0
for i in range(0, n):
command = str(input())
if "+" in command:
x += 1
else:
x -= 1
print (x) |
Pasha has a wooden stick of some positive integer length n. He wants to perform exactly three cuts to get four parts of the stick. Each part must have some positive integer length and the sum of these lengths will obviously be n.
Pasha likes rectangles but hates squares, so he wonders, how many ways are there to spli... | 1 | n=input()
print 0 if n&1 else n>>2 if n%4 else n/4-1
|
Andrewid the Android is a galaxy-famous detective. He is now investigating a case of frauds who make fake copies of the famous Stolp's gears, puzzles that are as famous as the Rubik's cube once was.
Its most important components are a button and a line of n similar gears. Each gear has n teeth containing all numbers f... | 1 | n=int(input())
ar=map(int,raw_input().split())
tmp=[]
for i in range(n):
tmp.append(i)
flag=False
for i in range(n):
for j in range(n):
if j%2==0:
ar[j]=(ar[j]-1+n)%n
else:
ar[j]=(ar[j]+1)%n
if ar==tmp:
flag=True
break
print "Yes" if flag else "No" |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | n = int(input().strip())
n1 = str(input().strip())
n2 = str(input().strip())
l = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
r = 0
for i in range(n):
s1 = abs(int(n1[i]) - int(n2[i]))
s2 = abs(int(n1[i]) - 0) + abs(int(n2[i]) - 9) + 1
s3 = abs(int(n2[i]) - 0) + abs(int(n1[i]) - 9) + 1
r += min(s1, s2, s3)
print(r) |
There are n people who want to participate in a boat competition. The weight of the i-th participant is w_i. Only teams consisting of two people can participate in this competition. As an organizer, you think that it's fair to allow only teams with the same total weight.
So, if there are k teams (a_1, b_1), (a_2, b_2)... | 3 | for t in range(int(input())):
p = int(input())
w = list(map(int, input().split()))
w.sort()
res = 0
if p > 1:
res = 1
for i in range(p - 2):
for j in range(p - 1, i + 1, -1):
s = w[i] + w[j]
l, r = i + 1, j - 1
res_ij = 1
... |
Scrooge McDuck keeps his most treasured savings in a home safe with a combination lock. Each time he wants to put there the treasures that he's earned fair and square, he has to open the lock.
<image>
The combination lock is represented by n rotating disks with digits from 0 to 9 written on them. Scrooge McDuck has t... | 3 | n=int(input())
x=input()
y=input()
c=0
for i in range(n):
xx=int(x[i])
yy=int(y[i])
a=abs(xx-yy)
b=10-a
m=min(a,b)
c=c+m
print(c)
|
Let's say you are standing on the XY-plane at point (0, 0) and you want to reach point (n, n).
You can move only in two directions:
* to the right, i. e. horizontally and in the direction that increase your x coordinate,
* or up, i. e. vertically and in the direction that increase your y coordinate.
In othe... | 3 | import sys
t = int(sys.stdin.readline())
for _ in range(t):
n = int(sys.stdin.readline())
l = list(map(int, sys.stdin.readline().split()))
right = l[0]
up = l[1]
su = l[1] + l[0]
udone = 1
rdone = 1
low = l[1] * n + l[0] * n
for i in range(2, n):
su += l[i]
if i % 2 =... |
It seems like the year of 2013 came only yesterday. Do you know a curious fact? The year of 2013 is the first year after the old 1987 with only distinct digits.
Now you are suggested to solve the following problem: given a year number, find the minimum year number which is strictly larger than the given one and has on... | 3 | a=int(input())
flag1=0
while flag1==0:
a+=1
dig=[]
dig2=set()
n=a
if n<10:
dig.append(n%10)
n//10
while n//10>0:
dig.append(n%10)
n=n//10
if n//10==0:
dig.append(n)
for i in range(len(dig)):
dig2.add(dig[i])
... |
In a dream Marco met an elderly man with a pair of black glasses. The man told him the key to immortality and then disappeared with the wind of time.
When he woke up, he only remembered that the key was a sequence of positive integers of some length n, but forgot the exact sequence. Let the elements of the sequence be... | 3 | def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
n=int(input())
a=list(map(int,input().split()))
gcd1=a[0]
for i in range(1,n):
gcd1=gcd(gcd1,a[i])
if gcd1 not in a:
print(-1)
else:
s=''
for i in range(n):
s+=str(gcd1) + ' ' + str(a[i]) + ' ' + str(gcd1) + ' '
... |
Theatre Square in the capital city of Berland has a rectangular shape with the size n × m meters. On the occasion of the city's anniversary, a decision was taken to pave the Square with square granite flagstones. Each flagstone is of the size a × a.
What is the least number of flagstones needed to pave the Square? It'... | 3 | import math
a=input().split(' ')
n=int(a[0])
m=int(a[1])
a=int(a[2])
print(math.ceil(n/a)*math.ceil(m/a)) |
Polycarp urgently needs a shovel! He comes to the shop and chooses an appropriate one. The shovel that Policarp chooses is sold for k burles. Assume that there is an unlimited number of such shovels in the shop.
In his pocket Polycarp has an unlimited number of "10-burle coins" and exactly one coin of r burles (1 ≤ r ... | 3 | #===============================================================================================
#importing some useful libraries.
from fractions import Fraction
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from ite... |
Recently Petya walked in the forest and found a magic stick.
Since Petya really likes numbers, the first thing he learned was spells for changing numbers. So far, he knows only two spells that can be applied to a positive integer:
1. If the chosen number a is even, then the spell will turn it into 3a/2;
2. If t... | 3 | n = int(input())
for i in range(n):
x, y = [int(l) for l in input().split()]
if x < y <= 3:
if x == 1:
print('NO')
else:
print('YES')
elif (x <= 3) and y > x:
print('NO')
else:
print('YES') |
While Mahmoud and Ehab were practicing for IOI, they found a problem which name was Longest common subsequence. They solved it, and then Ehab challenged Mahmoud with another problem.
Given two strings a and b, find the length of their longest uncommon subsequence, which is the longest string that is a subsequence of o... | 3 | from sys import stdin
a = stdin.readline().rstrip()
b = stdin.readline().rstrip()
if a == b:
print(-1)
else:
print(max(len(a),len(b)))
|
Misha hacked the Codeforces site. Then he decided to let all the users change their handles. A user can now change his handle any number of times. But each new handle must not be equal to any handle that is already used or that was used at some point.
Misha has a list of handle change requests. After completing the re... | 3 | ii=lambda:int(input())
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
d = {}
for _ in range(ii()):
a,b=input().split()
if a in d:
d[b]=d[a]
del d[a]
else:
d[b]=a
print(len(d))
for k in d:
print(d[k],k)
|
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 | import re
s=input()
if(len(s)<7):
print("NO")
elif(len(s)>7):
ones=re.search(r'\d*1111111\d*',s)
zeroes=re.search(r'\d*0000000\d*',s)
if(ones or zeroes):
print("YES")
else:
print("NO")
|
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points.
As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria:
* At least one participant should get a dip... | 3 | n = int(input())
a = list(map(int, input().split()))
while 0 in a:
a.remove(0)
print(len(set(a))) |
You have a positive integer m and a non-negative integer s. Your task is to find the smallest and the largest of the numbers that have length m and sum of digits s. The required numbers should be non-negative integers written in the decimal base without leading zeroes.
Input
The single line of the input contains a pa... | 3 | from copy import *
m, s = map(int, input().split())
def can(length, total):
return length*9 >= total >= 0
loans = ""
s1 = copy(s)
for i in range(m):
for d in range(10):
if (i > 0 or d > 0 or (m==1 and d==0)) and can(m-i-1, s1-d):
loans += chr(ord('0')+d)
s1 -= d
bre... |
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 ai worms. He labeled all these worms with consecutive integers: worms in first pile are labeled with numbers 1 to a1, worms in second pile are labeled with number... | 3 | # your code goes here
n1=int(input())
var=[int(x) for x in input().split()]
sumvar=sum(var)
li=list()
li.append(0)
index=0
arri=0
sumTillNow=var[0]
cnt=1
for index in range(1,sumvar+1):
if(index<=sumTillNow):
li.append(cnt)
else:
arri+=1
sumTillNow+=var[arri]
cnt+=1
li.append(cnt)
m=int(input())
var2=[int... |
Recently, you found a bot to play "Rock paper scissors" with. Unfortunately, the bot uses quite a simple algorithm to play: he has a string s = s_1 s_2 ... s_{n} of length n where each letter is either R, S or P.
While initializing, the bot is choosing a starting index pos (1 ≤ pos ≤ n), and then it can play any numbe... | 3 | for _ in range(int(input())):
def main():
# n=int(input())
# s = list(map(int,input().split()))
s = input()
x,y,z = s.count('P'),s.count('S'),s.count('R')
if x==max(x,y,z):print('S'*len(s))
elif y==max(x,y,z):print('R'*len(s))
elif z==max(x,y,z):print('P'*len(... |
An integer X is called a Harshad number if X is divisible by f(X), where f(X) is the sum of the digits in X when written in base 10.
Given an integer N, determine whether it is a Harshad number.
Constraints
* 1?N?10^8
* N is an integer.
Input
Input is given from Standard Input in the following format:
N
Output... | 3 | n=input()
print(("No","Yes")[int(n)%sum(map(int,list(n)))==0]) |
Little Pandey is someone who is lazy, and when he's around his best friend GJ, he becomes super lazy. Pandey thinks that he is a Math-wizard, so he picks up a number S and asks GJ to throw him a challenge around that number.
GJ explains Little Pandey a property called nothingness and decides to ask him Q queries bas... | 1 | from fractions import gcd
s, q = map(int, raw_input().split())
allgcd = []
for i in range(q):
t = input()
ans = gcd(s, t)
if ans in allgcd:
print "-1"
else:
print ans
allgcd.append(ans) |
Polycarp and his friends want to visit a new restaurant. The restaurant has n tables arranged along a straight line. People are already sitting at some tables. The tables are numbered from 1 to n in the order from left to right. The state of the restaurant is described by a string of length n which contains characters ... | 3 | from sys import stdin,stdout
from itertools import combinations
from collections import defaultdict,Counter
import math
def listIn():
return list((map(int,stdin.readline().strip().split())))
def stringListIn():
return([x for x in stdin.readline().split()])
def intIn():
return (int(stdin.readline())... |
Tonight is brain dinner night and all zombies will gather together to scarf down some delicious brains. The artful Heidi plans to crash the party, incognito, disguised as one of them. Her objective is to get away with at least one brain, so she can analyze the zombies' mindset back home and gain a strategic advantage.
... | 3 | N = int(input())
print(N // 2 + N % 2) |
You have n gifts and you want to give all of them to children. Of course, you don't want to offend anyone, so all gifts should be equal between each other. The i-th gift consists of a_i candies and b_i oranges.
During one move, you can choose some gift 1 ≤ i ≤ n and do one of the following operations:
* eat exactly... | 3 | import math
from collections import defaultdict
t = int(input())
for _ in range(t):
n = int(input())
a = [int(x) for x in input().split()]
b = [int(x) for x in input().split()]
atmp = sorted(a)
btmp = sorted(b)
moves = 0
amin, bmin = atmp[0], btmp[0]
for x in range(n):
moves += ... |
Pashmak decided to give Parmida a pair of flowers from the garden. There are n flowers in the garden and the i-th of them has a beauty number bi. Parmida is a very strange girl so she doesn't want to have the two most beautiful flowers necessarily. She wants to have those pairs of flowers that their beauty difference i... | 3 | n=int(input())
a=[int(x) for x in input().split()]
a.sort()
a1=a[-1]-a[0]
c1=a.count(a[0])
c2=a.count(a[-1])
if(a1==0):
print(0,(n*(n-1))//2)
else:
print(a1,c1*c2) |
All cities of Lineland are located on the Ox coordinate axis. Thus, each city is associated with its position xi — 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 city (bec... | 1 | n = input()
l = map(int,raw_input().split())
i = 0
for s in l:
if not i:
a = l[-1]-s
b = l[i+1]-s
elif i == n-1:
a = s-l[0]
b = s-l[i-1]
else:
a = max(l[-1]-s,s-l[0])
b = min(l[i+1]-s,s-l[i-1])
print b,a
i+=1 |
You have n coins, each of the same value of 1.
Distribute them into packets such that any amount x (1 ≤ x ≤ n) can be formed using some (possibly one or all) number of these packets.
Each packet may only be used entirely or not used at all. No packet may be used more than once in the formation of the single x, howeve... | 3 | n = int(input())
p = 0
while(n > 0):
n -= pow(2,p)
p += 1
print(p)
|
The new "Die Hard" movie has just been released! There are n people at the cinema box office standing in a huge line. Each of them has a single 100, 50 or 25 ruble bill. A "Die Hard" ticket costs 25 rubles. Can the booking clerk sell a ticket to each person and give the change if he initially has no money and sells the... | 3 | def R(): return map(int, input().split())
def I(): return int(input())
def S(): return str(input())
def L(): return list(R())
from collections import Counter
import math
import sys
from itertools import permutations
n=I()
a=L()
t25=0
t50=0
t100=0
for i in range(n):
if a[i]==25:
t25+=1
if a[i]=... |
Xenia the beginner mathematician is a third year student at elementary school. She is now learning the addition operation.
The teacher has written down the sum of multiple numbers. Pupils should calculate the sum. To make the calculation easier, the sum only contains numbers 1, 2 and 3. Still, that isn't enough for Xe... | 3 | s=input()
f=''
l=s.split('+')
for x in range(len(l)):
l[x]=int(l[x])
l.sort()
for y in range(len(l)):
if y==len(l)-1:
f += str(l[y])
else:
f+=str(l[y])+'+'
print(f) |
Alice guesses the strings that Bob made for her.
At first, Bob came up with the secret string a consisting of lowercase English letters. The string a has a length of 2 or more characters. Then, from string a he builds a new string b and offers Alice the string b so that she can guess the string a.
Bob builds b from a... | 3 | from sys import stdin
def r(): return stdin.readline().strip()
def r_t(tp): return map(tp, r().strip().split())
def r_a(tp): return list(r_t(tp))
def main():
cases = int(r())
for case in range(cases):
t = r()
ans = t[:2]
for i in range(3,len(t),2): ans+=t[i]
print(ans)
main() |
Some dwarves that are finishing the StUDY (State University for Dwarven Youngsters) Bachelor courses, have been told "no genome, no degree". That means that all dwarves should write a thesis on genome. Dwarven genome is far from simple. It is represented by a string that consists of lowercase Latin letters.
Dwarf Mish... | 3 | s, p = str(input()), str(input())
if len(s) != len(p):
print("NO")
else:
index = []
for j in range(len(s)):
if s[j] != p[j]:
index.append(j)
if len(index) > 2:
break
if len(index) == 2:
if s[index[0]] == p[index[1]] and s[index[1]] == p[index[0]]:
... |
Vasya works as a DJ in the best Berland nightclub, and he often uses dubstep music in his performance. Recently, he has decided to take a couple of old songs and make dubstep remixes from them.
Let's assume that a song consists of some number of words. To make the dubstep remix of this song, Vasya inserts a certain nu... | 1 | s = raw_input()
a = s.replace('WUB', ' ')
print a.lstrip() |
On the planet Mars a year lasts exactly n days (there are no leap years on Mars). But Martians have the same weeks as earthlings — 5 work days and then 2 days off. Your task is to determine the minimum possible and the maximum possible number of days off per year on Mars.
Input
The first line of the input contains a ... | 3 | n=int(input())
c=0
c+=int(n/7)*2
n-=int(n/7)*7
# print(n)
if n==0:
print(c,c)
elif n==1:
print(c,c+1)
elif n>=2 and n<=5:
print(c,c+2)
elif n==6:
print(c+1,c+2)
# elif n==7:
# pass
|
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 dista... | 3 |
# coding: utf-8
# In[3]:
n = int(input())
s = input()
idxs = list(map(int, input().split()))
r_flag = -1
l_flag = -1
ans = 10**20
for idx, q in enumerate(s):
if q == 'R':
r_flag = idxs[idx]
else:
l_flag = idxs[idx]
if r_flag != -1:
ans = min(ans, (l_flag - r_flag) // 2)
... |
One way to create a task is to learn from math. You can generate some random math statement or modify some theorems to get something new and build a new task from that.
For example, there is a statement called the "Goldbach's conjecture". It says: "each even number no less than four can be expressed as the sum of two ... | 3 | def simple(n):
a=set()
i=1
while i**2<=n:
if n%i==0:
a.add(i)
a.add(n//i)
i=i+1
if len (a)>2:
return 'Составное'
return 'Простое'
x=int(input())
for i in range(x//2+1):
if simple(i)=='Составное' and simple(x-i)=='Составное':
print(i, x-i)
... |
There are n cows playing poker at a table. For the current betting phase, each player's status is either "ALLIN", "IN", or "FOLDED", and does not change throughout the phase. To increase the suspense, a player whose current status is not "FOLDED" may show his/her hand to the table. However, so as not to affect any bett... | 1 | import sys,math
n=int(sys.stdin.readline())
s=sys.stdin.readline().strip()
if s.count('I')==1:
print 1
elif s.count('I')>1:
print 0
else:
print s.count('A')
|
Petya loves lucky numbers. We all know that lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Unfortunately, not all numbers are lucky. Petya calls a number nearly lucky if the number of lucky d... | 3 | s = input()
def main(s):
c = 0
for e in s:
if e == '4' or e =='7':
c += 1
return c == 4 or c == 7
print('YES' if main(s) else 'NO') |
A soldier wants to buy w bananas in the shop. He has to pay k dollars for the first banana, 2k 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?
Input
The first lin... | 3 | cfb , mtsh, btb =map(int, input().split())
tmtb = 0
for i in range(1,btb+1):
tmtb +=(i * cfb)
if tmtb > mtsh:
print(tmtb - mtsh)
else:
print(0) |
There are N cities numbered 1 through N, and M bidirectional roads numbered 1 through M. Road i connects City A_i and City B_i.
Snuke can perform the following operation zero or more times:
* Choose two distinct cities that are not directly connected by a road, and build a new road between the two cities.
After he... | 3 | class UnionFind:
par = None
def __init__(self, n):
self.par = [0] * n
def root(self, x):
if(self.par[x] == 0):
return x
else:
self.par[x] = self.root(self.par[x])
return self.root(self.par[x])
def unite(self, x, y):
if(self.root(x) != self.root(y)):
self.par[se... |
Panic is rising in the committee for doggo standardization — the puppies of the new brood have been born multi-colored! In total there are 26 possible colors of puppies in the nature and they are denoted by letters from 'a' to 'z' inclusive.
The committee rules strictly prohibit even the smallest diversity between dog... | 3 | a = int(input())
l = input()
mark = [0 for i in range(26)]
for e in l:
mark[ord(e)-97] += 1
flag = False
for e in mark:
if(e > 1):
flag = True
if(flag or a == 1):
print("Yes")
else:
print("No")
|
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the n... | 1 | a = input()
str1 = ""
for i in range(1, a + 1):
str1 += "%s " % i
str1 = str1.strip()
str2 = ""
for i in range(1, (a - 5) + 1):
str2 += "%s " % i
str2 = str2.strip()
str3 = str1.replace(str2, '')
str3 = str3.strip()
list1 = str3.split(' ')
delim = 1
for i in list1:
delim *= int(i)
result = delim / (1*2*3*4*... |
Once upon a time there were several little pigs and several wolves on a two-dimensional grid of size n × m. Each cell in this grid was either empty, containing one little pig, or containing one wolf.
A little pig and a wolf are adjacent if the cells that they are located at share a side. The little pigs are afraid of ... | 3 | n,m=map(int,input().split())
b=['']*(m)
c=0
for i in range(n):
a=input()
for i in range(a.count("PW")):
a=a.replace("PW","..")
c+=1
for i in range(a.count('WP')):
a=a.replace("WP","..")
c+=1
for i in range(m):
b[i]+=a[i]
for i in range(m):
for j in range(b[i]... |
Gildong is playing a video game called Block Adventure. In Block Adventure, there are n columns of blocks in a row, and the columns are numbered from 1 to n. All blocks have equal heights. The height of the i-th column is represented as h_i, which is the number of blocks stacked in the i-th column.
Gildong plays the g... | 3 | t=int(input())
f=[]
for i in range(t):
n,m,k=map(int,input().split())
h=list(map(int,input().split()))
ans='YES'
for j in range(n-1):
m+=min(k+h[j]-h[j+1],h[j])
if m<0:
ans='NO'
break
f+=[ans]
for i in f:
print(i) |
There are n stones on the table in a row, each of them can be red, green or blue. Count the minimum number of stones to take from the table so that any two neighboring stones had different colors. Stones in a row are considered neighboring if there are no other stones between them.
Input
The first line contains integ... | 3 | n = int(input(''))
sequence = list(input(''))
if n == 1:
print (0)
else:
for i in range (len(sequence)-1):
if sequence[i] == sequence [i+1]:
sequence[i] = 'D'
if sequence[-2] == sequence [-1]:
sequence[-1] = 'D'
output = [i for i in sequence if i == 'D']
print (len(output... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.