problem
stringlengths
29
9.39k
language
int64
1
3
solution
stringlengths
7
465k
Quite recently, a very smart student named Jury decided that lectures are boring, so he downloaded a game called "Black Square" on his super cool touchscreen phone. In this game, the phone's screen is divided into four vertical strips. Each second, a black square appears on some of the strips. According to the rules o...
1
a = map(int , raw_input().split()) s = map(int , raw_input()) ans = 0 n = len(s) for i in xrange(n): ans += a[s[i] - 1] print ans
This problem is different from the hard version. In this version Ujan makes exactly one exchange. You can hack this problem only if you solve both problems. After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first. Ujan has two distinct str...
3
for _ in range(int(input())): n=int(input()) a=list(input()) b=list(input()) ans=[] d1=dict() d2=dict() for i in range(n): try: d1[a[i]].add(i) except: d1[a[i]]=set([(i)]) try: d2[b[i]].add(i) except: d2[b[i]]=se...
Can you imagine our life if we removed all zeros from it? For sure we will have many problems. In this problem we will have a simple example if we removed all zeros from our life, it's the addition operation. Let's assume you are given this equation a + b = c, where a and b are positive integers, and c is the sum of a...
3
a=input() b=input() fake=str(int(a)+int(b)) a=a.replace("0","") b=b.replace("0","") fake=fake.replace("0","") if int(a)+int(b)==int(fake): print("YES") else: print("NO")
In this problem we assume the Earth to be a completely round ball and its surface a perfect sphere. The length of the equator and any meridian is considered to be exactly 40 000 kilometers. Thus, travelling from North Pole to South Pole or vice versa takes exactly 20 000 kilometers. Limak, a polar bear, lives on the N...
3
curr=0 for _ in range(int(input())): s=input().split() if not curr%40000 and s[1]!="South": print("NO") exit(0) elif curr%40000 == 20000 and s[1]!="North": print("NO") exit(0) if s[1] in ["North"]:curr-=int(s[0]) elif s[1] in ["South"]:curr+=int(s[0]) # print...
IA has so many colorful magnets on her fridge! Exactly one letter is written on each magnet, 'a' or 'b'. She loves to play with them, placing all magnets in a row. However, the girl is quickly bored and usually thinks how to make her entertainment more interesting. Today, when IA looked at the fridge, she noticed that...
1
s = raw_input().strip() n = len(s) out = ['0' for i in xrange(n)] i = 0 while i < n: while i < n and s[i] != 'a': i += 1 while i < n and s[i] == 'a': i += 1 if i <= n: out[i - 1] = '1' else: break while i < n and s[i] != 'b': i += 1 while i < n and s[i] == 'b': i += 1 if i < n: out[i - ...
Shubham has a binary string s. A binary string is a string containing only characters "0" and "1". He can perform the following operation on the string any amount of times: * Select an index of the string, and flip the character at that index. This means, if the character was "0", it becomes "1", and vice versa. ...
3
import sys from math import inf input = sys.stdin.readline def solve(): s = input() n = len(s) if len(set(s)) == 1: print(0) return zeros_pref = [0] * n ones_pref = [0] * n zeros_suff = [0] * n ones_suff = [0] * n zeros_pref[0] = int(s[0] == '0') ones_pref[0] = int(s[0] == '1') zeros_suff[-1] = int(s[-1...
A company has N members, who are assigned ID numbers 1, ..., N. Every member, except the member numbered 1, has exactly one immediate boss with a smaller ID number. When a person X is the immediate boss of a person Y, the person Y is said to be an immediate subordinate of the person X. You are given the information ...
3
n=int(input()) buka = [0]*n for joushi in input().split(): buka[int(joushi)-1] += 1 print(*buka,sep='\n')
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
for i in range(int(input())): l = input() if len(l)<=10: print(l) else: print(l[0]+str(len(l)-2)+l[-1])
Duff is in love with lovely numbers! A positive integer x is called lovely if and only if there is no such positive integer a > 1 such that a2 is a divisor of x. <image> Malek has a number store! In his store, he has only divisors of positive integer n (and he has all of them). As a birthday present, Malek wants to g...
3
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,copy,functools import random sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return list(map(int, sys.stdin.r...
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. Input The f...
3
import math def prime(k): if(k<=1): return False if(k<=3): return True if(k%2==0 or k%3==0): return False i=5 while i*i<=k: if(k%i==0 or k%(i+2)==0): return False i+=6 return True n=int(input()) l=list(map(int,input().split())) for j ...
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...
3
r1 = list(map(int, input().split())) r2 = list(map(int, input().split())) r3 = list(map(int, input().split())) temp1 = r1[1]+r1[2] temp2 = r2[0]+r2[2] temp3 = r3[0]+r3[1] x = int((temp2 + temp3 - temp1)/2) y = int((-temp2 + temp3 + temp1)/2) z = int((temp2 - temp3 + temp1)/2) r1[0] = x r2[1] = y r3[2] = z print(*r1) pr...
Are you going to Scarborough Fair? Parsley, sage, rosemary and thyme. Remember me to one who lives there. He once was the true love of mine. Willem is taking the girl to the highest building in island No.28, however, neither of them knows how to get there. Willem asks his friend, Grick for directions, Grick helped...
3
_, m = [int(x) for x in input().split()] s = list(input()) for ii in range(m): args = input().split() l, r = int(args[0]), int(args[1]) c1, c2 = args[2], args[3] for j in range(l - 1, r): if s[j] == c1: s[j] = c2 print(''.join(s))
Natasha is planning an expedition to Mars for n people. One of the important tasks is to provide food for each participant. The warehouse has m daily food packages. Each package has some food type a_i. Each participant must eat exactly one food package each day. Due to extreme loads, each participant must eat the sam...
3
pf = [int(item) for item in input().split()] #[number of people, food packages] ft = [int(item) for item in input().split()] if pf[0] > pf[1]: print(0) else: ftd = {} for x in ft: if x in ftd: ftd[x] = ftd[x]+1 else: ftd[x] = 1 pot = int(pf[1]/pf[0]) def food(x, d...
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()) i=0 alist=[] total=0 for i in range(0,n): alist.append([int(i) for i in input().split()]) if alist[i].count(1)>=2: total+=1 print (total)
Those days, many boys use beautiful girls' photos as avatars in forums. So it is pretty hard to tell the gender of a user at the first glance. Last year, our hero went to a forum and had a nice chat with a beauty (he thought so). After that they talked very often and eventually they became a couple in the network. Bu...
3
def main(): username = input() distinct_set = set(username) print("CHAT WITH HER!") if len(distinct_set) % 2 == 0 else print("IGNORE HIM!") if __name__ == '__main__': main()
Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left. Each square is painted black or white. The grid is said to be good if and only if the following condition is satisfied: * From (1, 1), we can reach (H, W) by moving one sq...
3
H,W = map(int,input().split()) s = [input() for _ in range(H)] DP = [[1000]+[0]*W for _ in range(H+1)] re = [[0]*(W+1) for _ in range(H+1)] DP[0] = [1000]*(W+1) DP[0][1] = DP[1][0] = 0 for i in range(1,H+1): for j in range(1,W+1): if s[i-1][j-1] == ".": DP[i][j] = min(DP[i-1][j],DP[i][j-1]) ...
One hot summer day Pete and his friend Billy decided to buy a watermelon. They chose the biggest and the ripest one, in their opinion. After that the watermelon was weighed, and the scales showed w kilos. They rushed home, dying of thirst, and decided to divide the berry, however they faced a hard problem. Pete and Bi...
3
from math import * w = input() if int(w) % 2 == 0 and int(w) > 2: print("YES") else: print("NO")
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 ...
3
s = input() string = input() b = 0 for i in range(0,len(s)): if s[i] in string: print("YES") b = 1 break if b==0: print("NO")
The Little Elephant loves chess very much. One day the Little Elephant and his friend decided to play chess. They've got the chess pieces but the board is a problem. They've got an 8 × 8 checkered board, each square is painted either black or white. The Little Elephant and his friend know that a proper chessboard doe...
1
for i in range(8): s=raw_input() if s!='WBWBWBWB' and s!='BWBWBWBW': print 'NO' exit() print 'YES'
A positive (strictly greater than zero) integer is called round if it is of the form d00...0. In other words, a positive integer is round if all its digits except the leftmost (most significant) are equal to zero. In particular, all numbers from 1 to 9 (inclusive) are round. For example, the following numbers are roun...
3
import math def main(): t = int(input()) for _ in range(t): n = input() if len(n) == 1: print(1) print(n) continue ans = 0 s = "" for i in range(len(n)): c = n[len(n)-1-i] if c != "0": ...
Nicholas has an array a that contains n distinct integers from 1 to n. In other words, Nicholas has a permutation of size n. Nicholas want the minimum element (integer 1) and the maximum element (integer n) to be as far as possible from each other. He wants to perform exactly one swap in order to maximize the distance...
3
n = int(input()) A = list(map(int, input().split())) for i in range(n): if A[i] == 1: posMin = i continue if A[i] == n: posMax = i if posMin > posMax: posMin, posMax = posMax, posMin print(max(posMax, n - posMin - 1))
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
def solve(N, candies, oranges): answer = 0 minCandies = min(candies) minOranges = min(oranges) for i in range(N): answer += max(candies[i] - minCandies, oranges[i] - minOranges) return answer if __name__ == "__main__": testCases = int(input()) for case in range(testCases): ...
Given is an integer N. Find the number of positive integers less than or equal to N that have an odd number of digits (in base ten without leading zeros). Constraints * 1 \leq N \leq 10^5 Input Input is given from Standard Input in the following format: N Output Print the number of positive integers less than ...
3
n=int(input()) cnt=0 for i in range(1,n+1): cnt+=len(str(i))%2 print(cnt)
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
# Parser - needed for reading # a simple parser for python. use get_number() and get_word() to read def parser(): while 1: data = list(input().split(' ')) for number in data: if len(number) > 0: yield(number) input_parser = parser() def get_word(): global inpu...
Santa Claus is the first who came to the Christmas Olympiad, and he is going to be the first to take his place at a desk! In the classroom there are n lanes of m desks each, and there are two working places at each of the desks. The lanes are numbered from 1 to n from the left to the right, the desks in a lane are numb...
3
from math import ceil n, m, k = map(int, input().split()) x = ceil(k/(2*m)) if k % (2 * m): y = ceil((k%(2*m))/2) else: y = m z = 'L' if k%2 else 'R' print(x, y, z)
Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and put them in a line so that he gets some number. What is the largest possible number divisible by 90 Jeff can make from the cards he's got? Jeff must make the number without leading zero. At that, we assume that number ...
3
N = int(input()) A = list(map(int, input().split())) five_cnt = A.count(5) zero_cnt = A.count(0) fiv = five_cnt // 9 * 9 if fiv == 0: if zero_cnt == 0: print(-1) else: print(0) else: if zero_cnt == 0: print(-1) else: print("5" * fiv + "0" * zero_cnt)
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav...
3
def solve(): n, m, x, y = list(map(int, input().split())) mundo = [] y = min(y, 2*x) price = 0 for _ in range(n): row = input() i = 0 while i<m: if row[i] == '.': if i+1< m and row[i+1] == '.': price += y i +...
As you may know, MemSQL has American offices in both San Francisco and Seattle. Being a manager in the company, you travel a lot between the two cities, always by plane. You prefer flying from Seattle to San Francisco than in the other direction, because it's warmer in San Francisco. You are so busy that you don't rem...
3
n=int(input()) a=input() s=0 f=0 for i in range(n-1): if a[i]+a[i+1]=='SF': f+=1 if a[i]+a[i+1]=='FS': s+=1 if f>s: print('YES') else: print('NO')
There are N squares aligned in a row. The i-th square from the left contains an integer a_i. Initially, all the squares are white. Snuke will perform the following operation some number of times: * Select K consecutive squares. Then, paint all of them white, or paint all of them black. Here, the colors of the squares...
3
n,k=map(int,input().split()) a=list(map(int,input().split())) base=sum([x for x in a if x>0]) black=sum([-x for x in a[:k] if x<0]) white=sum([x for x in a[:k] if x>0]) ans=max(0,base-min(black,white)) for i in range(k,n): if a[i]>0: white+=a[i] else: black-=a[i] if a[i-k]>0: white-=a[i-k] else: ...
Hongcow is learning to spell! One day, his teacher gives him a word that he needs to learn to spell. Being a dutiful student, he immediately learns how to spell the word. Hongcow has decided to try to make new words from this one. He starts by taking the word he just learned how to spell, and moves the last character ...
3
#!/usr/bin/env python3 def main(): try: while True: s = input() a = set() for i in range(len(s)): a.add(s) s = s[1:] + s[0] print(len(a)) except EOFError: pass main()
We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i. You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have? Constraints * 1\leq N,Q \leq 5 \times 10^5 * 1\leq c_i \leq N * 1\leq ...
3
class BIT: # 1-indexed def __init__(self, n): self.size = n + 1 self.bit = [0] * self.size def add(self, i, x): """Add x to a[i].""" while i < self.size: self.bit[i] += x i += i & -i def sumup(self, i): """Sum a[1]~a[i].""" res = ...
Initially, you have the array a consisting of one element 1 (a = [1]). In one move, you can do one of the following things: * Increase some (single) element of a by 1 (choose some i from 1 to the current length of a and increase a_i by one); * Append the copy of some (single) element of a to the end of the array...
3
import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter # from itertools import permutations,combinations def data():...
Sergey is testing a next-generation processor. Instead of bytes the processor works with memory cells consisting of n bits. These bits are numbered from 1 to n. An integer is stored in the cell in the following way: the least significant bit is stored in the first bit of the cell, the next significant bit is stored in ...
3
n = int(input()) s = input() a = 0 for i in range(n): a += (2**i)*(int(s[i])) a+=1 s2 = list(str(bin(a)))[2:] s2.reverse() while len(s2)<len(s): s2.append('0') answ = 0 for i in range(n): if s[i]!=s2[i]: answ+=1 print(answ)
Tomorrow is a difficult day for Polycarp: he has to attend a lectures and b practical classes at the university! Since Polycarp is a diligent student, he is going to attend all of them. While preparing for the university, Polycarp wonders whether he can take enough writing implements to write all of the lectures and d...
3
t=int(input()) for i in range(t): a,b,c,d,k=map(int,input().split()) s=0 if a==c: j=0 else: for j in range(k): if c*j<a<=c*(j+1): break if b==d: e=0 else: for e in range(k): if d*e<b<=d*(e+1): break if j+...
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
a = input() s=a.lower() for i in range(len(s)): if((s[i]!="a") and (s[i]!="e") and (s[i]!="i") and (s[i]!="o") and (s[i]!="u") and (s[i]!="y")): print("."+s[i] , end="")
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
k = [] x , y = 0,0 for i in range(5): l = list(map(int, input().split())) if 1 in l: y = l.index(1) x = i k.append(l) print(abs(2-x) + abs(2-y))
Two boys decided to compete in text typing on the site "Key races". During the competition, they have to type a text consisting of s characters. The first participant types one character in v1 milliseconds and has ping t1 milliseconds. The second participant types one character in v2 milliseconds and has ping t2 millis...
3
t,s1,s2,p1,p2=map(int,input().split()) time1=t*s1+p1*2 time2=t*s2+p2*2 if time1<time2: print('First') else: if time1!=time2: print('Second') else: print('Friendship') #https://codeforces.com/problemset/problem/835/A
Our beloved detective, Sherlock is currently trying to catch a serial killer who kills a person each day. Using his powers of deduction, he came to know that the killer has a strategy for selecting his next victim. The killer starts with two potential victims on his first day, selects one of these two, kills selected ...
1
if __name__ == '__main__': ans = raw_input().split(' ') n = input() print ans[0], ans[1] for i in range(n): x, y = raw_input().split(' ') if x == ans[0]: ans[0] = y else: ans[1] = y print ans[0], ans[1]
The three friends, Kuro, Shiro, and Katie, met up again! It's time for a party... What the cats do when they unite? Right, they have a party. Since they wanted to have as much fun as possible, they invited all their friends. Now n cats are at the party, sitting in a circle and eating soup. The rules are simple: anyone...
3
input_string = input() array = input_string.split() n = int(array[0]) m = int(array[1]) if m == 0 : print(1) elif(n-m <=m): print(n-m) else: print(m)
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
a, k, n = input().split() a = int(a) k = int(k) n = int(n) s = 0.0000 s = (n/2)*(2*a + (n-1)*a) if k<s: print(int(s-k)) else: print(0)
You are given a positive integer n. In one move, you can increase n by one (i.e. make n := n + 1). Your task is to find the minimum number of moves you need to perform in order to make the sum of digits of n be less than or equal to s. You have to answer t independent test cases. Input The first line of the input co...
3
def solve(): s, n = [i for i in input().split()] n = int(n) i = 0 ok = True while i < len(s): if n > int(s[i]): n -= int(s[i]) else: ok = False break i += 1 if ok: print(0) return if int(s[i]) == n: tmp = 0...
Linear Kingdom has exactly one tram line. It has n stops, numbered from 1 to n in the order of tram's movement. At the i-th stop ai passengers exit the tram, while bi passengers enter it. The tram is empty before it arrives at the first stop. Also, when the tram arrives at the last stop, all passengers exit so that it ...
3
n = int(input()) minCapacity = 0 n_people=0 first=False while n>0: n -= 1 n_exit,n_enter = [int(i) for i in input().split()] #print('minCapacity={0}'.format(minCapacity),end=' ') n_people -= n_exit n_people += n_enter #print('t={0},n_exit={1},n_enter={2}'.forma...
You are given a non-negative integer n, its decimal representation consists of at most 100 digits and doesn't contain leading zeroes. Your task is to determine if it is possible in this case to remove some of the digits (possibly not remove any digit at all) so that the result contains at least one digit, forms a non-...
3
import sys import math import bisect from sys import stdin, stdout from math import gcd, floor, sqrt, log from collections import defaultdict as dd from bisect import bisect_left as bl, bisect_right as br from collections import Counter from collections import defaultdict as dd # sys.setrecursionlimit(100000000) flus...
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
1
n = raw_input() if(int(n)>=0): print n else: n1 = n[:-1] n2 = n[:-2]+n[-1] n_c = max(int(n1),int(n2)) print(n_c)
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
test_cases = int(input()) for test_case in range(test_cases): coins = int(input()) total_coins = [2 ** x for x in range(1, coins)] half_size = coins // 2 first_set = [2 ** coins] second_set = [] for x in range(half_size - 1): first_set.append(total_coins[x]) for y in range(half_siz...
Given an array a1, a2, ..., an of n integers, find the largest number in the array that is not a perfect square. A number x is said to be a perfect square if there exists an integer y such that x = y2. Input The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array. The second ...
3
import math def check(a): try: b=int(math.sqrt(a)) if b*b==a: return False else: return True except: return True n=int(input()) c=[] a=set(map(int,input().split())) m=max(a) for i in a: if check(i): c.append(i) print(max(c))
You are given a set of n segments on the axis Ox, each segment has integer endpoints between 1 and m inclusive. Segments may intersect, overlap or even coincide with each other. Each segment is characterized by two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ m) — coordinates of the left and of the right endpoints. Consider...
3
n, m = [int(x) for x in input().split(' ')] plane = [i for i in range(1,m+1)] segments = [] for i in range(n): lb,up = [int(x) for x in input().split(' ')] for j in range(lb,up+1): segments.append(j) ans = list(set(plane) - set(segments)) print(len(ans)) if ans: print(*ans, sep=' ')
We have a grid with H horizontal rows and W vertical columns. Let (i,j) denote the square at the i-th row from the top and the j-th column from the left. The square (i, j) has two numbers A_{ij} and B_{ij} written on it. First, for each square, Takahashi paints one of the written numbers red and the other blue. Then...
3
h,w=map(int,input().split()) arr=[list(map(int,input().split())) for _ in range(2*h)] board=[[0]*w for _ in range(h)] for i in range(h): for j in range(w): board[i][j]+=arr[i][j] for i in range(h): for j in range(w): board[i][j]=abs(board[i][j]-arr[h+i][j]) dp=[[set() for _ in range(w)] for _ in range(h)] d...
"QAQ" is a word to denote an expression of crying. Imagine "Q" as eyes with tears and "A" as a mouth. Now Diamond has given Bort a string consisting of only uppercase English letters of length n. There is a great number of "QAQ" in the string (Diamond is so cute!). <image> illustration by 猫屋 https://twitter.com/nekoy...
1
s = raw_input() n = len(s) res = 0 for i in xrange(n): for j in xrange(i): for k in xrange(j): if s[i] == 'Q' and s[k] == 'Q' and s[j] == 'A': res += 1 print res
Find the minimum area of a square land on which you can place two identical rectangular a × b houses. The sides of the houses should be parallel to the sides of the desired square land. Formally, * You are given two identical rectangles with side lengths a and b (1 ≤ a, b ≤ 100) — positive integers (you are given ...
3
t=int(input()) for k in range(t): a,b=map(int,input().split()) c=min(max(2*a,b),max(2*b,a)) print(c*c)
«One dragon. Two dragon. Three dragon», — the princess was counting. She had trouble falling asleep, and she got bored of counting lambs when she was nine. However, just counting dragons was boring as well, so she entertained herself at best she could. Tonight she imagined that all dragons were here to steal her, and ...
3
k = int(input()) l = int(input()) m = int(input()) n = int(input()) d = int(input()) r = [] for i in range(k,d+1,k): r.append(i) for i in range(l,d+1,l): r.append(i) for i in range(m,d+1,m): r.append(i) for i in range(n,d+1,n): r.append(i) r = set(r) print(len(r))
Pari has a friend who loves palindrome numbers. A palindrome number is a number that reads the same forward or backward. For example 12321, 100001 and 1 are palindrome numbers, while 112 and 1021 are not. Pari is trying to love them too, but only very special and gifted people can understand the beauty behind palindro...
3
def main(): num_palindrome = input() print(num_palindrome + num_palindrome[::-1]) if __name__ == '__main__': main()
"Contestant who earns a score equal to or greater than the k-th place finisher's score will advance to the next round, as long as the contestant earns a positive score..." — an excerpt from contest rules. A total of n participants took part in the contest (n ≥ k), and you already know their scores. Calculate how many ...
3
a, b = input().split() balls = input().split() print(len([1 for i in balls if int(i) >= int(balls[int(b) - 1]) and int(i) > 0]))
Alice has a cute cat. To keep her cat fit, Alice wants to design an exercising walk for her cat! Initially, Alice's cat is located in a cell (x,y) of an infinite grid. According to Alice's theory, cat needs to move: * exactly a steps left: from (u,v) to (u-1,v); * exactly b steps right: from (u,v) to (u+1,v); ...
3
t=int(input()) for _ in range(t): a,b,c,d=map(int,input().split()) x,y,x1,y1,x2,y2=map(int,input().split()) x+=b-a y+=d-c if (a+b>0 and x1==x2): print("No") elif c+d>0 and y1==y2: print("No") elif x1<=x<=x2 and y1<=y<=y2: print("Yes") else: print("No")
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
import array, bisect, collections, copy, fractions, functools, heapq, itertools, math, random, re, string, sys, time, os, timeit sys.setrecursionlimit(10000000) inf = float('inf') def li(): return [int(x) for x in sys.stdin.readline().split()] def li_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def l...
String can be called correct if it consists of characters "0" and "1" and there are no redundant leading zeroes. Here are some examples: "0", "10", "1001". You are given a correct string s. You can perform two different operations on this string: 1. swap any pair of adjacent characters (for example, "101" <image>...
3
b=int(input('')) a=input('') t=[1] p=0 z=0 l=0 for i in range(len(a)): if(str(a[l])=='0'): z=z+1 l=l+1 if(z==len(a)): print(a) else: for k in range(z): t.append(0) for j in range(len(t)): print(t[p],end='') p=p+1
You are playing a variation of game 2048. Initially you have a multiset s of n integers. Every integer in this multiset is a power of two. You may perform any number (possibly, zero) operations with this multiset. During each operation you choose two equal integers from s, remove them from s and insert the number eq...
3
t = int(input()) for _ in range(t): n = int(input()) l = list(map(int, input().split())) while len(l) != len(set(l)) and 2048 not in set(l): for i in set(l): if l.count(i) > 1: l.remove(i) l.remove(i) l.append(i * 2) if 2048 in l: print('yes') else: print('no')
Vasya claims that he had a paper square. He cut it into two rectangular parts using one vertical or horizontal cut. Then Vasya informed you the dimensions of these two rectangular parts. You need to check whether Vasya originally had a square. In other words, check if it is possible to make a square using two given rec...
3
t = int(input()) for i in range(t): a1, b1 = map(int, input().split()) a2, b2 = map(int, input().split()) if a1 + a2 == b1 == b2 or a1 + b2 == a2 == b1 or b1 + a2 == a1 == b2 or b1 + b2 == a1 == a2: print("Yes") else: print("No")
You are given a string S of length N consisting of lowercase English letters. Process Q queries of the following two types: * Type 1: change the i_q-th character of S to c_q. (Do nothing if the i_q-th character is already c_q.) * Type 2: answer the number of different characters occurring in the substring of S betwee...
3
n=int(input()) ss=input() dps=['a']*n from collections import defaultdict d=defaultdict(list) for i in range(n): d[ss[i]].append(i) dps[i]=ss[i] sorted(d.items()) Q=int(input()) import bisect for i in range(Q): num,ii,c=input().split() #print(d) if num=='1': if c==dps[int(ii)-1]: ...
Yura has been walking for some time already and is planning to return home. He needs to get home as fast as possible. To do this, Yura can use the instant-movement locations around the city. Let's represent the city as an area of n × n square blocks. Yura needs to move from the block with coordinates (s_x,s_y) to the ...
3
import sys from sys import stdin n,m = map(int,stdin.readline().split()) sx,sy,gx,gy = map(int,stdin.readline().split()) xdic = {} xlis = [] ydic = {} ylis = [] if sx not in xdic: xdic[sx] = 0 xlis.append(sx) """ if gx not in xdic: xdic[gx] = 0 xlis.append(gx) """ if sy not in ydic: ydic[sy] =...
You might have remembered Theatre square from the [problem 1A](https://codeforces.com/problemset/problem/1/A). Now it's finally getting repaved. The square still has a rectangular shape of n × m meters. However, the picture is about to get more complicated now. Let a_{i,j} be the j-th square in the i-th row of the pav...
3
for _ in range(int(input())): n,m,x,y=[int(k) for k in input().split()] tiles=[] amt=0 for i in range(n): tilesele=input() tiles.append(list(tilesele)) flag=0 if 2*x<=y: for ii in range(n): amt+=(tiles[ii].count(".")*x) else: for ii in range(...
Vitaly has an array of n distinct integers. Vitaly wants to divide this array into three non-empty sets so as the following conditions hold: 1. The product of all numbers in the first set is less than zero ( < 0). 2. The product of all numbers in the second set is greater than zero ( > 0). 3. The product of a...
3
m=int(input()) l=list(map(int,input().split())) p,n,z=[],[],[] for i in range(m): if l[i]>0: p.append(l[i]) elif l[i]<0: n.append(l[i]) else: z.append(l[i]) if not p: p=n[:2] n=n[2:] print(1,n[0]) print(len(p),*p) print(len(z)+len(n)-1,*z,*n[1:]) ...
Two players are playing a game. First each of them writes an integer from 1 to 6, and then a dice is thrown. The player whose written number got closer to the number on the dice wins. If both payers have the same difference, it's a draw. The first player wrote number a, the second player wrote number b. How many ways ...
3
x = [int(i) for i in input().split()] a = x[0] b = x[1] a_p = 0 b_p= 0 draw = 0 for i in range(1,7): diffA = abs(a-i) diffB = abs(b-i) if diffA<diffB: a_p += 1 elif diffB<diffA: b_p += 1 else: draw += 1 print(a_p,draw,b_p,)
The Central Company has an office with a sophisticated security system. There are 10^6 employees, numbered from 1 to 10^6. The security system logs entrances and departures. The entrance of the i-th employee is denoted by the integer i, while the departure of the i-th employee is denoted by the integer -i. The compan...
3
mod=10**9+7 import sys # sys.setrecursionlimit(10**6) from sys import stdin, stdout import bisect #c++ upperbound import math import heapq def modinv(n,p): return pow(n,p-2,p) def cin(): return map(int,sin().split()) def ain(): #takes array as input return list(map(int...
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,s=int(input()),input() print(sum(1 for i in range(n-1) if s[i]==s[i+1]))
Ilya is a very clever lion, he lives in an unusual city ZooVille. In this city all the animals have their rights and obligations. Moreover, they even have their own bank accounts. The state of a bank account is an integer. The state of a bank account can be a negative number. This means that the owner of the account ow...
3
n=int(input()) if n>=0: print(n) else: n= -1*n n=str(n) li=[int(i) for i in n] list1=[int(i) for i in li] list2=[int(i) for i in li] list1.pop() list2.pop(-2) n1= ''.join(str(i) for i in list1) n2= ''.join(str(i) for i in list2) if n1=='0' or n2=='0': print('0') e...
An X-layered kagami mochi (X ≥ 1) is a pile of X round mochi (rice cake) stacked vertically where each mochi (except the bottom one) has a smaller diameter than that of the mochi directly below it. For example, if you stack three mochi with diameters of 10, 8 and 6 centimeters from bottom to top in this order, you have...
3
n = int(input()) d = set([input() for _ in range(n)]) print(len(d))
N people are standing in a queue, numbered 1, 2, 3, ..., N from front to back. Each person wears a hat, which is red, blue, or green. The person numbered i says: * "In front of me, exactly A_i people are wearing hats with the same color as mine." Assuming that all these statements are correct, find the number of p...
3
n=int(input()) l=list(map(int,input().split())) mod=10**9+7 ans=1 rgb=[0]*3 for i in range(n): f=0 for j in range(3): if l[i]==rgb[j]: if f==0: rgb[j]+=1 f+=1 ans*=f ans%=mod print(ans)
There is an integer sequence A of length N whose values are unknown. Given is an integer sequence B of length N-1 which is known to satisfy the following: B_i \geq \max(A_i, A_{i+1}) Find the maximum possible sum of the elements of A. Constraints * All values in input are integers. * 2 \leq N \leq 100 * 0 \leq B_i...
3
n=int(input()) l=list(map(int,input().split())) print(l[0]+sum(min(l[i],l[i+1]) for i in range(n-2))+l[-1])
You are given an integer sequence of length n, a_1, ..., a_n. Let us consider performing the following n operations on an empty sequence b. The i-th operation is as follows: 1. Append a_i to the end of b. 2. Reverse the order of the elements in b. Find the sequence b obtained after these n operations. Constraints...
3
# C n = int(input()) a_list = list(input().split()) res_list = [] for i in range(n-1, -1, -2): res_list.append(a_list[i]) if n % 2 == 0: for i in range(0, n, 2): res_list.append(a_list[i]) else: for i in range(1, n, 2): res_list.append(a_list[i]) print(" ".join(res_list))
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'...
1
import math n,m,a = [float(x) for x in raw_input().split()] b = math.ceil(n/a)*math.ceil(m/a) print(int(b))
After seeing the "ALL YOUR BASE ARE BELONG TO US" meme for the first time, numbers X and Y realised that they have different bases, which complicated their relations. You're given a number X represented in base bx and a number Y represented in base by. Compare those two numbers. Input The first line of the input con...
3
x = [int(e) for e in input().split(" ")] x1 = [int(t) for t in input().split(" ")] y = [int(w) for w in input().split(" ")] y1 = [int(q) for q in input().split(" ")] indx1 = len(x1)-1 #último item da lista indy1 = len(y1)-1 #último item da lista basex = x[1] basey = y[1] lx = x[0] ly = y[0] somx = 0 somy = 0 k = 0 h ...
A penguin Rocher has n sticks. He has exactly one stick with length i for all 1 ≤ i ≤ n. He can connect some sticks. If he connects two sticks that have lengths a and b, he gets one stick with length a + b. Two sticks, that were used in the operation disappear from his set and the new connected stick appears in his se...
3
a= int(input()) for i in range(0,a): b = int(input()) print(((b-1)//2)+1)
Yaroslav, Andrey and Roman can play cubes for hours and hours. But the game is for three, so when Roman doesn't show up, Yaroslav and Andrey play another game. Roman leaves a word for each of them. Each word consists of 2·n binary characters "0" or "1". After that the players start moving in turns. Yaroslav moves fir...
1
#!/usr/bin/env python2 if __name__ == '__main__': n = raw_input() s1, s2 = raw_input(), raw_input() count = {'11': 0, '10': 0, '01': 0, '00': 0} for i in range(0, len(s1)): count[s1[i] + s2[i]] += 1 fst, snd = 0, 0 fst += count['11'] & 1 tmp = min(count['10'], count['01']) co...
You are given a string s of even length n. String s is binary, in other words, consists only of 0's and 1's. String s has exactly n/2 zeroes and n/2 ones (n is even). In one operation you can reverse any substring of s. A substring of a string is a contiguous subsequence of that string. What is the minimum number of...
3
import io import os from collections import Counter, defaultdict, deque def solve(N, S): pairZeroes = 0 pairOnes = 0 for x, y in zip(S, S[1:]): if x == y == "0": pairZeroes += 1 if x == y == "1": pairOnes += 1 return max(pairZeroes, pairOnes) if __name__ == ...
For a positive integer n let's define a function f: f(n) = - 1 + 2 - 3 + .. + ( - 1)nn Your task is to calculate f(n) for a given integer n. Input The single line contains the positive integer n (1 ≤ n ≤ 1015). Output Print f(n) in a single line. Examples Input 4 Output 2 Input 5 Output -3 Note f(4)...
3
def cf(n): if(n%2==0): return n//2 else: prev = (n-1)//2 return prev-n n = int(input()) print(cf(n))
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()) saida = [] for _ in range(n): word = input().strip() if len(word) <= 10: saida.append(word) else: first = word[0] last = word[-1] final_word = '{}{}{}'.format(first, len(word) - 2, last) saida.append(final_word) print('\n'.join(saida))
One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality ...
3
t=int(input()) bh=[] for i in range(t): bh.append([int(i) for i in input().split()]) av=0 for i in bh: if i[0]<i[1]: av=1 break if av==1: print("Happy Alex") else: print("Poor Alex")
Kyoya Ootori is selling photobooks of the Ouran High School Host Club. He has 26 photos, labeled "a" to "z", and he has compiled them into a photo booklet with some photos in some order (possibly with some photos being duplicated). A photo booklet can be described as a string of lowercase letters, consisting of the pho...
1
s = raw_input() len1 = len(s) a = [] a.extend(s) af = [] for i in a: if i not in af: af.append(i) len2 = len(af) print ((len1+1)*26 - len1)
Igor is in the museum and he wants to see as many pictures as possible. Museum can be represented as a rectangular field of n × m cells. Each cell is either empty or impassable. Empty cells are marked with '.', impassable cells are marked with '*'. Every two adjacent cells of different types (one empty and one impassa...
3
import sys,io,os from atexit import register input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline sys.stdout = io.BytesIO() register(lambda :os.write(1,sys.stdout.getvalue())) def print(args=[], sep=' ', end='\n', file=sys.stdout): first = True sep = sep.encode() for a in args: if first: firs...
You are given two positive integers n (1 ≤ n ≤ 10^9) and k (1 ≤ k ≤ 100). Represent the number n as the sum of k positive integers of the same parity (have the same remainder when divided by 2). In other words, find a_1, a_2, …, a_k such that all a_i>0, n = a_1 + a_2 + … + a_k and either all a_i are even or all a_i ar...
3
I = input t = int(I()) for _ in range(t): n, k = map(int, I().split()) if n % 2 == 0: if k > n // 2: if k-1 > n or (k-1) % 2 == 0: print('NO') continue print('YES') print(n-(k-1), *[1]*(k-1)) continue print('YES') ...
The R1 company wants to hold a web search championship. There were n computers given for the competition, each of them is connected to the Internet. The organizers believe that the data transfer speed directly affects the result. The higher the speed of the Internet is, the faster the participant will find the necessar...
1
n, k = map(int, raw_input().split(" ")) C = sorted(map(int, raw_input().split(" ")), reverse=True) print C[k-1]
Robot Doc is located in the hall, with n computers stand in a line, numbered from left to right from 1 to n. Each computer contains exactly one piece of information, each of which Doc wants to get eventually. The computers are equipped with a security system, so to crack the i-th of them, the robot needs to collect at ...
3
n=int(input()) l=[int(x) for x in input().split()] done=0 c=0 s=set([]) while(done<n): if c%2==0: for i in range(n): if done>=l[i] and i not in s: done+=1 s.add(i) else: for i in range(n-1,-1,-1): if done>=l[i] and i not in s: ...
You are given an array A of length N. Your task is to divide it into several contiguous subarrays. Here, all subarrays obtained must be sorted in either non-decreasing or non-increasing order. At least how many subarrays do you need to divide A into? Constraints * 1 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * Each A_i ...
3
N = int(input()) A = list(map(int,input().split())) ans = 1 d = 0 tmp = A[0] for a in A[1:]: if d*(a-tmp) < 0: ans += 1 d = 0 else: d += a-tmp tmp = a print(ans)
We know that prime numbers are positive integers that have exactly two distinct positive divisors. Similarly, we'll call a positive integer t Т-prime, if t has exactly three distinct positive divisors. You are given an array of n positive integers. For each of them determine whether it is Т-prime or not. Input The f...
3
import math numbers = [True] * (10**6 + 1) numbers[0] = numbers[1] = False for i in range(2, int(math.sqrt(len(numbers)))): if numbers[i]: for j in range(i**2, len(numbers), i): numbers[j] = False square_numbers = frozenset([i ** 2 for i in range(len(numbers)) if numbers[i]]) n = int(input()...
Let's consider equation: x2 + s(x)·x - n = 0, where x, n are positive integers, s(x) is the function, equal to the sum of digits of number x in the decimal number system. You are given an integer n, find the smallest positive integer root of equation x, or else determine that there are no such roots. Input A sing...
3
import math def suu(nn): ans=0 while nn>0: ans+=nn%10 nn=nn//10 return ans n = int(input()) for i in range(1,9*18+1): x = int((-i + math.sqrt(i*i +4*n ))/2) if(x*x + i*x -n ==0 and suu(x)==i): print(x) exit() print(-1)
After finishing eating her bun, Alyona came up with two integers n and m. She decided to write down two columns of integers — the first column containing integers from 1 to n and the second containing integers from 1 to m. Now the girl wants to count how many pairs of integers she can choose, one from the first column ...
1
n, m = map(int, raw_input().split()) rec1 = [0 for i in xrange(5)] rec2 = [0 for i in xrange(5)] for i in xrange(1, n + 1) : rec1[i % 5] +=1 for i in xrange(1, m + 1): rec2[i % 5] += 1 ans = 0 for i in xrange(5): ans += rec2[(5 - i) % 5] * rec1[i] print ans
Vasya wants to turn on Christmas lights consisting of m bulbs. Initially, all bulbs are turned off. There are n buttons, each of them is connected to some set of bulbs. Vasya can press any of these buttons. When the button is pressed, it turns on all the bulbs it's connected to. Can Vasya light up all the bulbs? If Va...
3
n, m = map(int, input().split()) ll = [] for i in range(n): k = list(map(int, input().split())) for j in range(1,k[0]+1): ll.append(k[j]) ll = set(ll) ll = list(ll) if ll == [int(i) for i in range(1,m+1)]: print('YES') else: print('NO')
You are given n strings. Each string consists of lowercase English letters. Rearrange (reorder) the given strings in such a way that for every string, all strings that are placed before it are its substrings. String a is a substring of string b if it is possible to choose several consecutive letters in b in such a way...
3
def main(): n = int(input()) s = [] for _ in range(n): s.append(input()) for i in range(n-1): for j in range(i+1, n): if len(s[j]) < len(s[i]): s[i], s[j] = s[j], s[i] ok = True for i in range(n-1): for j in range(i+1, n): if s[i]...
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
inp = input() n = (len(inp)) // 2 flag = 0 for i in inp[1:]: if (i != '0'): flag = 1 break print(n + flag if len(inp) % 2 else n)
Write a program which reads two integers a and b, and calculates the following values: * a ÷ b: d (in integer) * remainder of a ÷ b: r (in integer) * a ÷ b: f (in real number) Constraints * 1 ≤ a, b ≤ 109 Input Two integers a and b are given in a line. Output Print d, r and f separated by a space in a line. For ...
1
x,y=map(int,raw_input().split()) print "%d %d %f" % (x/y,x%y,float(x)/y)
Top-model Izabella participates in the competition. She wants to impress judges and show her mathematical skills. Her problem is following: for given string, consisting of only 0 and 1, tell if it's possible to remove some digits in such a way, that remaining number is a representation of some positive integer, divisi...
3
s = input() one = s.find('1') zero = s[one + 1 :].count('0') if one != -1 and zero >= 6: print('yes') else: print('no')
Let's denote correct match equation (we will denote it as CME) an equation a + b = c there all integers a, b and c are greater than zero. For example, equations 2 + 2 = 4 (||+||=||||) and 1 + 2 = 3 (|+||=|||) are CME but equations 1 + 2 = 4 (|+||=||||), 2 + 2 = 3 (||+||=|||), and 0 + 1 = 1 (+|=|) are not. Now, you ha...
3
q = int(input()) arr = [] for i in range(q): n = int(input()) if n == 2: arr.append(2) elif n % 2 == 0: arr.append(0) else: arr.append(1) for num in arr: print(num)
Mr. Santa asks all the great programmers of the world to solve a trivial problem. He gives them an integer m and asks for the number of positive integers n, such that the factorial of n ends with exactly m zeroes. Are you among those great programmers who can solve this problem? Input The only line of input contains ...
3
def tra0(n): ans = 0 i = 1 while 5**i <= n: ans += n//(5**i) i += 1 return ans a = int(input()) i = 0 while True: temp = tra0(i) if temp == a: print(5) [print(s, end = ' ') for s in range(i, i+5)] print() exit() elif temp > a: print(0) exit() i += 5
Polycarp decided to relax on his weekend and visited to the performance of famous ropewalkers: Agafon, Boniface and Konrad. The rope is straight and infinite in both directions. At the beginning of the performance, Agafon, Boniface and Konrad are located in positions a, b and c respectively. At the end of the performa...
3
a, b, c, d = map(int, input().split()) a, b, c = sorted([a, b, c]) print(max(0, d - abs(b - a)) + max(0, d - abs(c - b)))
There is a factory that inputs the data of the side and diagonal lengths to the machine and cuts out the plastic plate. At this factory, we cut out only parallelogram molds, although they vary in size. You have been ordered by your boss to count the number of rectangles and rhombuses produced among the parallelograms t...
1
import sys ch, hi = 0, 0 for line in sys.stdin: a, b, c = map(int, line.rstrip().split(',')) if a == b: hi += 1 if a*a + b*b == c*c: ch += 1 print ch print hi
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()) ans = [0] * 3 for i in range(n): tmp = [int(x) for x in input().split()] for j in range(3): ans[j] += tmp[j] print("YES" if (ans[0] == ans[1] == ans[2] == 0) else "NO")
In this problem, your task is to use ASCII graphics to paint a cardiogram. A cardiogram is a polyline with the following corners: <image> That is, a cardiogram is fully defined by a sequence of positive integers a1, a2, ..., an. Your task is to paint a cardiogram by given sequence ai. Input The first line contai...
3
n, a = int(input()), list(map(int, input().split())) if n & 1: a.append(0) x, t = 0, [[' '] * sum(a) for i in range(2001)] y = u = v = 1000 for i in range(0, n, 2): for j in range(a[i]): t[y][x] = '/' x += 1 y += 1 v = max(v, y) for j in range(a[i + 1]): y -= 1 t[y][x...
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
from sys import stdin, exit s = stdin.readline().rstrip() prints = frozenset(['H', 'Q', '9']) for char in s: if char in prints: print('YES') exit() print('NO')
The only difference between easy and hard versions are constraints on n and k. You are messaging in one of the popular social networks via your smartphone. Your smartphone can show at most k most recent conversations with your friends. Initially, the screen is empty (i.e. the number of displayed conversations equals 0...
3
n, k = [int(i) for i in input().split()] arr = [int(i) for i in input().split()] dic = {} calls = [] qtd = 0 for i in range(n): x = arr[i] if(x not in dic or dic[x]<qtd-k): dic[x] = qtd calls+=[x] qtd+=1 st = "" for i in range(min(qtd,k)): st+=str(calls[qtd-i-1])+' ' print(min(qtd,k)) print(st)