problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
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
t=input() k=input() t=t.lower() k=k.lower() f=0 for i in range(len(t)): if ord(t[i])==ord(k[i]): continue if ord(t[i])<ord(k[i]): f=-1 break if ord(t[i])>ord(k[i]): f=1 break print(f)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
number = int(input()) counter = 0 for i in range(number): a, b, c = map(int, input().split()) if a + b + c >= 2: counter += 1 print(counter)
Gennady owns a small hotel in the countryside where he lives a peaceful life. He loves to take long walks, watch sunsets and play cards with tourists staying in his hotel. His favorite game is called "Mau-Mau". To play Mau-Mau, you need a pack of 52 cards. Each card has a suit (Diamonds β€” D, Clubs β€” C, Spades β€” S, or ...
1
from sys import stdin as inp table = list(inp.readline()[:-1]) hand = list(inp.readline()[:-1]) hand = [hand[i] for i in range(len(hand)) if (i+1)%3 != 0] if (table[0] in hand or table[1] in hand): print('YES') else: print('NO')
You are given an array a[0 … n-1] of length n which consists of non-negative integers. Note that array indices start from zero. An array is called good if the parity of each index matches the parity of the element at that index. More formally, an array is good if for all i (0 ≀ i ≀ n - 1) the equality i mod 2 = a[i] m...
1
for _ in range(input()): n = input() ; a = map(int, raw_input().split()) a = [x%2 for x in a] b = a[0::2] ; c = a[1::2] m =(b.count(1)+c.count(0)) if len(a)%2==1 and a.count(0) != n/2+1: print -1 elif len(a)%2==0 and a.count(0) != n/2: print -1 else: print [m/2,m/2 +1 ][m%2!=0]
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you." <image> The problem is:...
1
y=list(raw_input()) res=1 for i in y: res=2*res+(1 if i=='7' else 0) print res-1
Translator's note: in Russia's most widespread grading system, there are four grades: 5, 4, 3, 2, the higher the better, roughly corresponding to A, B, C and F respectively in American grading system. The term is coming to an end and students start thinking about their grades. Today, a professor told his students that...
3
n = int(input().strip()) a= [int(_) for _ in input().strip().split()] count=0 while (round(sum(a)/n + 0.00000001))!= 5: count+=1 a[a.index(min(a))]= 5 print(count)
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
s = input().split() m, n = int(s[0]), int(s[1]) print(m*n//2)
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 n,m,a=map(int,input().split()) if n<=a and m<=a: print(1) elif n<=a and m>=a: print(math.ceil(m/a)) elif m<=a and n>=a: print(math.ceil(n/a)) else: print(math.ceil(n/a)*math.ceil(m/a))
Vitya has just started learning Berlanese language. It is known that Berlanese uses the Latin alphabet. Vowel letters are "a", "o", "u", "i", and "e". Other letters are consonant. In Berlanese, there has to be a vowel after every consonant, but there can be any letter after any vowel. The only exception is a consonant...
3
s = input() p = "bcdfghjklmpqrstvwxyz" q = ['a','e','i','o','u'] f = 1 for i in range(len(s)-1): if s[i] in p and s[i+1] not in q: f = 0 break if s[len(s)-1] in p: f = 0 if f == 0: print("NO") elif f == 1: print("YES")
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
import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.wri...
Nowadays the one-way traffic is introduced all over the world in order to improve driving safety and reduce traffic jams. The government of Berland decided to keep up with new trends. Formerly all n cities of Berland were connected by n two-way roads in the ring, i. e. each city was connected directly to exactly two ot...
3
def find_next_path(cont, n, path, ind): for i in range(n): if cont[ind][i] != 0 and i not in path or \ cont[i][ind] != 0 and i not in path: return i return -1 n = int(input()) cont = [[0] * n for i in range(n)] for i in range(n): a, b, price = [int(item) for item in ...
Happy new year! The year 2020 is also known as Year Gyeongja (κ²½μžλ…„, gyeongja-nyeon) in Korea. Where did the name come from? Let's briefly look at the Gapja system, which is traditionally used in Korea to name the years. There are two sequences of n strings s_1, s_2, s_3, …, s_{n} and m strings t_1, t_2, t_3, …, t_{m}. ...
3
n,m = map(int, input().split()) a = [i for i in input().split()] b = [i for i in input().split()] q = int(input()) while q: y = int(input()) j = y - (y//n)*n k = y - (y//m)*m print(a[j-1]+b[k-1]) q-=1
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
3
friends = ['Danil', 'Olya', 'Slava', 'Ann', 'Nikita'] s = input() i = 0 for friend in friends: i += s.count(friend) print('YES' if i == 1 else 'NO')
Imagine that you have a twin brother or sister. Having another person that looks exactly like you seems very unusual. It's hard to say if having something of an alter ego is good or bad. And if you do have a twin, then you very well know what it's like. Now let's imagine a typical morning in your family. You haven't w...
1
class Twins: def solve(self, num, coingrp): if len(coingrp)<2:return len(coingrp) for x in range(0, len(coingrp)): if sum(coingrp[0:x+1])>sum(coingrp[x+1:]): return x+1 if __name__ == "__main__": number = int(raw_input()) coins = sorted(map(int, raw_input().spli...
Find the number of integers between 1 and K (inclusive) satisfying the following condition, modulo 10^9 + 7: * The sum of the digits in base ten is a multiple of D. Constraints * All values in input are integers. * 1 \leq K < 10^{10000} * 1 \leq D \leq 100 Input Input is given from Standard Input in the following ...
3
def solve(K, D): N = len(K) MOD = 1_000_000_007 dp = [[[0] * D for _ in range(2)] for _ in range(N + 1)] dp[0][0][0] = 1 for i in range(N): for is_less in range(2): for k in range(D): for l in range(10 if is_less else K[i] + 1): is_less_ = is_l...
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Petya calls a number almost lucky if it could be evenly divided by some lucky number. Help him find ...
1
s=input() if '4' in list(str(s)) and '7' in list(str(s)) and len(set(str(s)))==2: print 'YES' exit() elif (s/4>0 and s%4==0) or (s/7>0 and s%7==0)or (s/44>0 and s%44==0)or (s/47>0 and s%47==0)or (s/74>0 and s%74==0)or (s/77>0 and s%77==0)or (s/444>0 and s%444==0)or (s/447>0 and s%447==0)or (s/477>0 and s%477==0...
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
eq = input() eq2 = eq.replace('+', '') testlist = [] fn ='' for x in eq2: testlist.append(int(x)) tl2=sorted(testlist) for y in tl2: fn+=str(y) + '+' fn = fn[:-1] print(fn)
Tavak and Seyyed are good friends. Seyyed is very funny and he told Tavak to solve the following problem instead of longest-path. You are given l and r. For all integers from l to r, inclusive, we wrote down all of their integer divisors except 1. Find the integer that we wrote down the maximum number of times. Solve...
1
a, b = raw_input().split() print a if a == b else 2
In Berland a money reform is being prepared. New coins are being introduced. After long economic calculations was decided that the most expensive coin should possess the denomination of exactly n Berland dollars. Also the following restriction has been introduced for comfort: the denomination of each coin should be div...
3
# if __name__ == '__main__': # list=[] # flag=False # for i in range(2,1001): # for item in range(2,i): # if i%item==0: # flag=True # if not flag: # #ε°†ζ‰Ύεˆ°ηš„θ΄¨ζ•°ζ·»εŠ εˆ°εˆ—θ‘¨ι‡Œ # list.append(i) # flag=False # #打印输出 # numbers=','.join(...
Alexander is a well-known programmer. Today he decided to finally go out and play football, but with the first hit he left a dent on the new Rolls-Royce of the wealthy businessman Big Vova. Vladimir has recently opened a store on the popular online marketplace "Zmey-Gorynych", and offers Alex a job: if he shows his pro...
3
from collections import defaultdict import math t = int(input()) for _ in range(t): n = int(input()) l = list(map(int,input().split())) dic = defaultdict(lambda:0) for i in range(n): dic[l[i]]+=1 ans = [max(l)] GCD = max(l) dic[max(l)]-=1 prev_gcd = GCD for i in range(n-1): ...
Let's call a string good if and only if it consists of only two types of letters β€” 'a' and 'b' and every two consecutive letters are distinct. For example "baba" and "aba" are good strings and "abb" is a bad string. You have a strings "a", b strings "b" and c strings "ab". You want to choose some subset of these strin...
3
n = list(map(int,input().split())) a = n[0] b = n[1] c = n[2] MinAB = 0 if (abs(a-b)>=2): MinAB = min(a,b) if (MinAB!=0): print(MinAB + (MinAB+1) + c*2) else: print(a + b + c*2)
You are given a board of size n Γ— n, where n is odd (not divisible by 2). Initially, each cell of the board contains one figure. In one move, you can select exactly one figure presented in some cell and move it to one of the cells sharing a side or a corner with the current cell, i.e. from the cell (i, j) you can move...
3
for t in range(int(input())): n = int(input()) result = 0 for i in range(1, n//2+1): result += i*i print(8*result)
Two players decided to play one interesting card game. There is a deck of n cards, with values from 1 to n. The values of cards are pairwise different (this means that no two different cards have equal values). At the beginning of the game, the deck is completely distributed between players such that each player has a...
3
for _ in [0]*int(input()): n, k1, k2 = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) print("YES" if max(a) > max(b) else "NO")
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
t = int(input()) for i in range(t): n = int(input()) nums = [] for j in range(1,n+1): nums.append(2**j) sum1 = nums[n-1] sum2 = 0 c = 0 for j in range(int(n/2)-1): sum1 += nums[j] c += 1 for j in range(c,n-1): sum2 += nums[j] print(abs(sum1-sum2)) ...
Having learned the multiplication table, Takahashi can multiply two integers between 1 and 9 (inclusive) together. He cannot do any other calculation. Given are two integers A and B. If Takahashi can calculate A \times B, print the result; if he cannot, print `-1` instead. Constraints * 1 \leq A \leq 20 * 1 \leq B ...
3
a,b = map(int, input().split()) print(a*b if (a<=9)&(b<=9) else -1)
You are policeman and you are playing a game with Slavik. The game is turn-based and each turn consists of two phases. During the first phase you make your move and during the second phase Slavik makes his move. There are n doors, the i-th door initially has durability equal to a_i. During your move you can try to br...
3
n,x,y = input().split(' ') n = int(n) x = int(x) y = int(y) doors = input().split(' ') doors_sum = 0 for i in doors: doors_sum += int(i) if y >= x: cnt = 0 for i in doors: if int(i) <= x: cnt+=1 if cnt % 2 == 0: print(int(cnt/2)) else: print(int(cnt...
One day Alex was creating a contest about his friends, but accidentally deleted it. Fortunately, all the problems were saved, but now he needs to find them among other problems. But there are too many problems, to do it manually. Alex asks you to write a program, which will determine if a problem is from this contest ...
3
s = input() import sys ans = 0 names = ["Danil", "Olya", "Slava", "Ann", "Nikita"] for item in names: ans += s.count(item) if(ans == 1): print("yes") else: print("no")
One day Vasya the Hipster decided to count how many socks he had. It turned out that he had a red socks and b blue socks. According to the latest fashion, hipsters should wear the socks of different colors: a red one on the left foot, a blue one on the right foot. Every day Vasya puts on new socks in the morning and ...
1
a, b = map(int, raw_input().split()) print min(a,b), A = a - min(a,b) B = b - min(a,b) x = max(A,B) print x/2
A new e-mail service "Berlandesk" is going to be opened in Berland in the near future. The site administration wants to launch their project as soon as possible, that's why they ask you to help. You're suggested to implement the prototype of site registration system. The system should work on the following principle. ...
3
n=int(input()) d={} for _ in range(n): name=input() if(name not in d): d[name]=1 print("OK") else: print(name+str(d[name])) d[name]+=1
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on al...
3
from collections import defaultdict,deque import sys,heapq,bisect,math,itertools,string,queue,copy,time sys.setrecursionlimit(10**8) INF = float('inf') mod = 10**9+7 eps = 10**-7 def inp(): return int(input()) def inpl(): return list(map(int, input().split())) def inpl_str(): return list(input().split()) N = inp() cnt...
A guy named Vasya attends the final grade of a high school. One day Vasya decided to watch a match of his favorite hockey team. And, as the boy loves hockey very much, even more than physics, he forgot to do the homework. Specifically, he forgot to complete his physics tasks. Next day the teacher got very angry at Vasy...
3
n = int(input()) v_res = [0, 0, 0] for i in range(n): v = [int(x) for x in input().split()] for j in range(3): v_res[j] += v[j] res = list(filter(lambda x: x == 0, v_res)) if len(res) == 3: print('YES') else: print('NO')
There are quite a lot of ways to have fun with inflatable balloons. For example, you can fill them with water and see what happens. Grigory and Andrew have the same opinion. So, once upon a time, they went to the shop and bought n packets with inflatable balloons, where i-th of them has exactly a_i balloons inside. T...
3
n = int(input()) a = list(map(int, input().split())) if n == 1: print(-1) elif n == 2: if a[0] != a[1]: print(1) print(a.index(max(a)) + 1) else: print(-1) else: b = a.copy() b.remove(min(b)) b.sort() print(len(b)) for i in b: print(a.index(i) + 1, end=" "...
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
t = int(input()) while(t): t-=1 n = int(input()) A = [i for i in map(int, input().strip().split())] A.sort() i = 0 ans = 1 while(i<n): if(A[i]<=i+1): check = True else: check = False if(check): ans = i+2 i+=1 print(ans) ...
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
n, m, a = map(int, input().split()) if n%a == 0: ans1 = n/a else: ans1 = n//a+1 if m%a == 0: ans2 = m/a else: ans2 = m//a+1 ans = int(ans1*ans2) print(ans)
Polycarpus loves hamburgers very much. He especially adores the hamburgers he makes with his own hands. Polycarpus thinks that there are only three decent ingredients to make hamburgers from: a bread, sausage and cheese. He writes down the recipe of his favorite "Le Hamburger de Polycarpus" as a string of letters 'B' (...
1
def f(x): return max(0,b*x - nb)*pb + max(0,x*s - ns)*ps + max(0,x*c - nc)*pc <= m st = raw_input() b = st.count('B') s = st.count('S') c = st.count('C') nb,ns,nc = map(int,raw_input().split()) pb,ps,pc = map(int,raw_input().split()) m = int(raw_input()) lo = 0; hi = 10**13; mid = 0; while(lo < hi): mid = (lo+hi+...
Vasya is choosing a laptop. The shop has n laptops to all tastes. Vasya is interested in the following properties: processor speed, ram and hdd. Vasya is a programmer and not a gamer which is why he is not interested in all other properties. If all three properties of a laptop are strictly less than those properties ...
1
n = int(raw_input()) specs = [] for i in range(n): specs.append([int(i) for i in raw_input().split()]) for i in range(n): for j in range(n): if specs[i][0] > specs[j][0] and \ specs[i][1] > specs[j][1] and specs[i][2] > specs[j][2]: specs[j][3] = 9999 prices = [specs[i][3] ...
Ashish has n elements arranged in a line. These elements are represented by two integers a_i β€” the value of the element and b_i β€” the type of the element (there are only two possible types: 0 and 1). He wants to sort the elements in non-decreasing values of a_i. He can perform the following operation any number of t...
3
# Author: S Mahesh Raju # Username: maheshraju2020 # Date: 07/06/2020 from sys import stdin,stdout from math import gcd, ceil, sqrt ii1 = lambda: int(stdin.readline().strip()) is1 = lambda: stdin.readline().strip() iia = lambda: list(map(int, stdin.readline().strip().split())) isa = lambda: stdin.readline().strip().sp...
Given are integers A, B, and N. Find the maximum possible value of floor(Ax/B) - A Γ— floor(x/B) for a non-negative integer x not greater than N. Here floor(t) denotes the greatest integer not greater than the real number t. Constraints * 1 ≀ A ≀ 10^{6} * 1 ≀ B ≀ 10^{12} * 1 ≀ N ≀ 10^{12} * All values in input are i...
3
A,B,N = map(int, input().split()) x = min(B-1,N) ans = (A*x)//B print(ans)
This is the easier version of the problem. In this version 1 ≀ n, m ≀ 100. You can hack this problem only if you solve and lock both problems. You are given a sequence of integers a=[a_1,a_2,...,a_n] of length n. Its subsequence is obtained by removing zero or more elements from the sequence a (they do not necessarily...
3
n = int(input()) a = input().split() for i in range(n): a[i] = int(a[i]) a_sorted = sorted(a, reverse = True) m = int(input()) r = [] for _ in range(m): b = [] k, pos = input().split() k = int(k) pos = int(pos) - 1 for i in range(n - 1, -1 , -1): if a[i] > a_sorted[k - 1]: b....
Karen is getting ready for a new school day! <image> It is currently hh:mm, given in a 24-hour format. As you know, Karen loves palindromes, and she believes that it is good luck to wake up when the time is a palindrome. What is the minimum number of minutes she should sleep, such that, when she wakes up, the time i...
1
st=str(raw_input()) h=st[0:2] m=st[3:5] h=int(h) m=int(m) c=0 def peldd(a,b): a=str(a) b=str(b) if(len(a)==1): a="0"+a if(len(b)==1): b="0"+b if(a[1]==b[0] and b[1]==a[0]): return 1 else: return 0 for i in range(0,10000): if peldd(h,m): print c ...
Easy and hard versions are actually different problems, so read statements of both problems completely and carefully. Summer vacation has started so Alice and Bob want to play and joy, but... Their mom doesn't think so. She says that they have to read some amount of books before all entertainments. Alice and Bob will ...
3
def solution(): s = input().split() n = int(s[0]) k = int(s[1]) yyLike = [] xqLike = [] bothLike = [] s = 0 for i in range(n): line = input().split() cost = int(line[0]) if line[1] == '1' and line[2] == '1': bothLike.append(cost) elif line[1] ...
Student Valera is an undergraduate student at the University. His end of term exams are approaching and he is to pass exactly n exams. Valera is a smart guy, so he will be able to pass any exam he takes on his first try. Besides, he can take several exams on one day, and in any order. According to the schedule, a stud...
3
import math import random import itertools import collections import sys import time import fractions import os import functools import bisect def timer(f): def tmp(*args, **kwargs): t = time.time() res = f(*args, **kwargs) print("ВрСмя выполнСния Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ: %f" % (time.time()-t)) re...
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
# import sys # sys.stdin = open("test.txt", 'r') t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) c = {} p = a[0] for v in a: if v not in c: c[v] = 1 else: c[v] += 1 if c[v] > 1 and v != p or c[v] == 3: ...
This is the easy version of the problem. The difference between the versions is in the number of possible operations that can be made. You can make hacks if and only if you solved both versions of the problem. You are given a binary table of size n Γ— m. This table consists of symbols 0 and 1. You can make such operat...
3
for _ in range(int(input())): m, n = map(int, input().split()) A = [[0] * (n + 1)] + [[0] + list(map(int, list(input()))) for _ in range(m)] ans = [] for i in range(1, m - 1): for j in range(1, n + 1): if A[i][j]: ans.append([i, j, i + 1, j, i + 1, j + 1 if j < n else...
You found a mysterious function f. The function takes two strings s1 and s2. These strings must consist only of lowercase English letters, and must be the same length. The output of the function f is another string of the same length. The i-th character of the output is equal to the minimum of the i-th character of s1...
3
s1, s2 = input(), input() ret = '' for i in range(len(s1)): if s1[i] < s2[i]: ret = -1 break elif s1[i] > s2[i]: ret += s2[i] elif s1[i] == s2[i]: ret += 'z' print(ret)
Takahashi has N balls. Initially, an integer A_i is written on the i-th ball. He would like to rewrite the integer on some balls so that there are at most K different integers written on the N balls. Find the minimum number of balls that Takahashi needs to rewrite the integers on them. Constraints * 1 \leq K \leq N...
3
import collections n,k = map(int,input().split()) a = list(map(int,input().split())) l = collections.Counter(a) l = list(l.values()) l.sort(reverse = True) print(sum(l[k:]))
The School β„–0 of the capital of Berland has n children studying in it. All the children in this school are gifted: some of them are good at programming, some are good at maths, others are good at PE (Physical Education). Hence, for each child we know value ti: * ti = 1, if the i-th child is good at programming, *...
3
n=int(input()) m=list(map(int,input().split())) l = (min(m.count(1),m.count(2),m.count(3))) print(l) d=0 j=n for i in range(l): a = 0 b = 0 c = 0 p=1 while(p): if(a==0 and m[d%j]==1 ): a= d%j +1 m[d%j] = 0 d=d+1 if( b==0 and m[d%j]==2 ): ...
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...
3
n,m=map(int,input().split()) x=[int(i) for i in input().split()] y=[int(i) for i in input().split()] b=x[0] x=x[1:] g=y[0] y=y[1:] happyb=[0]*n happyg=[0]*m for i in x: happyb[i]=1 for i in y: happyg[i]=1 for i in range(100000): if happyb[i%n] or happyg[i%m]: happyb[i%n]=1 happyg[i%m]=1...
Alex doesn't like boredom. That's why whenever he gets bored, he comes up with games. One long winter evening he came up with a game and decided to play it. Given a sequence a consisting of n integers. The player can make several steps. In a single step he can choose an element of the sequence (let's denote it ak) and...
3
input() N = 100005 m = [0] * N for i in map(int, input().split(' ')): m[i] += 1 for i in range(2, N): m[i] = max(m[i - 1], m[i - 2] + m[i] * i) print(m[N - 1])
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
import queue def inp(): return map(int, input().split(' ')) if __name__ == '__main__': # int # n = in (), k = in (); # for (int i = 0; i < n; i ++) # { # string # s; # cin >> s; # cnt[s.size()] + +; # } # string # pass; # cin >> # pass; # int # maxi...
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() s=s.lower() ss="" for i in range(len(s)): if s[i]=='a' or s[i]== 'o'or s[i]=='y' or s[i]== 'e'or s[i]=='u' or s[i]== 'i': continue ss=ss+'.'+s[i] print(ss)
Johnny has recently found an ancient, broken computer. The machine has only one register, which allows one to put in there one variable. Then in one operation, you can shift its bits left or right by at most three positions. The right shift is forbidden if it cuts off some ones. So, in fact, in one operation, you can m...
3
import sys input = sys.stdin.readline def getInt(): return int(input()) def getVars(): return map(int, input().split()) def getList(): return list(map(int, input().split())) def getStr(): return input().strip() ## ------------------------------- t = getInt() for _ in range(t): a, b = getVars() if(a == b): ...
You start with the number 0 and you want to reach the number N. You can change the number, paying a certain amount of coins, with the following operations: * Multiply the number by 2, paying A coins. * Multiply the number by 3, paying B coins. * Multiply the number by 5, paying C coins. * Increase or decrease the num...
3
from functools import lru_cache import sys sys.setrecursionlimit(10**6) T = int(input()) for _ in range(T): N, A, B, C, D = map(int, input().split()) @lru_cache(maxsize=None) def solve(n): if n == 1: return D res = n * D for v, c in zip([2, 3, 5], [A, B, C]): ...
When preparing a tournament, Codeforces coordinators try treir best to make the first problem as easy as possible. This time the coordinator had chosen some problem and asked n people about their opinions. Each person answered whether this problem is easy or hard. If at least one of these n people has answered that th...
3
n = int(input()) s = list(int(num) for num in input().strip().split())[:n] if 1 in s: print("HARD") else: print("EASY")
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
#!/usr/bin/env python3 s = input() for c in s: if not(c in 'aeioyuAEIOYU'): print('.'+c.lower(), end = '') print()
You are given an integer n. In one move, you can either multiply n by two or divide n by 6 (if it is divisible by 6 without the remainder). Your task is to find the minimum number of moves needed to obtain 1 from n or determine if it's impossible to do that. You have to answer t independent test cases. Input The fi...
3
t =int(input()) for test in range(t): n = int(input()) twos = 0 while n%2 == 0: n//=2 twos+=1 tris = 0 while n%3 == 0: n//=3 tris+=1 if n != 1 or twos>tris: print(-1) else: print(tris+tris-twos)
Given are strings S and T. Consider changing S to T by repeating the operation below. Find the minimum number of operations required to do so. Operation: Choose one character of S and replace it with a different character. Constraints * S and T have lengths between 1 and 2\times 10^5 (inclusive). * S and T consists ...
3
S = input() T = input() print(sum([x!=y for x,y in zip(S,T)]))
You are given n strings s_1, s_2, …, s_n consisting of lowercase Latin letters. In one operation you can remove a character from a string s_i and insert it to an arbitrary position in a string s_j (j may be equal to i). You may perform this operation any number of times. Is it possible to make all n strings equal? In...
3
from collections import Counter t = int(input()) for _ in range(t): n = int(input()) arr = [] for _ in range(n): s = input() for x in s: arr.append(x) c = Counter(arr) if all([x % n == 0 for x in list(c.values())]): print("YES") else: print("NO")
Polycarpus has a ribbon, its length is n. He wants to cut the ribbon in a way that fulfils the following two conditions: * After the cutting each ribbon piece should have length a, b or c. * After the cutting the number of ribbon pieces should be maximum. Help Polycarpus and find the number of ribbon pieces ...
1
input = raw_input().split() cuts = [] n = int(input[0]) a = int(input[1]) cuts.append(a) b = int(input[2]) cuts.append(b) c = int(input[3]) cuts.append(c) maximum_cuts = [] for z in range(0, 4001): maximum_cuts.append(0) for i in range(0, n+1): maximum_cuts[i] = -100000 cuts.sort(key=int) maximum_cuts[0] = 0 maxi...
There are N observatories in AtCoder Hill, called Obs. 1, Obs. 2, ..., Obs. N. The elevation of Obs. i is H_i. There are also M roads, each connecting two different observatories. Road j connects Obs. A_j and Obs. B_j. Obs. i is said to be good when its elevation is higher than those of all observatories that can be r...
3
N,M=map(int,input().split()) H=list(map(int,input().split())) A=[1]*N for i in range(M): a,b=map(int,input().split()) if H[a-1]<=H[b-1]: A[a-1]-=A[a-1] if H[a-1]>=H[b-1]: A[b-1]-=A[b-1] print(sum(A))
Roma (a popular Russian name that means 'Roman') loves the Little Lvov Elephant's lucky numbers. Let us remind you that lucky numbers are positive integers whose decimal representation only contains lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not. Roma's got n positive integers....
3
n,k=map(int,input().split()) l=list(map(int,input().split())) c,c1=0,0 for i in range(n): s=str(l[i]) c=s.count('4')+s.count('7') if c<=k: c1+=1 print(c1)
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 = input() result = "" i = 0 while i < len(s): if s[i] == '.': result += '0' i += 1 elif s[i] == '-' and s[i+1] == '.': result += '1' i += 2 elif s[i] == '-' and s[i+1] == '-': result += '2' i += 2 print(result)
Polycarpus has postcards and photos hung in a row on the wall. He decided to put them away to the closet and hang on the wall a famous painter's picture. Polycarpus does it like that: he goes from the left to the right and removes the objects consecutively. As Polycarpus doesn't want any mix-ups to happen, he will not ...
1
pc = raw_input() hand = 0 curr = '' ans = 0 for char in pc: if hand == 0: ans += 1 hand += 1 curr = char elif hand == 5: ans += 1 hand = 1 curr = char elif char != curr: ans += 1 curr = char hand = 1 else: hand += 1 print ans
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
n = int(input()) def distinct(n): n = str(n) a = list(n) if a[0] != a[1] and a[0] != a[2] and a[0] != a[3] and a[1] != a[2] and a[1] != a[3] and a[2] != a[3]: return True return False i = n + 1 while True: if distinct(i): print(i) break i += 1
Everyone knows that agents in Valorant decide, who will play as attackers, and who will play as defenders. To do that Raze and Breach decided to play t matches of a digit game... In each of t matches of the digit game, a positive integer is generated. It consists of n digits. The digits of this integer are numerated f...
3
for _ in range(int(input())): n = int(input()) s = input() # s = -1 if(n & 1): for i in range(0,n,2): if(s[i] in "13579"): s = 1 print(1) break else: print(2) else: for i in range(1, n, 2): if...
Given is a string S of length N. Find the maximum length of a non-empty string that occurs twice or more in S as contiguous substrings without overlapping. More formally, find the maximum positive integer len such that there exist integers l_1 and l_2 ( 1 \leq l_1, l_2 \leq N - len + 1 ) that satisfy the following: ...
3
import sys input = sys.stdin.readline def main(): n = int(input()) s = input()[::-1] ans = 0 l = 0 r = 1 for r in range(1,n): if s[l:r] in s[r:]: ans=r-l else: l += 1 print(ans) main()
Zeke loves to spend time with Penny and likes her. Penny is having an issue to solve a mathematics problem and is confused. She seeks Zeke's help as she feels he could help her with the problem. He finds this problem very simple. The problem is to count the number of unique triplets of different numbers (N1, N2, N3), w...
1
test=input() for i in range(0,test): a=map(int,raw_input().split()) a.sort(); ans=a[0]*(a[1]-1)*(a[2]-2) print ans%1000000007
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
m, n = map(int, input().strip().split()) print((m * n) // 2)
A programming competition site AtCode regularly holds programming contests. The next contest on AtCode is called ABC, which is rated for contestants with ratings less than 1200. The contest after the ABC is called ARC, which is rated for contestants with ratings less than 2800. The contest after the ARC is called AG...
3
r=int(input()) n=0 if r<1200 else 1 if r<2800 else 2 print(['ABC','ARC','AGC'][n])
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
for _ in range(int(input())): a, b = map(int, input().split()) if a * 2 <= b: print(a) elif b * 2 <= a: print(b) else: mid = min(a, b) - abs(a - b) div = 0 if mid % 3 == 2: div = 1 print(abs(a - b) + mid//3*2 + div)
One day Vasya got hold of information on the Martian dollar course in bourles for the next n days. The buying prices and the selling prices for one dollar on day i are the same and are equal to ai. Vasya has b bourles. He can buy a certain number of dollars and then sell it no more than once in n days. According to Mar...
3
n,m=map(int,input().split()) a=list(map(int,input().split())) ans=0 x=a[0] y=a[0] c=True for i in range(1,n): if(a[i]<x): l=m%x s=m//x # print(ans,x,y) ans=max(ans,s*y+l) x=a[i] y=a[i] if(i==n-1): c=False else: if(a[i]>y): y...
You have a list of numbers from 1 to n written from left to right on the blackboard. You perform an algorithm consisting of several steps (steps are 1-indexed). On the i-th step you wipe the i-th number (considering only remaining numbers). You wipe the whole number (not one digit). <image> When there are less than ...
3
TestCase = int(input()) while( TestCase > 0 ): [n,x] = list( map( int,input().split() ) ) print(2*x) TestCase -= 1
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
x = list(map(int, input().split())) a = x[0] * x[1] a = int(a/2) print(a)
You are given four integers n, c_0, c_1 and h and a binary string s of length n. A binary string is a string consisting of characters 0 and 1. You can change any character of the string s (the string should be still binary after the change). You should pay h coins for each change. After some changes (possibly zero) ...
3
for _ in range(int(input())): n,c0,c1,h=[int(w) for w in input().split()] x=input() a=0 for i in x: if i=='0': a+=min(c0,c1+h) else: a+=min(c1,c0+h) print(a)
You are given n k-digit integers. You have to rearrange the digits in the integers so that the difference between the largest and the smallest number was minimum. Digits should be rearranged by the same rule in all integers. Input The first line contains integers n and k β€” the number and digit capacity of numbers cor...
3
from itertools import permutations n, nDig = map(int, input().split()) a = [list(input()) for _ in range(n)] vals = [[] for _ in range(n)] for i, digs in enumerate(a): for p in permutations(digs): vals[i].append(int(''.join(p))) ret = float('inf') for p in zip(*vals): ret = min(ret, max(p) - min(p)) ...
Little girl Tanya climbs the stairs inside a multi-storey building. Every time Tanya climbs a stairway, she starts counting steps from 1 to the number of steps in this stairway. She speaks every number aloud. For example, if she climbs two stairways, the first of which contains 3 steps, and the second contains 4 steps,...
3
n = int(input()) steps = [int(i) for i in input().split()] count = 0 ans = [] for i in range(1,n): if steps[i] == 1: count += 1 ans.append(str(steps[i - 1])) ans.append(str(steps[n - 1])) print(count+1) print(" ".join(ans))
Lolek and Bolek are about to travel abroad by plane. The local airport has a special "Choose Your Plane" offer. The offer's conditions are as follows: * it is up to a passenger to choose a plane to fly on; * if the chosen plane has x (x > 0) empty seats at the given moment, then the ticket for such a plane costs ...
3
n,m = [int(x) for x in input().split()] l = [int(x) for x in input().split()] a = sorted(l) ctr = int(0) i = int(0) maxprice = int(0) minprice = int(0) while ctr!=n: maxprice+=max(l) l[l.index(max(l))]-=1 ctr+=1 ctr = 0 while ctr!=n: minprice += a[i] a[i]-=1 ctr+=1 if a[i]==0: i+=1 print(maxprice,minpr...
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...
3
n=int(input()) x=input().split() for i in range(n): x[i]=int(x[i]) print(x[1]-x[0],x[n-1]-x[0]) for i in range(1,n-1): print(min(x[i]-x[i-1],x[i+1]-x[i]),max(x[i]-x[0],x[n-1]-x[i])) print(x[n-1]-x[n-2],x[n-1]-x[0])
Today at the lesson of mathematics, Petya learns about the digital root. The digital root of a non-negative integer is the single digit value obtained by an iterative process of summing digits, on each iteration using the result from the previous iteration to compute a digit sum. The process continues until a single-d...
3
import bisect import decimal from decimal import Decimal import os from collections import Counter import bisect from collections import defaultdict import math import random import heapq from math import sqrt import sys from functools import reduce, cmp_to_key from collections import deque import threading from itert...
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
for t in range(int(input())): n, k = map(int, input().split()) sz = n-1 shifts = (k-1) // sz st = n * shifts + 1 index = (k-1) - sz * shifts ans = st + index print(ans)
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
1
m = n = int(raw_input()) a = map(int,raw_input().split()) i=0 n1=n2=0 while a: if a[0]>a[-1]: b=a.pop(0) else: b=a.pop() if i&1==0: n1+=b else: n2+=b i+=1 print n1,n2
Modern text editors usually show some information regarding the document being edited. For example, the number of words, the number of pages, or the number of characters. In this problem you should implement the similar functionality. You are given a string which only consists of: * uppercase and lowercase English...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**10 mod = 10**9 + 7 def f(): n = int(input()) s = input() f = False r = 0 r2 = 0 sc = '' for c in s: if c == '(': for ss in sc.split('_'): ...
Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome. Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation. This abbreviation is made lik...
3
n = int(input()) for i in range(n): a = str(input()) if (len(a) > 10): a = (a[0],len(a)-2,a[-1]) print(*a, sep = '') else: print(a)
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers. Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high...
3
t = int(input()) from math import ceil for i in range(t): n = int(input()) l = list(map(int, input().split())) nums = [] max_diff = 0 for i in range(n): if( l[i] != -1 ): if ( i > 0 and l[i - 1] == -1 ) or ( i < n-1 and l[i+1] == -1 ): nums.append(l[i]) if ( i < n-1 and l[i+1] != -...
Sereja and Dima play a game. The rules of the game are very simple. The players have n cards in a row. Each card contains a number, all numbers on the cards are distinct. The players take turns, Sereja moves first. During his turn a player can take one card: either the leftmost card in a row, or the rightmost one. The ...
3
n = int(input()) l = [int(num) for num in input().split(' ')] Sereja = 0 Dima = 0 while len(l) >= 1: if l[0] >= l[-1]: Sereja += l.pop(0) else: Sereja += l.pop(-1) if len(l) == 0: break if l[0] >= l[-1]: Dima += l.pop(0) else: Dima += l.pop(-1) print(Sereja, D...
We have a string S of length N consisting of `R`, `G`, and `B`. Find the number of triples (i,~j,~k)~(1 \leq i < j < k \leq N) that satisfy both of the following conditions: * S_i \neq S_j, S_i \neq S_k, and S_j \neq S_k. * j - i \neq k - j. Constraints * 1 \leq N \leq 4000 * S is a string of length N consisting of...
3
N = int(input()) S = input() ans, gap = S.count('R') * S.count('G') * S.count('B'), 1 while gap * 2 + 1 <= N: ans -= sum([1 for i in range(N - gap * 2) if {'R', 'G', 'B'} == {S[i], S[i + gap], S[i + 2 * gap]}]) gap += 1 print(ans)
One day three best friends Petya, Vasya and Tonya decided to form a team and take part in programming contests. Participants are usually offered several problems during programming contests. Long before the start the friends decided that they will implement a problem if at least two of them are sure about the solution....
3
n = int(input()) c = 0 s= [] for i in range(n): a = input() s.append(a.split()) temp=0 for i in s: for j in i: if int(j) == 1: temp +=1 if temp > 1: c += 1 temp=0 print(c)
After playing Neo in the legendary "Matrix" trilogy, Keanu Reeves started doubting himself: maybe we really live in virtual reality? To find if this is true, he needs to solve the following problem. Let's call a string consisting of only zeroes and ones good if it contains different numbers of zeroes and ones. For exa...
3
n = int(input()) s = input() c0 = s.count('0') c1 = n - c0 if c0 != c1: print(1, s, sep='\n') else: print(2) print(s[0], s[1:], sep=' ')
Apart from having lots of holidays throughout the year, residents of Berland also have whole lucky years. Year is considered lucky if it has no more than 1 non-zero digit in its number. So years 100, 40000, 5 are lucky and 12, 3001 and 12345 are not. You are given current year in Berland. Your task is to find how long...
3
def digit_count(x): count = 0 while x>0: count += 1 x //= 10 return count year = input() wait = int(year[0]) year = int(year) ans = (wait+1)*(10**(digit_count(year)-1)) ans -= year print(ans)
You are given an integer sequence 1, 2, ..., n. You have to divide it into two sets A and B in such a way that each element belongs to exactly one set and |sum(A) - sum(B)| is minimum possible. The value |x| is the absolute value of x and sum(S) is the sum of elements of the set S. Input The first line of the input ...
1
N = input() if(N % 4==0): print "0" elif(N%4==1): print "1" elif(N%4==2): print "1" else: print "0"
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
''' Name : Jaymeet Mehta codeforces id :mj_13 Problem : ''' from sys import stdin,stdout test=int(stdin.readline()) for _ in range(test): N=int(stdin.readline()) a=[int(x) for x in input().split()] a.sort() flag=True for i in range(N-1): if a[i+1]-a[i]>1: flag=False ...
A permutation is a sequence of integers p1, p2, ..., pn, consisting of n distinct positive integers, each of them doesn't exceed n. Let's denote the i-th element of permutation p as pi. We'll call number n the size of permutation p1, p2, ..., pn. Nickolas adores permutations. He likes some permutations more than the o...
3
n=int(input()) if(n%2!=0): print("-1") else: print(*list(range(n,0,-1)))
You are given a long decimal number a consisting of n digits from 1 to 9. You also have a function f that maps every digit from 1 to 9 to some (possibly the same) digit from 1 to 9. You can perform the following operation no more than once: choose a non-empty contiguous subsegment of digits in a, and replace each digi...
3
n = int(input()) a = input() f = list(map(int, input().split())) ans = '' r = 0 fa = 0 for i in a: r += 1 chert = max(int(i), f[int(i) - 1]) if chert != int(i): fa += 1 ans += str(chert) if chert != f[int(i) - 1] and chert == int(i) and r != len(a) and fa > 0: #print(ans) ans...
You are given an array a consisting of n integers. Your task is to determine if a has some subsequence of length at least 3 that is a palindrome. Recall that an array b is called a subsequence of the array a if b can be obtained by removing some (possibly, zero) elements from a (not necessarily consecutive) without c...
3
for _ in range(int(input())): n=int(input()) l=list(map(int,input().split())) flag=0 for i in range(n): if i+2<n: if l[i] in l[i+2:]: flag=1 break if flag==1: print('YES') else: print('NO') ...
The game of Berland poker is played with a deck of n cards, m of which are jokers. k players play this game (n is divisible by k). At the beginning of the game, each player takes n/k cards from the deck (so each card is taken by exactly one player). The player who has the maximum number of jokers is the winner, and he...
3
tc = int(input()) for _ in range(tc): n,m,k = list(map(int,input().split())) if m==0: print(0) else: x = min(m,n//k) if x == m: print(m) else: y=0 if (m-x)%(k-1) == 0: y = (m-x)//(k-1) else: y =...
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...
3
I = lambda: map(int, input().split()) _, k = I() A = list(I()) s = sum(A) print(max(abs(s-sum(A[i::k])) for i in range(k)))
You are given two binary strings a and b of the same length. You can perform the following two operations on the string a: * Swap any two bits at indices i and j respectively (1 ≀ i, j ≀ n), the cost of this operation is |i - j|, that is, the absolute difference between i and j. * Select any arbitrary index i (1 ...
3
from collections import defaultdict n=int(input()) x=input() y=input() a=[int(i) for i in x] b=[int(i) for i in y] d=defaultdict(int) res=[] #print(a,b) for i in range(n): if(a[i]!=b[i]): d[i]=a[i] res+=[i] i=1 c=0 #print(res) #print(d) while(i<len(res)): if(res[i]-res[i-1]<2 and d[res[i]]!=d[re...
You are given a sequence s consisting of n digits from 1 to 9. You have to divide it into at least two segments (segment β€” is a consecutive sequence of elements) (in other words, you have to place separators between some digits of the sequence) in such a way that each element belongs to exactly one segment and if the ...
3
n = int(input()) for i in range(n): d = int(input()) s = input() if len(s) == 2 and (s[0] == s[1] or s[0] > s[1]): print("NO") else: print("YES") print(2) print(s[:1], s[1:])
Hongcow is ruler of the world. As ruler of the world, he wants to make it easier for people to travel by road within their own countries. The world can be modeled as an undirected graph with n nodes and m edges. k of the nodes are home to the governments of the k countries that make up the world. There is at most one...
3
n,m,k=map(int,input().split()) C=list(map(int,input().split())) g=[[0]*(n+1) for _ in range(n+1)] for _ in range(m): a,b=map(int, input().split()) g[a][b]=g[b][a]=1 y=[0]*k v=[0]*(n+1) def dfs(c, x): y[c]+=1 v[x]=1 for j in range(n+1): if g[x][j]==1 and v[j]==0: dfs(c,j) for c ...
Today Sonya learned about long integers and invited all her friends to share the fun. Sonya has an initially empty multiset with integers. Friends give her t queries, each of one of the following type: 1. + ai β€” add non-negative integer ai to the multiset. Note, that she has a multiset, thus there may be many occur...
1
import sys n = int(input()) D = {} def get_hash(x): return ("".join(['1' if xi in ('1', '3', '5', '7', '9') else '0' for xi in x])).zfill(18) def get_match(x): x = x.zfill(18) return D.get(x, 0) for i in range(n): c, a = raw_input().split() p = get_hash(a) if c == '+': D.setdefaul...