index
int64
0
5.16k
difficulty
int64
7
12
question
stringlengths
126
7.12k
solution
stringlengths
30
18.6k
test_cases
dict
3,700
7
[Thanos sort](https://codegolf.stackexchange.com/questions/182221/implement-the-thanos-sorting-algorithm) is a supervillain sorting algorithm, which works as follows: if the array is not sorted, snap your fingers* to remove the first or the second half of the items, and repeat the process. Given an input array, what is the size of the longest sorted array you can obtain from it using Thanos sort? *Infinity Gauntlet required. Input The first line of input contains a single number n (1 ≀ n ≀ 16) β€” the size of the array. n is guaranteed to be a power of 2. The second line of input contains n space-separated integers a_i (1 ≀ a_i ≀ 100) β€” the elements of the array. Output Return the maximal length of a sorted array you can obtain using Thanos sort. The elements of the array have to be sorted in non-decreasing order. Examples Input 4 1 2 2 4 Output 4 Input 8 11 12 1 2 13 14 3 4 Output 2 Input 4 7 6 5 4 Output 1 Note In the first example the array is already sorted, so no finger snaps are required. In the second example the array actually has a subarray of 4 sorted elements, but you can not remove elements from different sides of the array in one finger snap. Each time you have to remove either the whole first half or the whole second half, so you'll have to snap your fingers twice to get to a 2-element sorted array. In the third example the array is sorted in decreasing order, so you can only save one element from the ultimate destruction.
def f(a): if(sorted(a)==a): return len(a) k = len(a)//2 return max(f(a[:k]),f(a[k:])) n = input() a = [int(i) for i in input().split()] print(f(a))
{ "input": [ "4\n7 6 5 4\n", "8\n11 12 1 2 13 14 3 4\n", "4\n1 2 2 4\n" ], "output": [ "1\n", "2\n", "4\n" ] }
3,701
12
The only difference between easy and hard versions is constraints. Ivan plays a computer game that contains some microtransactions to make characters look cooler. Since Ivan wants his character to be really cool, he wants to use some of these microtransactions β€” and he won't start playing until he gets all of them. Each day (during the morning) Ivan earns exactly one burle. There are n types of microtransactions in the game. Each microtransaction costs 2 burles usually and 1 burle if it is on sale. Ivan has to order exactly k_i microtransactions of the i-th type (he orders microtransactions during the evening). Ivan can order any (possibly zero) number of microtransactions of any types during any day (of course, if he has enough money to do it). If the microtransaction he wants to order is on sale then he can buy it for 1 burle and otherwise he can buy it for 2 burles. There are also m special offers in the game shop. The j-th offer (d_j, t_j) means that microtransactions of the t_j-th type are on sale during the d_j-th day. Ivan wants to order all microtransactions as soon as possible. Your task is to calculate the minimum day when he can buy all microtransactions he want and actually start playing. Input The first line of the input contains two integers n and m (1 ≀ n, m ≀ 2 β‹… 10^5) β€” the number of types of microtransactions and the number of special offers in the game shop. The second line of the input contains n integers k_1, k_2, ..., k_n (0 ≀ k_i ≀ 2 β‹… 10^5), where k_i is the number of copies of microtransaction of the i-th type Ivan has to order. It is guaranteed that sum of all k_i is not less than 1 and not greater than 2 β‹… 10^5. The next m lines contain special offers. The j-th of these lines contains the j-th special offer. It is given as a pair of integers (d_j, t_j) (1 ≀ d_j ≀ 2 β‹… 10^5, 1 ≀ t_j ≀ n) and means that microtransactions of the t_j-th type are on sale during the d_j-th day. Output Print one integer β€” the minimum day when Ivan can order all microtransactions he wants and actually start playing. Examples Input 5 6 1 2 0 2 0 2 4 3 3 1 5 1 2 1 5 2 3 Output 8 Input 5 3 4 2 1 3 2 3 5 4 2 2 5 Output 20
def check(mid): l = [0 for i in range(n)] for i in b: if(i[0] > mid): break l[i[1]-1] = i[0] v = [0 for i in range(mid+1)] for i in range(n): v[l[i]] += a[i] ct = 0 for i in range(1,mid+1): ct += 1 if(ct >= v[i]): ct -= v[i] v[i] = 0 else: v[i] -= ct ct = 0 return ct >= 2*sum(v) def bs(): l = 0 r = 5*10**5 while(l <= r): mid = (l+r)//2 if(check(mid)): r = mid-1 else: l = mid+1 return r+1 n,m = map(int,input().split()) a = list(map(int,input().split())) b = [] for i in range(m): b.append(list(map(int,input().split()))) b.sort() print(bs())
{ "input": [ "5 6\n1 2 0 2 0\n2 4\n3 3\n1 5\n1 2\n1 5\n2 3\n", "5 3\n4 2 1 3 2\n3 5\n4 2\n2 5\n" ], "output": [ "8\n", "20\n" ] }
3,702
11
Heidi found out that the Daleks have created a network of bidirectional Time Corridors connecting different destinations (at different times!). She suspects that they are planning another invasion on the entire Space and Time. In order to counter the invasion, she plans to deploy a trap in the Time Vortex, along a carefully chosen Time Corridor. She knows that tinkering with the Time Vortex is dangerous, so she consulted the Doctor on how to proceed. She has learned the following: * Different Time Corridors require different amounts of energy to keep stable. * Daleks are unlikely to use all corridors in their invasion. They will pick a set of Corridors that requires the smallest total energy to maintain, yet still makes (time) travel possible between any two destinations (for those in the know: they will use a minimum spanning tree). * Setting the trap may modify the energy required to keep the Corridor stable. Heidi decided to carry out a field test and deploy one trap, placing it along the first Corridor. But she needs to know whether the Daleks are going to use this corridor after the deployment of the trap. She gives you a map of Time Corridors (an undirected graph) with energy requirements for each Corridor. For a Corridor c, E_{max}(c) is the largest e ≀ 10^9 such that if we changed the required amount of energy of c to e, then the Daleks may still be using c in their invasion (that is, it belongs to some minimum spanning tree). Your task is to calculate E_{max}(c_1) for the Corridor c_1 that Heidi plans to arm with a trap, which is the first edge in the graph. Input The first line contains integers n and m (2 ≀ n ≀ 10^5, n - 1 ≀ m ≀ 10^6), number of destinations to be invaded and the number of Time Corridors. Each of the next m lines describes a Corridor: destinations a, b and energy e (1 ≀ a, b ≀ n, a β‰  b, 0 ≀ e ≀ 10^9). It's guaranteed, that no pair \\{a, b\} will repeat and that the graph is connected β€” that is, it is possible to travel between any two destinations using zero or more Time Corridors. Output Output a single integer: E_{max}(c_1) for the first Corridor c_1 from the input. Example Input 3 3 1 2 8 2 3 3 3 1 4 Output 4 Note After the trap is set, the new energy requirement for the first Corridor may be either smaller, larger, or equal to the old energy requiremenet. In the example, if the energy of the first Corridor is set to 4 or less, then the Daleks may use the set of Corridors \{ \{ 1,2 \}, \{ 2,3 \} \} (in particular, if it were set to less than 4, then this would be the only set of Corridors that they would use). However, if it is larger than 4, then they will instead use the set \{ \{2,3\}, \{3,1\} \}.
def naiveSolve(): return class UnionFind: def __init__(self, n): self.parent = list(range(n)) def find(self, a): #return parent of a. a and b are in same set if they have same parent acopy = a while a != self.parent[a]: a = self.parent[a] while acopy != a: #path compression self.parent[acopy], acopy = a, self.parent[acopy] return a def union(self, a, b): #union a and b self.parent[self.find(b)] = self.find(a) def main(): n,m=readIntArr() cab=[] # (cost,a,b) first=-1 # first (cost,a,b) for _ in range(m): a,b,c=readIntArr() if first==-1: # exclude the 1st one first first=(c,a,b) else: cab.append((c,a,b)) if n==2 or m+1==n: print(int(1e9)) return a1,b1=first[1],first[2] cab.sort() uf=UnionFind(n+1) ans=int(1e9) for c,a,b in cab: if uf.find(a)!=uf.find(b): uf.union(a,b) if uf.find(a1)==uf.find(b1): ans=c break print(ans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(r): print('? {}'.format(r)) sys.stdout.flush() return readIntArr() def answerInteractive(adj,n): print('!') for u in range(1,n+1): for v in adj[u]: if v>u: print('{} {}'.format(u,v)) sys.stdout.flush() inf=float('inf') MOD=10**9+7 # MOD=998244353 from math import gcd,floor,ceil # from math import floor,ceil # for Python2 for _abc in range(1): main()
{ "input": [ "3 3\n1 2 8\n2 3 3\n3 1 4\n" ], "output": [ "4\n" ] }
3,703
9
You are given an array a consisting of n integers. Your task is to say the number of such positive integers x such that x divides each number from the array. In other words, you have to find the number of common divisors of all elements in the array. For example, if the array a will be [2, 4, 6, 2, 10], then 1 and 2 divide each number from the array (so the answer for this test is 2). Input The first line of the input contains one integer n (1 ≀ n ≀ 4 β‹… 10^5) β€” the number of elements in a. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 10^{12}), where a_i is the i-th element of a. Output Print one integer β€” the number of such positive integers x such that x divides each number from the given array (in other words, the answer is the number of common divisors of all elements in the array). Examples Input 5 1 2 3 4 5 Output 1 Input 6 6 90 12 18 30 18 Output 4
import functools as f import math as m def gcd_list(l): return f.reduce(m.gcd,l) n,g=input(),gcd_list((map(int,input().split()))) sq=int(m.sqrt(g));c=0 for i in range(1,sq+1): if i*i==g:c+=1 elif g%i==0:c+=2 print(c)
{ "input": [ "5\n1 2 3 4 5\n", "6\n6 90 12 18 30 18\n" ], "output": [ "1\n", "4\n" ] }
3,704
8
Let n be a positive integer. Let a, b, c be nonnegative integers such that a + b + c = n. Alice and Bob are gonna play rock-paper-scissors n times. Alice knows the sequences of hands that Bob will play. However, Alice has to play rock a times, paper b times, and scissors c times. Alice wins if she beats Bob in at least ⌈ n/2 βŒ‰ (n/2 rounded up to the nearest integer) hands, otherwise Alice loses. Note that in rock-paper-scissors: * rock beats scissors; * paper beats rock; * scissors beat paper. The task is, given the sequence of hands that Bob will play, and the numbers a, b, c, determine whether or not Alice can win. And if so, find any possible sequence of hands that Alice can use to win. If there are multiple answers, print any of them. Input The first line contains a single integer t (1 ≀ t ≀ 100) β€” the number of test cases. Then, t testcases follow, each consisting of three lines: * The first line contains a single integer n (1 ≀ n ≀ 100). * The second line contains three integers, a, b, c (0 ≀ a, b, c ≀ n). It is guaranteed that a + b + c = n. * The third line contains a string s of length n. s is made up of only 'R', 'P', and 'S'. The i-th character is 'R' if for his i-th Bob plays rock, 'P' if paper, and 'S' if scissors. Output For each testcase: * If Alice cannot win, print "NO" (without the quotes). * Otherwise, print "YES" (without the quotes). Also, print a string t of length n made up of only 'R', 'P', and 'S' β€” a sequence of hands that Alice can use to win. t must contain exactly a 'R's, b 'P's, and c 'S's. * If there are multiple answers, print any of them. The "YES" / "NO" part of the output is case-insensitive (i.e. "yEs", "no" or "YEs" are all valid answers). Note that 'R', 'P' and 'S' are case-sensitive. Example Input 2 3 1 1 1 RPS 3 3 0 0 RPS Output YES PSR NO Note In the first testcase, in the first hand, Alice plays paper and Bob plays rock, so Alice beats Bob. In the second hand, Alice plays scissors and Bob plays paper, so Alice beats Bob. In the third hand, Alice plays rock and Bob plays scissors, so Alice beats Bob. Alice beat Bob 3 times, and 3 β‰₯ ⌈ 3/2 βŒ‰ = 2, so Alice wins. In the second testcase, the only sequence of hands that Alice can play is "RRR". Alice beats Bob only in the last hand, so Alice can't win. 1 < ⌈ 3/2 βŒ‰ = 2.
import sys def I(): return sys.stdin.readline().rstrip() for _ in range( int( I() ) ): n = int( I() ) c = list( map( int, I().split() ) ) m = [ "R", "P", "S" ] d = [ "S", "R", "P" ] bob = I() alice = [] ans = 0 for h in bob: i = d.index( h ) al = None if c[ i ] > 0: c[ i ] -= 1 al = m[ i ] ans += 1 alice.append( al ) for i in range( n ): if alice[ i ] == None: for j in range( 3 ): if c[ j ] > 0: c[ j ] -= 1 alice[ i ] = m[ j ] break if ans >= (n + 1) // 2: print( "YES" ) print( "".join( alice ) ) else: print( "NO" )
{ "input": [ "2\n3\n1 1 1\nRPS\n3\n3 0 0\nRPS\n" ], "output": [ "YES\nPSR\nNO\n" ] }
3,705
12
The well-known Fibonacci sequence F_0, F_1, F_2,… is defined as follows: * F_0 = 0, F_1 = 1. * For each i β‰₯ 2: F_i = F_{i - 1} + F_{i - 2}. Given an increasing arithmetic sequence of positive integers with n elements: (a, a + d, a + 2β‹… d,…, a + (n - 1)β‹… d). You need to find another increasing arithmetic sequence of positive integers with n elements (b, b + e, b + 2β‹… e,…, b + (n - 1)β‹… e) such that: * 0 < b, e < 2^{64}, * for all 0≀ i < n, the decimal representation of a + i β‹… d appears as substring in the last 18 digits of the decimal representation of F_{b + i β‹… e} (if this number has less than 18 digits, then we consider all its digits). Input The first line contains three positive integers n, a, d (1 ≀ n, a, d, a + (n - 1) β‹… d < 10^6). Output If no such arithmetic sequence exists, print -1. Otherwise, print two integers b and e, separated by space in a single line (0 < b, e < 2^{64}). If there are many answers, you can output any of them. Examples Input 3 1 1 Output 2 1 Input 5 1 2 Output 19 5 Note In the first test case, we can choose (b, e) = (2, 1), because F_2 = 1, F_3 = 2, F_4 = 3. In the second test case, we can choose (b, e) = (19, 5) because: * F_{19} = 4181 contains 1; * F_{24} = 46368 contains 3; * F_{29} = 514229 contains 5; * F_{34} = 5702887 contains 7; * F_{39} = 63245986 contains 9.
''' import os,sys,random MOD=10**18 def MUL(a,b): global MOD c=[[0,0],[0,0]] for i in range(2): for j in range(2): for k in range(2): c[i][k]=(c[i][k]+a[i][j]*b[j][k])%MOD return c def POW(a,b): r=[[1,0],[0,1]] while b: if b&1:r=MUL(r,a) a=MUL(a,a);b>>=1 return r print(POW([[0,1],[1,1]],int(input()))) #input:1200000002 #output:584177449000000001 #inv of 584177449:614945049 ''' n,a,d=map(int,input().split()) A=614945049;N=10**9;M=3*N//2 print(A*a%N*M+1,A*d%N*M)
{ "input": [ "5 1 2\n", "3 1 1\n" ], "output": [ "4417573500000000001 8835147000000000000\n", "4417573500000000001 4417573500000000000\n" ] }
3,706
9
This problem is different with hard version only by constraints on total answers length It is an interactive problem Venya joined a tour to the madhouse, in which orderlies play with patients the following game. Orderlies pick a string s of length n, consisting only of lowercase English letters. The player can ask two types of queries: * ? l r – ask to list all substrings of s[l..r]. Substrings will be returned in random order, and in every substring, all characters will be randomly shuffled. * ! s – guess the string picked by the orderlies. This query can be asked exactly once, after that the game will finish. If the string is guessed correctly, the player wins, otherwise he loses. The player can ask no more than 3 queries of the first type. To make it easier for the orderlies, there is an additional limitation: the total number of returned substrings in all queries of the first type must not exceed (n+1)^2. Venya asked you to write a program, which will guess the string by interacting with the orderlies' program and acting by the game's rules. Your program should immediately terminate after guessing the string using a query of the second type. In case your program guessed the string incorrectly, or it violated the game rules, it will receive verdict Wrong answer. Note that in every test case the string is fixed beforehand and will not change during the game, which means that the interactor is not adaptive. Input First line contains number n (1 ≀ n ≀ 100) β€” the length of the picked string. Interaction You start the interaction by reading the number n. To ask a query about a substring from l to r inclusively (1 ≀ l ≀ r ≀ n), you should output ? l r on a separate line. After this, all substrings of s[l..r] will be returned in random order, each substring exactly once. In every returned substring all characters will be randomly shuffled. In the case, if you ask an incorrect query, ask more than 3 queries of the first type or there will be more than (n+1)^2 substrings returned in total, you will receive verdict Wrong answer. To guess the string s, you should output ! s on a separate line. After printing each query, do not forget to flush the output. Otherwise, you will get Idleness limit exceeded. To flush the output, you can use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If you received - (dash) as an answer to any query, you need to terminate your program with exit code 0 (for example, by calling exit(0)). This means that there was an error in the interaction protocol. If you don't terminate with exit code 0, you can receive any unsuccessful verdict. Hack format To hack a solution, use the following format: The first line should contain one integer n (1 ≀ n ≀ 100) β€” the length of the string, and the following line should contain the string s. Example Input 4 a aa a cb b c c Output ? 1 2 ? 3 4 ? 4 4 ! aabc
from bisect import bisect_left as bl from bisect import bisect_right as br import heapq import math from collections import * from functools import reduce,cmp_to_key import sys input = sys.stdin.readline # M = mod = 998244353 def factors(n):return sorted(list(set(reduce(list.__add__,([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))) # def inv_mod(n):return pow(n, mod - 2, mod) def li():return [int(i) for i in input().rstrip('\n').split(' ')] def st():return input().rstrip('\n') def val():return int(input().rstrip('\n')) def li2():return [i for i in input().rstrip('\n').split(' ')] def li3():return [int(i) for i in input().rstrip('\n')] n = val() cnt1 = Counter() cnt2 = Counter() print('? 1 ' + str(n),flush = True) le = 0 for i in range(n): for j in range(i+1,n+1):le += 1 for j in range(le): cnt1[''.join(sorted(st()))] += 1 if n == 1: for i in cnt1.keys(): print('! ' + str(i),flush = True) exit() print('? 2 ' + str(n),flush = True) le = 0 for i in range(1,n): for j in range(i+1,n+1):le += 1 # print(le) for i in range(le): cnt2[''.join(sorted(st()))] += 1 cnt1 -= cnt2 cnt1 = sorted(list(cnt1),key = lambda x:len(x)) s = '' currcount = Counter() for i in cnt1: currcount = Counter(s) for j in i: if not currcount[j]: s += j break currcount[j] -= 1 print('! ' + s,flush = True)
{ "input": [ "4\n\na\naa\na\n\ncb\nb\nc\n\nc" ], "output": [ "? 1 2\n? 2 2\n? 1 4\n! aacb\n" ] }
3,707
7
INTERCAL is the oldest of esoteric programming languages. One of its many weird features is the method of character-based output, known as Turing Tape method. It converts an array of unsigned 8-bit integers into a sequence of characters to print, using the following method. The integers of the array are processed one by one, starting from the first. Processing i-th element of the array is done in three steps: 1. The 8-bit binary notation of the ASCII-code of the previous printed character is reversed. When the first element of the array is processed, the result of this step is considered to be 0. 2. The i-th element of the array is subtracted from the result of the previous step modulo 256. 3. The binary notation of the result of the previous step is reversed again to produce ASCII-code of the i-th character to be printed. You are given the text printed using this method. Restore the array used to produce this text. Input The input will consist of a single line text which contains the message printed using the described method. String text will contain between 1 and 100 characters, inclusive. ASCII-code of each character of text will be between 32 (space) and 126 (tilde), inclusive. Output Output the initial array, which was used to produce text, one integer per line. Examples Input Hello, World! Output 238 108 112 0 64 194 48 26 244 168 24 16 162 Note Let's have a closer look at the beginning of the example. The first character is "H" with ASCII-code 72 = 010010002. Its reverse is 000100102 = 18, and this number should become the result of the second step of processing. The result of the first step is considered to be 0, so the first element of the array has to be (0 - 18) mod 256 = 238, where a mod b is the remainder of division of a by b.
def f(x): return int(format(256 + x, 'b')[:: -1][: -1], 2) t, x = input(), 0 for i in t: y = f(ord(i)) print((x - y) % 256) x = y
{ "input": [ "Hello, World!\n" ], "output": [ "238\n108\n112\n0\n64\n194\n48\n26\n244\n168\n24\n16\n162\n" ] }
3,708
10
Little Petya very much likes rectangles and especially squares. Recently he has received 8 points on the plane as a gift from his mother. The points are pairwise distinct. Petya decided to split them into two sets each containing 4 points so that the points from the first set lay at the vertexes of some square and the points from the second set lay at the vertexes of a rectangle. Each point of initial 8 should belong to exactly one set. It is acceptable for a rectangle from the second set was also a square. If there are several partitions, Petya will be satisfied by any of them. Help him find such partition. Note that the rectangle and the square from the partition should have non-zero areas. The sides of the figures do not have to be parallel to the coordinate axes, though it might be the case. Input You are given 8 pairs of integers, a pair per line β€” the coordinates of the points Petya has. The absolute value of all coordinates does not exceed 104. It is guaranteed that no two points coincide. Output Print in the first output line "YES" (without the quotes), if the desired partition exists. In the second line output 4 space-separated numbers β€” point indexes from the input, which lie at the vertexes of the square. The points are numbered starting from 1. The numbers can be printed in any order. In the third line print the indexes of points lying at the vertexes of a rectangle in the similar format. All printed numbers should be pairwise distinct. If the required partition does not exist, the first line should contain the word "NO" (without the quotes), after which no output is needed. Examples Input 0 0 10 11 10 0 0 11 1 1 2 2 2 1 1 2 Output YES 5 6 7 8 1 2 3 4 Input 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 Output NO Input 0 0 4 4 4 0 0 4 1 2 2 3 3 2 2 1 Output YES 1 2 3 4 5 6 7 8 Note Pay attention to the third example: the figures do not necessarily have to be parallel to the coordinate axes.
from sys import stdin, stdout from itertools import permutations as p from itertools import combinations as com def sqr_or_rec(a, b, c, d): x = ((a[1] - b[1])**2 + (a[0] - b[0]) **2) y = ((c[1] - b[1])**2 + (c[0] - b[0]) **2) w = ((c[1] - d[1])**2 + (c[0] - d[0]) **2) z = ((a[1] - d[1])**2 + (a[0] - d[0]) **2) hypo1 = ((a[1] - c[1])**2 + (a[0] - c[0]) **2) hypo2 = ((b[1] - d[1])**2 + (b[0] - d[0]) **2) if len(set([x,y,w,z])) == 1 and hypo1 == x + y and hypo2 == hypo1 and hypo2 == w + z: return 0 elif len(set([x,y,w,z])) == 2 and hypo1 == x + y and hypo2 == hypo1 and hypo2 == w + z: return 1 else: return -1 x = [] for i in range(8): l, m = map(int, input().split()) x.append([l, m]) sqr, rec = [], [] for g in p(list(range(8)), 4): a, b, c, d = x[g[0]], x[g[1]], x[g[2]], x[g[3]] if sqr_or_rec(a,b,c,d) == 0: y = sorted(g) if y not in sqr: sqr.append(y) elif sqr_or_rec(a,b,c,d) == 1: y = sorted(g) if y not in rec: rec.append(y) if len(sqr) == 0 or (len(sqr) == 1 and len(rec) == 0): print("NO") else: if len(sqr) >= 2: for q in com(sqr, 2): if len(set(q[0] + q[1])) == 8: print("YES") for k in sqr[0]: stdout.write(str(k+1)+" ") print() for k in sqr[1]: stdout.write(str(k+1)+" ") print() exit() for q in rec: if len(set(q + sqr[0])) == 8: print("YES") for k in sqr[0]: stdout.write(str(k+1)+" ") print() for k in q: stdout.write(str(k+1)+" ") print() exit() print("NO")
{ "input": [ "0 0\n10 11\n10 0\n0 11\n1 1\n2 2\n2 1\n1 2\n", "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 6\n7 7\n", "0 0\n4 4\n4 0\n0 4\n1 2\n2 3\n3 2\n2 1\n" ], "output": [ "YES\n5 6 7 8\n1 2 3 4\n", "NO\n", "YES\n1 2 3 4\n5 6 7 8\n" ] }
3,709
10
Omkar is playing his favorite pixelated video game, Bed Wars! In Bed Wars, there are n players arranged in a circle, so that for all j such that 2 ≀ j ≀ n, player j - 1 is to the left of the player j, and player j is to the right of player j - 1. Additionally, player n is to the left of player 1, and player 1 is to the right of player n. Currently, each player is attacking either the player to their left or the player to their right. This means that each player is currently being attacked by either 0, 1, or 2 other players. A key element of Bed Wars strategy is that if a player is being attacked by exactly 1 other player, then they should logically attack that player in response. If instead a player is being attacked by 0 or 2 other players, then Bed Wars strategy says that the player can logically attack either of the adjacent players. Unfortunately, it might be that some players in this game are not following Bed Wars strategy correctly. Omkar is aware of whom each player is currently attacking, and he can talk to any amount of the n players in the game to make them instead attack another player β€” i. e. if they are currently attacking the player to their left, Omkar can convince them to instead attack the player to their right; if they are currently attacking the player to their right, Omkar can convince them to instead attack the player to their left. Omkar would like all players to be acting logically. Calculate the minimum amount of players that Omkar needs to talk to so that after all players he talked to (if any) have changed which player they are attacking, all players are acting logically according to Bed Wars strategy. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≀ t ≀ 10^4). The descriptions of the test cases follows. The first line of each test case contains one integer n (3 ≀ n ≀ 2 β‹… 10^5) β€” the amount of players (and therefore beds) in this game of Bed Wars. The second line of each test case contains a string s of length n. The j-th character of s is equal to L if the j-th player is attacking the player to their left, and R if the j-th player is attacking the player to their right. It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output one integer: the minimum number of players Omkar needs to talk to to make it so that all players are acting logically according to Bed Wars strategy. It can be proven that it is always possible for Omkar to achieve this under the given constraints. Example Input 5 4 RLRL 6 LRRRRL 8 RLLRRRLL 12 LLLLRRLRRRLL 5 RRRRR Output 0 1 1 3 2 Note In the first test case, players 1 and 2 are attacking each other, and players 3 and 4 are attacking each other. Each player is being attacked by exactly 1 other player, and each player is attacking the player that is attacking them, so all players are already being logical according to Bed Wars strategy and Omkar does not need to talk to any of them, making the answer 0. In the second test case, not every player acts logically: for example, player 3 is attacked only by player 2, but doesn't attack him in response. Omkar can talk to player 3 to convert the attack arrangement to LRLRRL, in which you can see that all players are being logical according to Bed Wars strategy, making the answer 1.
import math def func(): n=int(input()) s=input() end=n-1 while s[end]==s[0] and end>=0: end-=1 s=s[end+1:]+s[:end+1] if end==-1: x=0 if n%3!=0: x=1 return x+n//3 r,l,ans=0,0,0 for i in range(n): if(s[i]=="R"): r+=1 ans+=int(l//3) l=0 else: l+=1 ans+=int(r//3) r=0 ans+=int(l//3)+int(r//3) return ans t=int(input()) while t>0: t-=1 print(func())
{ "input": [ "5\n4\nRLRL\n6\nLRRRRL\n8\nRLLRRRLL\n12\nLLLLRRLRRRLL\n5\nRRRRR\n" ], "output": [ "0\n1\n1\n3\n2\n" ] }
3,710
11
One day, n people (n is an even number) met on a plaza and made two round dances, each round dance consists of exactly n/2 people. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Each person should belong to exactly one of these two round dances. Round dance is a dance circle consisting of 1 or more people. Two round dances are indistinguishable (equal) if one can be transformed to another by choosing the first participant. For example, round dances [1, 3, 4, 2], [4, 2, 1, 3] and [2, 1, 3, 4] are indistinguishable. For example, if n=2 then the number of ways is 1: one round dance consists of the first person and the second one of the second person. For example, if n=4 then the number of ways is 3. Possible options: * one round dance β€” [1,2], another β€” [3,4]; * one round dance β€” [2,4], another β€” [3,1]; * one round dance β€” [4,1], another β€” [3,2]. Your task is to find the number of ways n people can make two round dances if each round dance consists of exactly n/2 people. Input The input contains one integer n (2 ≀ n ≀ 20), n is an even number. Output Print one integer β€” the number of ways to make two round dances. It is guaranteed that the answer fits in the 64-bit integer data type. Examples Input 2 Output 1 Input 4 Output 3 Input 8 Output 1260 Input 20 Output 12164510040883200
n=int(input()) def fact(x): if(x<=1):return 1 return x*fact(x-1) print(2*fact(n-1)//n)
{ "input": [ "2\n", "20\n", "4\n", "8\n" ], "output": [ "1\n", "12164510040883200\n", "3\n", "1260\n" ] }
3,711
10
You are given a string s of 0's and 1's. You are allowed to perform the following operation: * choose a non-empty contiguous substring of s that contains an equal number of 0's and 1's; * flip all characters in the substring, that is, replace all 0's with 1's, and vice versa; * reverse the substring. For example, consider s = 00111011, and the following operation: * Choose the first six characters as the substring to act upon: 00111011. Note that the number of 0's and 1's are equal, so this is a legal choice. Choosing substrings 0, 110, or the entire string would not be possible. * Flip all characters in the substring: 11000111. * Reverse the substring: 10001111. Find the lexicographically smallest string that can be obtained from s after zero or more operations. Input The first line contains a single integer T (1 ≀ T ≀ 5 β‹… 10^5) β€” the number of test cases. Each of the following T lines contains a single non-empty string β€” the input string s for the respective test case. All strings consist of characters 0 and 1, and their total length does not exceed 5 β‹… 10^5. Output For each test case, on a separate line print the lexicographically smallest string that can be obtained from s after zero or more operations. Example Input 3 100101 1100011 10101010 Output 010110 0110110 10101010 Note In the first test case a single operation should be applied to the entire string. In the second test case two operations are needed: 0111001, 0110110. In the third test case the string stays the same after any operation.
import os import sys from io import BytesIO, IOBase def main(): pass # region fastio 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.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") t = int(input()) START = 500001 seen = [0] * (2 * START) while t > 0: t -= 1 s = input() cur = START for c in s: if c == '0': seen[cur] += 1 cur -= 1 else: cur += 1 seen[cur] += 1 cur = START while True: if seen[cur] > 1 or seen[cur] > 0 and seen[cur + 1] == 0: seen[cur] -= 1 cur -= 1 print('0', end='', flush=False) elif seen[cur + 1] > 0: cur += 1 seen[cur] -= 1 print('1', end='', flush=False) else: break print(flush=False)
{ "input": [ "3\n100101\n1100011\n10101010\n" ], "output": [ "\n010110\n0110110\n10101010\n" ] }
3,712
10
Your friend Salem is Warawreh's brother and only loves math and geometry problems. He has solved plenty of such problems, but according to Warawreh, in order to graduate from university he has to solve more graph problems. Since Salem is not good with graphs he asked your help with the following problem. <image> You are given a complete directed graph with n vertices without self-loops. In other words, you have n vertices and each pair of vertices u and v (u β‰  v) has both directed edges (u, v) and (v, u). Every directed edge of the graph is labeled with a single character: either 'a' or 'b' (edges (u, v) and (v, u) may have different labels). You are also given an integer m > 0. You should find a path of length m such that the string obtained by writing out edges' labels when going along the path is a palindrome. The length of the path is the number of edges in it. You can visit the same vertex and the same directed edge any number of times. Input The first line contains a single integer t (1 ≀ t ≀ 500) β€” the number of test cases. The first line of each test case contains two integers n and m (2 ≀ n ≀ 1000; 1 ≀ m ≀ 10^{5}) β€” the number of vertices in the graph and desirable length of the palindrome. Each of the next n lines contains n characters. The j-th character of the i-th line describes the character on the edge that is going from node i to node j. Every character is either 'a' or 'b' if i β‰  j, or '*' if i = j, since the graph doesn't contain self-loops. It's guaranteed that the sum of n over test cases doesn't exceed 1000 and the sum of m doesn't exceed 10^5. Output For each test case, if it is possible to find such path, print "YES" and the path itself as a sequence of m + 1 integers: indices of vertices in the path in the appropriate order. If there are several valid paths, print any of them. Otherwise, (if there is no answer) print "NO". Example Input 5 3 1 *ba b*b ab* 3 3 *ba b*b ab* 3 4 *ba b*b ab* 4 6 *aaa b*ba ab*a bba* 2 6 *a b* Output YES 1 2 YES 2 1 3 2 YES 1 3 1 3 1 YES 1 2 1 3 4 1 4 NO Note The graph from the first three test cases is shown below: <image> In the first test case, the answer sequence is [1,2] which means that the path is: $$$1 \xrightarrow{b} 2$$$ So the string that is obtained by the given path is b. In the second test case, the answer sequence is [2,1,3,2] which means that the path is: $$$2 \xrightarrow{b} 1 \xrightarrow{a} 3 \xrightarrow{b} 2$$$ So the string that is obtained by the given path is bab. In the third test case, the answer sequence is [1,3,1,3,1] which means that the path is: $$$1 \xrightarrow{a} 3 \xrightarrow{a} 1 \xrightarrow{a} 3 \xrightarrow{a} 1$$$ So the string that is obtained by the given path is aaaa. The string obtained in the fourth test case is abaaba.
from itertools import cycle, islice def solve(): n, m = [int(t) for t in input().split()] g = [input() for _ in range(n)] for i in range(n): for j in range(i+1, n): if g[i][j] == g[j][i]: return repeat(i, j, m) if m % 2 == 1: return repeat(0, 1, m) if n >= 3: for x, y, z in (0, 1, 2), (1, 2, 0), (2, 0, 1): if g[x][y] == g[y][z]: if (m // 2) % 2 == 1: return repeat(x, y, m//2-1) + repeat(y, z, m//2) else: return repeat(y, x, m//2-1) + repeat(y, z, m//2) return None def repeat(i, j, k): return list(islice(cycle([i+1, j+1]), k+1)) for _ in range(int(input())): res = solve() if res is None: print("NO") else: print("YES") print(*res)
{ "input": [ "5\n3 1\n*ba\nb*b\nab*\n3 3\n*ba\nb*b\nab*\n3 4\n*ba\nb*b\nab*\n4 6\n*aaa\nb*ba\nab*a\nbba*\n2 6\n*a\nb*\n" ], "output": [ "\nYES\n1 2\nYES\n2 1 3 2\nYES\n1 3 1 3 1\nYES\n1 2 1 3 4 1 4\nNO\n" ] }
3,713
12
This is the easy version of the problem. The difference between the versions is the constraints on a_i. You can make hacks only if all versions of the problem are solved. Little Dormi has recently received a puzzle from his friend and needs your help to solve it. The puzzle consists of an upright board with n rows and m columns of cells, some empty and some filled with blocks of sand, and m non-negative integers a_1,a_2,…,a_m (0 ≀ a_i ≀ n). In this version of the problem, a_i will be equal to the number of blocks of sand in column i. When a cell filled with a block of sand is disturbed, the block of sand will fall from its cell to the sand counter at the bottom of the column (each column has a sand counter). While a block of sand is falling, other blocks of sand that are adjacent at any point to the falling block of sand will also be disturbed and start to fall. Specifically, a block of sand disturbed at a cell (i,j) will pass through all cells below and including the cell (i,j) within the column, disturbing all adjacent cells along the way. Here, the cells adjacent to a cell (i,j) are defined as (i-1,j), (i,j-1), (i+1,j), and (i,j+1) (if they are within the grid). Note that the newly falling blocks can disturb other blocks. In one operation you are able to disturb any piece of sand. The puzzle is solved when there are at least a_i blocks of sand counted in the i-th sand counter for each column from 1 to m. You are now tasked with finding the minimum amount of operations in order to solve the puzzle. Note that Little Dormi will never give you a puzzle that is impossible to solve. Input The first line consists of two space-separated positive integers n and m (1 ≀ n β‹… m ≀ 400 000). Each of the next n lines contains m characters, describing each row of the board. If a character on a line is '.', the corresponding cell is empty. If it is '#', the cell contains a block of sand. The final line contains m non-negative integers a_1,a_2,…,a_m (0 ≀ a_i ≀ n) β€” the minimum amount of blocks of sand that needs to fall below the board in each column. In this version of the problem, a_i will be equal to the number of blocks of sand in column i. Output Print one non-negative integer, the minimum amount of operations needed to solve the puzzle. Examples Input 5 7 #....#. .#.#... #....#. #....## #.#.... 4 1 1 1 0 3 1 Output 3 Input 3 3 #.# #.. ##. 3 1 1 Output 1 Note For example 1, by disturbing both blocks of sand on the first row from the top at the first and sixth columns from the left, and the block of sand on the second row from the top and the fourth column from the left, it is possible to have all the required amounts of sand fall in each column. It can be proved that this is not possible with fewer than 3 operations, and as such the answer is 3. Here is the puzzle from the first example. <image> For example 2, by disturbing the cell on the top row and rightmost column, one can cause all of the blocks of sand in the board to fall into the counters at the bottom. Thus, the answer is 1. Here is the puzzle from the second example. <image>
import sys input = sys.stdin.readline def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] n, m = map(int, input().split()) board = [] for _ in range(n): board.append(input()) l = list(map(int, input().split())) adj = [[] for _ in range(n * m)] last = [-1] * m for i in range(n-1,-1,-1): for j in range(m): if board[i][j] == '#': if last[j] != -1: adj[m * i + j].append(m*last[j] + j) if last[j] == i + 1: adj[m * (i+1) + j].append(m*i + j) last[j] = i if j != 0 and last[j-1] != -1: adj[m * i + j].append(m*last[j-1] + j-1) if last[j-1] == i: adj[m * i + j - 1].append(m * i + j) if j != m - 1 and last[j + 1] != -1: adj[m * i + j].append(m*last[j+1] + j+1) tar = find_SCC(adj) comp = [-1] * (m * n) curr = 0 for l in tar: for v in l: comp[v] = curr curr += 1 outB = [True] * curr for i in range(m * n): for v in adj[i]: if comp[i] != comp[v]: outB[comp[v]] = False for i in range(n): for j in range(m): if board[i][j] == '.': outB[comp[m * i + j]] = False out = 0 for b in outB: if b: out += 1 print(out)
{ "input": [ "5 7\n#....#.\n.#.#...\n#....#.\n#....##\n#.#....\n4 1 1 1 0 3 1\n", "3 3\n#.#\n#..\n##.\n3 1 1\n" ], "output": [ "\n3\n", "\n1\n" ] }
3,714
10
Let's consider one interesting word game. In this game you should transform one word into another through special operations. Let's say we have word w, let's split this word into two non-empty parts x and y so, that w = xy. A split operation is transforming word w = xy into word u = yx. For example, a split operation can transform word "wordcut" into word "cutword". You are given two words start and end. Count in how many ways we can transform word start into word end, if we apply exactly k split operations consecutively to word start. Two ways are considered different if the sequences of applied operations differ. Two operation sequences are different if exists such number i (1 ≀ i ≀ k), that in the i-th operation of the first sequence the word splits into parts x and y, in the i-th operation of the second sequence the word splits into parts a and b, and additionally x β‰  a holds. Input The first line contains a non-empty word start, the second line contains a non-empty word end. The words consist of lowercase Latin letters. The number of letters in word start equals the number of letters in word end and is at least 2 and doesn't exceed 1000 letters. The third line contains integer k (0 ≀ k ≀ 105) β€” the required number of operations. Output Print a single number β€” the answer to the problem. As this number can be rather large, print it modulo 1000000007 (109 + 7). Examples Input ab ab 2 Output 1 Input ababab ababab 1 Output 2 Input ab ba 2 Output 0 Note The sought way in the first sample is: ab β†’ a|b β†’ ba β†’ b|a β†’ ab In the second sample the two sought ways are: * ababab β†’ abab|ab β†’ ababab * ababab β†’ ab|abab β†’ ababab
def WordCut(): start = input() end = input() k = int(input()) n=len(start) dpA,dpB = (start==end),(start!=end) end+=end A=sum(start==end[i:i+n] for i in range(n)) B = n- A M = 10**9+7 for _ in range(k): dpA,dpB=(dpA*(A-1)+dpB*A)%M,(dpA*B+dpB*(B-1))%M return int(dpA) print(WordCut())
{ "input": [ "ababab\nababab\n1\n", "ab\nab\n2\n", "ab\nba\n2\n" ], "output": [ "2\n", "1\n", "0\n" ] }
3,715
7
The Little Elephant loves Ukraine very much. Most of all he loves town Rozdol (ukr. "Rozdil"). However, Rozdil is dangerous to settle, so the Little Elephant wants to go to some other town. The Little Elephant doesn't like to spend much time on travelling, so for his journey he will choose a town that needs minimum time to travel to. If there are multiple such cities, then the Little Elephant won't go anywhere. For each town except for Rozdil you know the time needed to travel to this town. Find the town the Little Elephant will go to or print "Still Rozdil", if he stays in Rozdil. Input The first line contains a single integer n (1 ≀ n ≀ 105) β€” the number of cities. The next line contains n integers, separated by single spaces: the i-th integer represents the time needed to go from town Rozdil to the i-th town. The time values are positive integers, not exceeding 109. You can consider the cities numbered from 1 to n, inclusive. Rozdil is not among the numbered cities. Output Print the answer on a single line β€” the number of the town the Little Elephant will go to. If there are multiple cities with minimum travel time, print "Still Rozdil" (without the quotes). Examples Input 2 7 4 Output 2 Input 7 7 4 47 100 4 9 12 Output Still Rozdil Note In the first sample there are only two cities where the Little Elephant can go. The travel time for the first town equals 7, to the second one β€” 4. The town which is closest to Rodzil (the only one) is the second one, so the answer is 2. In the second sample the closest cities are cities two and five, the travelling time to both of them equals 4, so the answer is "Still Rozdil".
def arr_inp(): return [int(x) for x in input().split()] n = int(input()) a = arr_inp() if (a.count(min(a))< 2): exit(print(a.index(min(a))+1)) print('Still Rozdil')
{ "input": [ "7\n7 4 47 100 4 9 12\n", "2\n7 4\n" ], "output": [ "Still Rozdil", "2" ] }
3,716
10
Convexity of a set of points on the plane is the size of the largest subset of points that form a convex polygon. Your task is to build a set of n points with the convexity of exactly m. Your set of points should not contain three points that lie on a straight line. Input The single line contains two integers n and m (3 ≀ m ≀ 100, m ≀ n ≀ 2m). Output If there is no solution, print "-1". Otherwise, print n pairs of integers β€” the coordinates of points of any set with the convexity of m. The coordinates shouldn't exceed 108 in their absolute value. Examples Input 4 3 Output 0 0 3 0 0 3 1 1 Input 6 3 Output -1 Input 6 6 Output 10 0 -10 0 10 1 9 1 9 -1 0 -2 Input 7 4 Output 176166 6377 709276 539564 654734 174109 910147 434207 790497 366519 606663 21061 859328 886001
def f(x): return int(x * x + 1e7) def g(x): return -f(x) n, m = map(int, input().split()) if(m == 3): if(n == 3): print('0 0') print('1 0') print('0 1') elif(n == 4): print('0 0') print('1 1') print('10000 0') print('0 10000') else: print(-1) else: for i in range(m): print(i, f(i)) for i in range(n - m): print(i, g(i))
{ "input": [ "6 6\n", "4 3\n", "6 3\n", "7 4\n" ], "output": [ "0 10000000\n1 10000001\n2 10000004\n3 10000009\n4 10000016\n5 10000025\n", "0 0\n3 0\n0 3\n1 1\n", "-1\n", "0 10000000\n1 10000001\n2 10000004\n3 10000009\n0 -10000000\n1 -10000001\n2 -10000004\n" ] }
3,717
9
Vitaly is a very weird man. He's got two favorite digits a and b. Vitaly calls a positive integer good, if the decimal representation of this integer only contains digits a and b. Vitaly calls a good number excellent, if the sum of its digits is a good number. For example, let's say that Vitaly's favourite digits are 1 and 3, then number 12 isn't good and numbers 13 or 311 are. Also, number 111 is excellent and number 11 isn't. Now Vitaly is wondering, how many excellent numbers of length exactly n are there. As this number can be rather large, he asks you to count the remainder after dividing it by 1000000007 (109 + 7). A number's length is the number of digits in its decimal representation without leading zeroes. Input The first line contains three integers: a, b, n (1 ≀ a < b ≀ 9, 1 ≀ n ≀ 106). Output Print a single integer β€” the answer to the problem modulo 1000000007 (109 + 7). Examples Input 1 3 3 Output 1 Input 2 3 10 Output 165
f=[0]*(10**6+1) f[0]=f[1]=1 mod=10**9+7 for i in range(2,10**6+1): f[i]=(f[i-1]*i)%mod def comb(n,r): return (f[n]*pow(f[n-r]*f[r],mod-2,mod))%mod a,b,n=map(int,input().split()) ans=0 def is_good(x,a,b): x=str(x) a=str(a) b=str(b) flag=True for xx in x: if xx!=a and xx!=b: flag=False return flag for k in range(n+1): s=a*k+b*(n-k) if is_good(s,a,b): ans+=comb(n,k) ans%=mod print(ans%mod)
{ "input": [ "1 3 3\n", "2 3 10\n" ], "output": [ "1\n", "165\n" ] }
3,718
7
Iahub got bored, so he invented a game to be played on paper. He writes n integers a1, a2, ..., an. Each of those integers can be either 0 or 1. He's allowed to do exactly one move: he chooses two indices i and j (1 ≀ i ≀ j ≀ n) and flips all values ak for which their positions are in range [i, j] (that is i ≀ k ≀ j). Flip the value of x means to apply operation x = 1 - x. The goal of the game is that after exactly one move to obtain the maximum number of ones. Write a program to solve the little game of Iahub. Input The first line of the input contains an integer n (1 ≀ n ≀ 100). In the second line of the input there are n integers: a1, a2, ..., an. It is guaranteed that each of those n values is either 0 or 1. Output Print an integer β€” the maximal number of 1s that can be obtained after exactly one move. Examples Input 5 1 0 0 1 0 Output 4 Input 4 1 0 0 1 Output 4 Note In the first case, flip the segment from 2 to 5 (i = 2, j = 5). That flip changes the sequence, it becomes: [1 1 1 0 1]. So, it contains four ones. There is no way to make the whole sequence equal to [1 1 1 1 1]. In the second case, flipping only the second and the third element (i = 2, j = 3) will turn all numbers into 1.
def invert(s): return str(1-int(s)) input() a=input().split() c=0 for i in range(len(a)): for j in range(len(a)-1,i-1,-1): m=(a[:i]+list(map(invert,a[i:j+1]))+a[j+1:]).count('1') if m>c: c=m print(c)
{ "input": [ "4\n1 0 0 1\n", "5\n1 0 0 1 0\n" ], "output": [ "4", "4" ] }
3,719
8
Igor has fallen in love with Tanya. Now Igor wants to show his feelings and write a number on the fence opposite to Tanya's house. Igor thinks that the larger the number is, the more chance to win Tanya's heart he has. Unfortunately, Igor could only get v liters of paint. He did the math and concluded that digit d requires ad liters of paint. Besides, Igor heard that Tanya doesn't like zeroes. That's why Igor won't use them in his number. Help Igor find the maximum number he can write on the fence. Input The first line contains a positive integer v (0 ≀ v ≀ 106). The second line contains nine positive integers a1, a2, ..., a9 (1 ≀ ai ≀ 105). Output Print the maximum number Igor can write on the fence. If he has too little paint for any digit (so, he cannot write anything), print -1. Examples Input 5 5 4 3 2 1 2 3 4 5 Output 55555 Input 2 9 11 1 12 5 8 9 10 6 Output 33 Input 0 1 1 1 1 1 1 1 1 1 Output -1
def f(t, k, d): j = k - 1 for i in range(k, 9): if d >= t[i]: j = i return d - t[j], j + 1 n = int(input()) t = list(map(int, input().split())) m, k = t[0], 1 for i, x in enumerate(t, 1): if x <= m: m, k = x, i if n < m: print(-1) else: d, j, s = n % m, k + 1, [] while j != k: d, j = f(t, k, d + m) s.append(j) print(''.join(map(str, s)) + str(k) * (n // m - len(s)))
{ "input": [ "0\n1 1 1 1 1 1 1 1 1\n", "2\n9 11 1 12 5 8 9 10 6\n", "5\n5 4 3 2 1 2 3 4 5\n" ], "output": [ "-1\n", "33\n", "55555\n" ] }
3,720
9
A festival will be held in a town's main street. There are n sections in the main street. The sections are numbered 1 through n from left to right. The distance between each adjacent sections is 1. In the festival m fireworks will be launched. The i-th (1 ≀ i ≀ m) launching is on time ti at section ai. If you are at section x (1 ≀ x ≀ n) at the time of i-th launching, you'll gain happiness value bi - |ai - x| (note that the happiness value might be a negative value). You can move up to d length units in a unit time interval, but it's prohibited to go out of the main street. Also you can be in an arbitrary section at initial time moment (time equals to 1), and want to maximize the sum of happiness that can be gained from watching fireworks. Find the maximum total happiness. Note that two or more fireworks can be launched at the same time. Input The first line contains three integers n, m, d (1 ≀ n ≀ 150000; 1 ≀ m ≀ 300; 1 ≀ d ≀ n). Each of the next m lines contains integers ai, bi, ti (1 ≀ ai ≀ n; 1 ≀ bi ≀ 109; 1 ≀ ti ≀ 109). The i-th line contains description of the i-th launching. It is guaranteed that the condition ti ≀ ti + 1 (1 ≀ i < m) will be satisfied. Output Print a single integer β€” the maximum sum of happiness that you can gain from watching all the fireworks. Please, do not write the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 50 3 1 49 1 1 26 1 4 6 1 10 Output -31 Input 10 2 1 1 1000 4 9 1000 4 Output 1992
from collections import deque def rollingmax(x, y, r, a): k = 2 * r + 1 d = deque() lx = len(x) for i in range(lx + r): if i < lx: while d and d[-1][1] <= x[i]: d.pop() d.append((i, x[i])) while d and d[0][0] <= i - k: d.popleft() if i >= r: y[i - r] = d[0][1] - abs(i - r - a) n, m, d = [int(x) for x in input().split()] a, ball, t0 = [int(x) for x in input().split()] f = [-abs(i - a) for i in range(1, n + 1)] g = [0] * n for _ in range(m - 1): a, b, t = [int(x) for x in input().split()] ball += b r = min(n - 1, (t - t0) * d) t0 = t rollingmax(f, g, r, a - 1) f, g = g, f print(max(f) + ball)
{ "input": [ "50 3 1\n49 1 1\n26 1 4\n6 1 10\n", "10 2 1\n1 1000 4\n9 1000 4\n" ], "output": [ " -31\n", " 1992\n" ] }
3,721
7
The finalists of the "Russian Code Cup" competition in 2214 will be the participants who win in one of the elimination rounds. The elimination rounds are divided into main and additional. Each of the main elimination rounds consists of c problems, the winners of the round are the first n people in the rating list. Each of the additional elimination rounds consists of d problems. The winner of the additional round is one person. Besides, k winners of the past finals are invited to the finals without elimination. As a result of all elimination rounds at least nΒ·m people should go to the finals. You need to organize elimination rounds in such a way, that at least nΒ·m people go to the finals, and the total amount of used problems in all rounds is as small as possible. Input The first line contains two integers c and d (1 ≀ c, d ≀ 100) β€” the number of problems in the main and additional rounds, correspondingly. The second line contains two integers n and m (1 ≀ n, m ≀ 100). Finally, the third line contains an integer k (1 ≀ k ≀ 100) β€” the number of the pre-chosen winners. Output In the first line, print a single integer β€” the minimum number of problems the jury needs to prepare. Examples Input 1 10 7 2 1 Output 2 Input 2 2 2 1 2 Output 0
def f(x, y): return x * c + y * d c, d = map(int, input().split()) n, m = map(int, input().split()) k = n * m - int(input()) x, s = 0, max(0, k * d) while k > x * n: t = f(x, k - x * n) if t < s: s = t x += 1 print(min(s, f(x, 0)))
{ "input": [ "2 2\n2 1\n2\n", "1 10\n7 2\n1\n" ], "output": [ "0\n", "2\n" ] }
3,722
10
Andrey needs one more problem to conduct a programming contest. He has n friends who are always willing to help. He can ask some of them to come up with a contest problem. Andrey knows one value for each of his fiends β€” the probability that this friend will come up with a problem if Andrey asks him. Help Andrey choose people to ask. As he needs only one problem, Andrey is going to be really upset if no one comes up with a problem or if he gets more than one problem from his friends. You need to choose such a set of people that maximizes the chances of Andrey not getting upset. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of Andrey's friends. The second line contains n real numbers pi (0.0 ≀ pi ≀ 1.0) β€” the probability that the i-th friend can come up with a problem. The probabilities are given with at most 6 digits after decimal point. Output Print a single real number β€” the probability that Andrey won't get upset at the optimal choice of friends. The answer will be considered valid if it differs from the correct one by at most 10 - 9. Examples Input 4 0.1 0.2 0.3 0.8 Output 0.800000000000 Input 2 0.1 0.2 Output 0.260000000000 Note In the first sample the best strategy for Andrey is to ask only one of his friends, the most reliable one. In the second sample the best strategy for Andrey is to ask all of his friends to come up with a problem. Then the probability that he will get exactly one problem is 0.1Β·0.8 + 0.9Β·0.2 = 0.26.
input() p = sorted(map(float, input().split(' '))) m = max(p) p = [(1 - i, i) for i in p] def konv(a, b): return a[0] * b[0], a[0] * b[1] + a[1] * b[0] while len(p) > 1: p.append(konv(p.pop(), p.pop())) m = max(m, p[-1][1]) print(m)
{ "input": [ "4\n0.1 0.2 0.3 0.8\n", "2\n0.1 0.2\n" ], "output": [ "0.8000000000\n", "0.2600000000\n" ] }
3,723
10
Tomash keeps wandering off and getting lost while he is walking along the streets of Berland. It's no surprise! In his home town, for any pair of intersections there is exactly one way to walk from one intersection to the other one. The capital of Berland is very different! Tomash has noticed that even simple cases of ambiguity confuse him. So, when he sees a group of four distinct intersections a, b, c and d, such that there are two paths from a to c β€” one through b and the other one through d, he calls the group a "damn rhombus". Note that pairs (a, b), (b, c), (a, d), (d, c) should be directly connected by the roads. Schematically, a damn rhombus is shown on the figure below: <image> Other roads between any of the intersections don't make the rhombus any more appealing to Tomash, so the four intersections remain a "damn rhombus" for him. Given that the capital of Berland has n intersections and m roads and all roads are unidirectional and are known in advance, find the number of "damn rhombi" in the city. When rhombi are compared, the order of intersections b and d doesn't matter. Input The first line of the input contains a pair of integers n, m (1 ≀ n ≀ 3000, 0 ≀ m ≀ 30000) β€” the number of intersections and roads, respectively. Next m lines list the roads, one per line. Each of the roads is given by a pair of integers ai, bi (1 ≀ ai, bi ≀ n;ai β‰  bi) β€” the number of the intersection it goes out from and the number of the intersection it leads to. Between a pair of intersections there is at most one road in each of the two directions. It is not guaranteed that you can get from any intersection to any other one. Output Print the required number of "damn rhombi". Examples Input 5 4 1 2 2 3 1 4 4 3 Output 1 Input 4 12 1 2 1 3 1 4 2 1 2 3 2 4 3 1 3 2 3 4 4 1 4 2 4 3 Output 12
import sys from functools import lru_cache, cmp_to_key from heapq import merge, heapify, heappop, heappush from math import * from collections import defaultdict as dd, deque, Counter as C from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect from time import perf_counter from fractions import Fraction import copy import time starttime = time.time() mod = int(pow(10, 9) + 7) mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(*var, end="\n"): sys.stdout.write(' '.join(map(str, var))+end) def L(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)] try: # sys.setrecursionlimit(int(pow(10,4))) sys.stdin = open("input.txt", "r") # sys.stdout = open("../output.txt", "w") except: pass def pmat(A): for ele in A: print(*ele,end="\n") # def seive(): # prime=[1 for i in range(10**6+1)] # prime[0]=0 # prime[1]=0 # for i in range(10**6+1): # if(prime[i]): # for j in range(2*i,10**6+1,i): # prime[j]=0 # return prime for _ in range(1): n,m=L() g=[[] for i in range(n+1)] for i in range(m): x,y=L() g[x].append(y) ans=0 for i in range(1,n+1): d={} for imm in g[i]: for ele in g[imm]: if ele!=i and ele!=imm: d[ele]=d.get(ele,0)+1 for ele in d: if d[ele]>=2: ans+=d[ele]*(d[ele]-1)//2 print(ans) endtime = time.time() # print(f"Runtime of the program is {endtime - starttime}")
{ "input": [ "4 12\n1 2\n1 3\n1 4\n2 1\n2 3\n2 4\n3 1\n3 2\n3 4\n4 1\n4 2\n4 3\n", "5 4\n1 2\n2 3\n1 4\n4 3\n" ], "output": [ "12\n", "1\n" ] }
3,724
8
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum: <image> Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p). Input The single line of input contains two integers n and m (1 ≀ m ≀ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p). The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows. * In subproblem B1 (3 points), the constraint 1 ≀ n ≀ 8 will hold. * In subproblem B2 (4 points), the constraint 1 ≀ n ≀ 50 will hold. Output Output n number forming the required permutation. Examples Input 2 2 Output 2 1 Input 3 2 Output 1 3 2 Note In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
arc = [] def sv(a,b,c,n,v): if n < c//2: arc[a] = v if b-a>1: sv(a+1,b,c//2,n,v+1) else: arc[b-1] = v if b-a>1: sv(a,b-1,c//2,n-c//2,v+1) n, m = map(int, input().split()) arc = [0]*n ssc = 1<<(n-1) sv(0, n, ssc, m-1, 1) print(' '.join(map(str, arc)))
{ "input": [ "2 2\n", "3 2\n" ], "output": [ "2 1 \n", "1 3 2 \n" ] }
3,725
10
Igor has been into chess for a long time and now he is sick of the game by the ordinary rules. He is going to think of new rules of the game and become world famous. Igor's chessboard is a square of size n Γ— n cells. Igor decided that simple rules guarantee success, that's why his game will have only one type of pieces. Besides, all pieces in his game are of the same color. The possible moves of a piece are described by a set of shift vectors. The next passage contains a formal description of available moves. Let the rows of the board be numbered from top to bottom and the columns be numbered from left to right from 1 to n. Let's assign to each square a pair of integers (x, y) β€” the number of the corresponding column and row. Each of the possible moves of the piece is defined by a pair of integers (dx, dy); using this move, the piece moves from the field (x, y) to the field (x + dx, y + dy). You can perform the move if the cell (x + dx, y + dy) is within the boundaries of the board and doesn't contain another piece. Pieces that stand on the cells other than (x, y) and (x + dx, y + dy) are not important when considering the possibility of making the given move (for example, like when a knight moves in usual chess). Igor offers you to find out what moves his chess piece can make. He placed several pieces on the board and for each unoccupied square he told you whether it is attacked by any present piece (i.e. whether some of the pieces on the field can move to that cell). Restore a possible set of shift vectors of the piece, or else determine that Igor has made a mistake and such situation is impossible for any set of shift vectors. Input The first line contains a single integer n (1 ≀ n ≀ 50). The next n lines contain n characters each describing the position offered by Igor. The j-th character of the i-th string can have the following values: * o β€” in this case the field (i, j) is occupied by a piece and the field may or may not be attacked by some other piece; * x β€” in this case field (i, j) is attacked by some piece; * . β€” in this case field (i, j) isn't attacked by any piece. It is guaranteed that there is at least one piece on the board. Output If there is a valid set of moves, in the first line print a single word 'YES' (without the quotes). Next, print the description of the set of moves of a piece in the form of a (2n - 1) Γ— (2n - 1) board, the center of the board has a piece and symbols 'x' mark cells that are attacked by it, in a format similar to the input. See examples of the output for a full understanding of the format. If there are several possible answers, print any of them. If a valid set of moves does not exist, print a single word 'NO'. Examples Input 5 oxxxx x...x x...x x...x xxxxo Output YES ....x.... ....x.... ....x.... ....x.... xxxxoxxxx ....x.... ....x.... ....x.... ....x.... Input 6 .x.x.. x.x.x. .xo..x x..ox. .x.x.x ..x.x. Output YES ........... ........... ........... ....x.x.... ...x...x... .....o..... ...x...x... ....x.x.... ........... ........... ........... Input 3 o.x oxx o.x Output NO Note In the first sample test the piece is a usual chess rook, and in the second sample test the piece is a usual chess knight.
n = int(input()) b = [input() for i in range(n)] h = [[False] * n for i in range(n)] p = [[i, j] for i in range(n) for j in range(n) if b[i][j] == 'o'] v = [['.'] * (2 * n - 1) for i in range(2 * n - 1)] def on(x, y): return x in range(n) and y in range(n) def proc(dx, dy): for pi in p: if on(pi[0] + dx, pi[1] + dy) and b[pi[0] + dx][pi[1] + dy] == '.': return v[dx + n - 1][dy + n - 1] = 'x' for pi in p: if on(pi[0] + dx, pi[1] + dy): h[pi[0] + dx][pi[1] + dy] = True for i in range(-(n - 1), n): for j in range(-(n - 1), n): proc(i, j) if any(b[i][j] == 'x' and not h[i][j] for i in range(n) for j in range(n)): print('NO') else: print('YES') v[n - 1][n - 1] = 'o' for vi in v: print(''.join(vi))
{ "input": [ "5\noxxxx\nx...x\nx...x\nx...x\nxxxxo\n", "3\no.x\noxx\no.x\n", "6\n.x.x..\nx.x.x.\n.xo..x\nx..ox.\n.x.x.x\n..x.x.\n" ], "output": [ "YES\nxxxxxxxxx\nx...xxxxx\nx...xxxxx\nx...xxxxx\nxxxxoxxxx\nxxxxx...x\nxxxxx...x\nxxxxx...x\nxxxxxxxxx\n", "NO\n", "YES\nxxxxxxxxxxx\nxxxxxxxxxxx\nxx.x.x..xxx\nxxx.x.x..xx\nxx.x...x.xx\nxxx..o..xxx\nxx.x...x.xx\nxx..x.x.xxx\nxxx..x.x.xx\nxxxxxxxxxxx\nxxxxxxxxxxx\n" ] }
3,726
8
The Cereal Guy's friend Serial Guy likes to watch soap operas. An episode is about to start, and he hasn't washed his plate yet. But he decided to at least put in under the tap to be filled with water. The plate can be represented by a parallelepiped k Γ— n Γ— m, that is, it has k layers (the first layer is the upper one), each of which is a rectangle n Γ— m with empty squares ('.') and obstacles ('#'). The water can only be present in the empty squares. The tap is positioned above the square (x, y) of the first layer, it is guaranteed that this square is empty. Every minute a cubical unit of water falls into the plate. Find out in how many minutes the Serial Guy should unglue himself from the soap opera and turn the water off for it not to overfill the plate. That is, you should find the moment of time when the plate is absolutely full and is going to be overfilled in the next moment. Note: the water fills all the area within reach (see sample 4). Water flows in each of the 6 directions, through faces of 1 Γ— 1 Γ— 1 cubes. Input The first line contains three numbers k, n, m (1 ≀ k, n, m ≀ 10) which are the sizes of the plate. Then follow k rectangles consisting of n lines each containing m characters '.' or '#', which represents the "layers" of the plate in the order from the top to the bottom. The rectangles are separated by empty lines (see the samples). The last line contains x and y (1 ≀ x ≀ n, 1 ≀ y ≀ m) which are the tap's coordinates. x is the number of the line and y is the number of the column. Lines of each layer are numbered from left to right by the integers from 1 to n, columns of each layer are numbered from top to bottom by the integers from 1 to m. Output The answer should contain a single number, showing in how many minutes the plate will be filled. Examples Input 1 1 1 . 1 1 Output 1 Input 2 1 1 . # 1 1 Output 1 Input 2 2 2 .# ## .. .. 1 1 Output 5 Input 3 2 2 #. ## #. .# .. .. 1 2 Output 7 Input 3 3 3 .#. ### ##. .## ### ##. ... ... ... 1 1 Output 13
a=[] b=list(map(int,input().split())) input() for i in range(b[0]): a.append([]) for j in range(b[1]): a[i].append([]) for z in input(): a[i][j].append(z) input() x,y=map(int,input().split()); x-=1; y-=1 ans=[0] def wv(k,x,y): if (k<0)or(k==b[0])or(x<0)or(x==b[1])or(y<0)or(y==b[2])or(a[k][x][y]=='#'): return ans[0]+=1 a[k][x][y]='#' wv(k-1,x,y) wv(k+1,x,y) wv(k,x-1,y) wv(k,x+1,y) wv(k,x,y-1) wv(k,x,y+1) wv(0,x,y) print(ans[0])
{ "input": [ "3 2 2\n\n#.\n##\n\n#.\n.#\n\n..\n..\n\n1 2\n", "2 2 2\n\n.#\n##\n\n..\n..\n\n1 1\n", "2 1 1\n\n.\n\n#\n\n1 1\n", "3 3 3\n\n.#.\n###\n##.\n\n.##\n###\n##.\n\n...\n...\n...\n\n1 1\n", "1 1 1\n\n.\n\n1 1\n" ], "output": [ "7", "5", "1", "13", "1" ] }
3,727
10
Limak is a little polar bear. He doesn't have many toys and thus he often plays with polynomials. He considers a polynomial valid if its degree is n and its coefficients are integers not exceeding k by the absolute value. More formally: Let a0, a1, ..., an denote the coefficients, so <image>. Then, a polynomial P(x) is valid if all the following conditions are satisfied: * ai is integer for every i; * |ai| ≀ k for every i; * an β‰  0. Limak has recently got a valid polynomial P with coefficients a0, a1, a2, ..., an. He noticed that P(2) β‰  0 and he wants to change it. He is going to change one coefficient to get a valid polynomial Q of degree n that Q(2) = 0. Count the number of ways to do so. You should count two ways as a distinct if coefficients of target polynoms differ. Input The first line contains two integers n and k (1 ≀ n ≀ 200 000, 1 ≀ k ≀ 109) β€” the degree of the polynomial and the limit for absolute values of coefficients. The second line contains n + 1 integers a0, a1, ..., an (|ai| ≀ k, an β‰  0) β€” describing a valid polynomial <image>. It's guaranteed that P(2) β‰  0. Output Print the number of ways to change one coefficient to get a valid polynomial Q that Q(2) = 0. Examples Input 3 1000000000 10 -9 -3 5 Output 3 Input 3 12 10 -9 -3 5 Output 2 Input 2 20 14 -7 19 Output 0 Note In the first sample, we are given a polynomial P(x) = 10 - 9x - 3x2 + 5x3. Limak can change one coefficient in three ways: 1. He can set a0 = - 10. Then he would get Q(x) = - 10 - 9x - 3x2 + 5x3 and indeed Q(2) = - 10 - 18 - 12 + 40 = 0. 2. Or he can set a2 = - 8. Then Q(x) = 10 - 9x - 8x2 + 5x3 and indeed Q(2) = 10 - 18 - 32 + 40 = 0. 3. Or he can set a1 = - 19. Then Q(x) = 10 - 19x - 3x2 + 5x3 and indeed Q(2) = 10 - 38 - 12 + 40 = 0. In the second sample, we are given the same polynomial. This time though, k is equal to 12 instead of 109. Two first of ways listed above are still valid but in the third way we would get |a1| > k what is not allowed. Thus, the answer is 2 this time.
def convert_to_binary(coef): res = [] n = len(coef) carry = 0 i = 0 while i < n + 1000: if i >= n and not carry: break cur = carry if i < n: cur += coef[i] mod = cur % 2 div = cur // 2 # print(cur, div, mod) res.append(mod) carry = div i += 1 return res, carry n, k = map(int, input().split()) coef = list(map(int, input().split())) b, carry = convert_to_binary(coef) ref = False if carry < 0: b, carry = convert_to_binary(list(map(lambda x: -x, coef))) ref = True last = len(b) - 1 while b[last] != 1: last -= 1 ans = 0 for i in range(0, n + 1): if last - i > 40: continue cur = 0 for j in range(i, last + 1): cur += b[j] * (2 ** (j - i)) new_coef = coef[i] - cur if ref: new_coef = coef[i] + cur if abs(new_coef) > k: if b[i] == 1: break continue if i == n and new_coef == 0: if b[i] == 1: break continue ans += 1 if b[i] == 1: break print(ans)
{ "input": [ "3 12\n10 -9 -3 5\n", "2 20\n14 -7 19\n", "3 1000000000\n10 -9 -3 5\n" ], "output": [ "2", "0", "3" ] }
3,728
7
Codeforces user' handle color depends on his rating β€” it is red if his rating is greater or equal to 2400; it is orange if his rating is less than 2400 but greater or equal to 2200, etc. Each time participant takes part in a rated contest, his rating is changed depending on his performance. Anton wants the color of his handle to become red. He considers his performance in the rated contest to be good if he outscored some participant, whose handle was colored red before the contest and his rating has increased after it. Anton has written a program that analyses contest results and determines whether he performed good or not. Are you able to do the same? Input The first line of the input contains a single integer n (1 ≀ n ≀ 100) β€” the number of participants Anton has outscored in this contest . The next n lines describe participants results: the i-th of them consists of a participant handle namei and two integers beforei and afteri ( - 4000 ≀ beforei, afteri ≀ 4000) β€” participant's rating before and after the contest, respectively. Each handle is a non-empty string, consisting of no more than 10 characters, which might be lowercase and uppercase English letters, digits, characters Β«_Β» and Β«-Β» characters. It is guaranteed that all handles are distinct. Output Print Β«YESΒ» (quotes for clarity), if Anton has performed good in the contest and Β«NOΒ» (quotes for clarity) otherwise. Examples Input 3 Burunduk1 2526 2537 BudAlNik 2084 2214 subscriber 2833 2749 Output YES Input 3 Applejack 2400 2400 Fluttershy 2390 2431 Pinkie_Pie -2500 -2450 Output NO Note In the first sample, Anton has outscored user with handle Burunduk1, whose handle was colored red before the contest and his rating has increased after the contest. In the second sample, Applejack's rating has not increased after the contest, while both Fluttershy's and Pinkie_Pie's handles were not colored red before the contest.
n=int(input()) def f(n): for i in range(n): s,bf,af=input().split() bf,af=int(bf),int(af) if bf>=2400 and af-bf>0: return "YES" return "NO" print(f(n))
{ "input": [ "3\nApplejack 2400 2400\nFluttershy 2390 2431\nPinkie_Pie -2500 -2450\n", "3\nBurunduk1 2526 2537\nBudAlNik 2084 2214\nsubscriber 2833 2749\n" ], "output": [ "NO", "YES" ] }
3,729
11
A rare article in the Internet is posted without a possibility to comment it. On a Polycarp's website each article has comments feed. Each comment on Polycarp's website is a non-empty string consisting of uppercase and lowercase letters of English alphabet. Comments have tree-like structure, that means each comment except root comments (comments of the highest level) has exactly one parent comment. When Polycarp wants to save comments to his hard drive he uses the following format. Each comment he writes in the following format: * at first, the text of the comment is written; * after that the number of comments is written, for which this comment is a parent comment (i. e. the number of the replies to this comments); * after that the comments for which this comment is a parent comment are written (the writing of these comments uses the same algorithm). All elements in this format are separated by single comma. Similarly, the comments of the first level are separated by comma. For example, if the comments look like: <image> then the first comment is written as "hello,2,ok,0,bye,0", the second is written as "test,0", the third comment is written as "one,1,two,2,a,0,b,0". The whole comments feed is written as: "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0". For a given comments feed in the format specified above print the comments in a different format: * at first, print a integer d β€” the maximum depth of nesting comments; * after that print d lines, the i-th of them corresponds to nesting level i; * for the i-th row print comments of nesting level i in the order of their appearance in the Policarp's comments feed, separated by space. Input The first line contains non-empty comments feed in the described format. It consists of uppercase and lowercase letters of English alphabet, digits and commas. It is guaranteed that each comment is a non-empty string consisting of uppercase and lowercase English characters. Each of the number of comments is integer (consisting of at least one digit), and either equals 0 or does not contain leading zeros. The length of the whole string does not exceed 106. It is guaranteed that given structure of comments is valid. Output Print comments in a format that is given in the statement. For each level of nesting, comments should be printed in the order they are given in the input. Examples Input hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0 Output 3 hello test one ok bye two a b Input a,5,A,0,a,0,A,0,a,0,A,0 Output 2 a A a A a A Input A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0 Output 4 A K M B F H L N O C D G I P E J Note The first example is explained in the statements.
#!/usr/bin/env python3 from collections import defaultdict def ri(): return map(int, input().split()) temp = input().split(',') node = temp[0::2] count = temp[1::2] count = list(map(int, count)) level = defaultdict(list) stack = [] l = 0 for j in range(len(node)): level[l].append(j) if count[j]: count[j] -= 1 stack.append(j) l += 1 else: while len(stack): if count[stack[-1]] == 0: stack.pop() l -= 1 else: count[stack[-1]] -= 1 break print(len(level)) for l in level: print(' '.join([node[i] for i in level[l]]))
{ "input": [ "A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0\n", "a,5,A,0,a,0,A,0,a,0,A,0\n", "hello,2,ok,0,bye,0,test,0,one,1,two,2,a,0,b,0\n" ], "output": [ "4\nA K M \nB F H L N O \nC D G I P \nE J \n", "2\na \nA a A a A \n", "3\nhello test one \nok bye two \na b \n" ] }
3,730
8
Anton has the integer x. He is interested what positive integer, which doesn't exceed x, has the maximum sum of digits. Your task is to help Anton and to find the integer that interests him. If there are several such integers, determine the biggest of them. Input The first line contains the positive integer x (1 ≀ x ≀ 1018) β€” the integer which Anton has. Output Print the positive integer which doesn't exceed x and has the maximum sum of digits. If there are several such integers, print the biggest of them. Printed integer must not contain leading zeros. Examples Input 100 Output 99 Input 48 Output 48 Input 521 Output 499
def rec(num): mod = 10 if num < mod: return 0 dom = mod while mod * dom < num: dom *= mod num %= dom if (mod * num // dom + 1) % mod: return num return rec(num) num = int(input()) print(num - rec(num + 1))
{ "input": [ "521\n", "100\n", "48\n" ], "output": [ "499\n", "99\n", "48\n" ] }
3,731
11
Oleg the bank client and Igor the analyst are arguing again. This time, they want to pick a gift as a present for their friend, ZS the coder. After a long thought, they decided that their friend loves to eat carrots the most and thus they want to pick the best carrot as their present. There are n carrots arranged in a line. The i-th carrot from the left has juiciness ai. Oleg thinks ZS loves juicy carrots whereas Igor thinks that he hates juicy carrots. Thus, Oleg would like to maximize the juiciness of the carrot they choose while Igor would like to minimize the juiciness of the carrot they choose. To settle this issue, they decided to play a game again. Oleg and Igor take turns to play the game. In each turn, a player can choose a carrot from either end of the line, and eat it. The game ends when only one carrot remains. Oleg moves first. The last remaining carrot will be the carrot that they will give their friend, ZS. Oleg is a sneaky bank client. When Igor goes to a restroom, he performs k moves before the start of the game. Each move is the same as above (eat a carrot from either end of the line). After Igor returns, they start the game with Oleg still going first. Oleg wonders: for each k such that 0 ≀ k ≀ n - 1, what is the juiciness of the carrot they will give to ZS if he makes k extra moves beforehand and both players play optimally? Input The first line of input contains a single integer n (1 ≀ n ≀ 3Β·105) β€” the total number of carrots. The next line contains n space-separated integers a1, a2, ..., an (1 ≀ ai ≀ 109). Here ai denotes the juiciness of the i-th carrot from the left of the line. Output Output n space-separated integers x0, x1, ..., xn - 1. Here, xi denotes the juiciness of the carrot the friends will present to ZS if k = i. Examples Input 4 1 2 3 5 Output 3 3 5 5 Input 5 1000000000 1000000000 1000000000 1000000000 1 Output 1000000000 1000000000 1000000000 1000000000 1000000000 Note For the first example, When k = 0, one possible optimal game is as follows: * Oleg eats the carrot with juiciness 1. * Igor eats the carrot with juiciness 5. * Oleg eats the carrot with juiciness 2. * The remaining carrot has juiciness 3. When k = 1, one possible optimal play is as follows: * Oleg eats the carrot with juiciness 1 beforehand. * Oleg eats the carrot with juiciness 2. * Igor eats the carrot with juiciness 5. * The remaining carrot has juiciness 3. When k = 2, one possible optimal play is as follows: * Oleg eats the carrot with juiciness 1 beforehand. * Oleg eats the carrot with juiciness 2 beforehand. * Oleg eats the carrot with juiciness 3. * The remaining carrot has juiciness 5. When k = 3, one possible optimal play is as follows: * Oleg eats the carrot with juiciness 1 beforehand. * Oleg eats the carrot with juiciness 2 beforehand. * Oleg eats the carrot with juiciness 3 beforehand. * The remaining carrot has juiciness 5. Thus, the answer is 3, 3, 5, 5. For the second sample, Oleg can always eat the carrot with juiciness 1 since he always moves first. So, the remaining carrot will always have juiciness 1000000000.
def evens(A): n = len(A) l = n//2-1; r = n//2 if len(A)%2 == 1: l+= 1 ans = [max(A[l], A[r])] while r < n-1: l-= 1; r+= 1 ans.append(max(ans[-1], A[l], A[r])) return ans def interleave(A, B): q = [] for i in range(len(B)): q+= [A[i], B[i]] if len(A) != len(B): q.append(A[-1]) return q n = int(input()) A = list(map(int,input().split())) M = [min(A[i],A[i+1]) for i in range(n-1)] ansA = evens(A) ansM = evens(M) if n>1 else [] if n%2 == 0: print(*interleave(ansA, ansM[1:]), max(A)) else: print(*interleave(ansM, ansA[1:]), max(A))
{ "input": [ "5\n1000000000 1000000000 1000000000 1000000000 1\n", "4\n1 2 3 5\n" ], "output": [ "1000000000 1000000000 1000000000 1000000000 1000000000 \n", "3 3 5 5 \n" ] }
3,732
10
There are two main kinds of events in the life of top-model: fashion shows and photo shoots. Participating in any of these events affects the rating of appropriate top-model. After each photo shoot model's rating increases by a and after each fashion show decreases by b (designers do too many experiments nowadays). Moreover, sometimes top-models participates in talk shows. After participating in talk show model becomes more popular and increasing of her rating after photo shoots become c and decreasing of her rating after fashion show becomes d. Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will never become negative. Help her to find a suitable moment for participating in the talk show. Let's assume that model's career begins in moment 0. At that moment Izabella's rating was equal to start. If talk show happens in moment t if will affect all events in model's life in interval of time [t..t + len) (including t and not including t + len), where len is duration of influence. Izabella wants to participate in a talk show, but she wants to do it in such a way that her rating will not become become negative before talk show or during period of influence of talk show. Help her to find a suitable moment for participating in the talk show. Input In first line there are 7 positive integers n, a, b, c, d, start, len (1 ≀ n ≀ 3Β·105, 0 ≀ start ≀ 109, 1 ≀ a, b, c, d, len ≀ 109), where n is a number of fashion shows and photo shoots, a, b, c and d are rating changes described above, start is an initial rating of model and len is a duration of influence of talk show. In next n lines descriptions of events are given. Each of those lines contains two integers ti and qi (1 ≀ ti ≀ 109, 0 ≀ q ≀ 1) β€” moment, in which event happens and type of this event. Type 0 corresponds to the fashion show and type 1 β€” to photo shoot. Events are given in order of increasing ti, all ti are different. Output Print one non-negative integer t β€” the moment of time in which talk show should happen to make Izabella's rating non-negative before talk show and during period of influence of talk show. If there are multiple answers print smallest of them. If there are no such moments, print - 1. Examples Input 5 1 1 1 4 0 5 1 1 2 1 3 1 4 0 5 0 Output 6 Input 1 1 2 1 2 1 2 1 0 Output -1
from sys import stdin from collections import deque def main(): n, a, b, c, d, st, l = map(int, input().split()) q = deque() po = q.popleft pu = q.append mq = deque() mpop = mq.pop mpo = mq.popleft mpu = mq.append sb = [0] * (n + 1) mst = st pu((0, 0, mst, st)) pp = 0 for i, line in enumerate(stdin): line = line.split() t = int(line[0], 10) while q and q[0][0] + l <= t: p, j, ma, sa = po() if ma < 0: print (-1) return while mq and mq[0][1] < p: mpo() sa += (-sb[j] + mq[0][0]) if mq else 0 if ma > sa: ma = sa if ma >= 0: print (min(pp, p)) return pp = p + 1 pu((t, i, mst, st)) if line[1] == '1': st += a x = sb[i] + c else: st -= b x = sb[i] - d if mst > st: mst = st while mq and mq[-1][0] > x: mpop() mpu((x, t)) sb[i+1] = x pu((t + 1, n, mst, st)) while q: p, j, ma, sa = po() if ma < 0: print (-1) return while mq and mq[0][1] < p: mpo() sa += (-sb[j] + mq[0][0]) if mq else 0 if ma > sa: ma = sa if ma >= 0: print (min(pp, p)) return pp = p + 1 print (-1) main()
{ "input": [ "5 1 1 1 4 0 5\n1 1\n2 1\n3 1\n4 0\n5 0\n", "1 1 2 1 2 1 2\n1 0\n" ], "output": [ "6\n", "-1\n" ] }
3,733
10
Vasya writes his own library for building graphical user interface. Vasya called his creation VTK (VasyaToolKit). One of the interesting aspects of this library is that widgets are packed in each other. A widget is some element of graphical interface. Each widget has width and height, and occupies some rectangle on the screen. Any widget in Vasya's library is of type Widget. For simplicity we will identify the widget and its type. Types HBox and VBox are derivatives of type Widget, so they also are types Widget. Widgets HBox and VBox are special. They can store other widgets. Both those widgets can use the pack() method to pack directly in itself some other widget. Widgets of types HBox and VBox can store several other widgets, even several equal widgets β€” they will simply appear several times. As a result of using the method pack() only the link to the packed widget is saved, that is when the packed widget is changed, its image in the widget, into which it is packed, will also change. We shall assume that the widget a is packed in the widget b if there exists a chain of widgets a = c1, c2, ..., ck = b, k β‰₯ 2, for which ci is packed directly to ci + 1 for any 1 ≀ i < k. In Vasya's library the situation when the widget a is packed in the widget a (that is, in itself) is not allowed. If you try to pack the widgets into each other in this manner immediately results in an error. Also, the widgets HBox and VBox have parameters border and spacing, which are determined by the methods set_border() and set_spacing() respectively. By default both of these options equal 0. <image> The picture above shows how the widgets are packed into HBox and VBox. At that HBox and VBox automatically change their size depending on the size of packed widgets. As for HBox and VBox, they only differ in that in HBox the widgets are packed horizontally and in VBox β€” vertically. The parameter spacing sets the distance between adjacent widgets, and border β€” a frame around all packed widgets of the desired width. Packed widgets are placed exactly in the order in which the pack() method was called for them. If within HBox or VBox there are no packed widgets, their sizes are equal to 0 Γ— 0, regardless of the options border and spacing. The construction of all the widgets is performed using a scripting language VasyaScript. The description of the language can be found in the input data. For the final verification of the code Vasya asks you to write a program that calculates the sizes of all the widgets on the source code in the language of VasyaScript. Input The first line contains an integer n β€” the number of instructions (1 ≀ n ≀ 100). Next n lines contain instructions in the language VasyaScript β€” one instruction per line. There is a list of possible instructions below. * "Widget [name]([x],[y])" β€” create a new widget [name] of the type Widget possessing the width of [x] units and the height of [y] units. * "HBox [name]" β€” create a new widget [name] of the type HBox. * "VBox [name]" β€” create a new widget [name] of the type VBox. * "[name1].pack([name2])" β€” pack the widget [name2] in the widget [name1]. At that, the widget [name1] must be of type HBox or VBox. * "[name].set_border([x])" β€” set for a widget [name] the border parameter to [x] units. The widget [name] must be of type HBox or VBox. * "[name].set_spacing([x])" β€” set for a widget [name] the spacing parameter to [x] units. The widget [name] must be of type HBox or VBox. All instructions are written without spaces at the beginning and at the end of the string. The words inside the instruction are separated by exactly one space. There are no spaces directly before the numbers and directly after them. The case matters, for example, "wiDget x" is not a correct instruction. The case of the letters is correct in the input data. All names of the widgets consist of lowercase Latin letters and has the length from 1 to 10 characters inclusive. The names of all widgets are pairwise different. All numbers in the script are integers from 0 to 100 inclusive It is guaranteed that the above-given script is correct, that is that all the operations with the widgets take place after the widgets are created and no widget is packed in itself. It is guaranteed that the script creates at least one widget. Output For each widget print on a single line its name, width and height, separated by spaces. The lines must be ordered lexicographically by a widget's name. Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use cout stream (also you may use %I64d specificator) Examples Input 12 Widget me(50,40) VBox grandpa HBox father grandpa.pack(father) father.pack(me) grandpa.set_border(10) grandpa.set_spacing(20) Widget brother(30,60) father.pack(brother) Widget friend(20,60) Widget uncle(100,20) grandpa.pack(uncle) Output brother 30 60 father 80 60 friend 20 60 grandpa 120 120 me 50 40 uncle 100 20 Input 15 Widget pack(10,10) HBox dummy HBox x VBox y y.pack(dummy) y.set_border(5) y.set_spacing(55) dummy.set_border(10) dummy.set_spacing(20) x.set_border(10) x.set_spacing(10) x.pack(pack) x.pack(dummy) x.pack(pack) x.set_border(0) Output dummy 0 0 pack 10 10 x 40 10 y 10 10 Note In the first sample the widgets are arranged as follows: <image>
import sys from array import array # noqa: F401 import re def input(): return sys.stdin.buffer.readline().decode('utf-8') class Widget(object): def __init__(self, x, y): self.x = x self.y = y class Box(object): def __init__(self): self.children = [] self.border = 0 self.spacing = 0 self._x = -1 self._y = -1 def set_border(self, size): self.border = size def set_spacing(self, size): self.spacing = size def pack(self, widget): self.children.append(widget) @property def x(self): if self._x == -1: self._x = (max(child.x for child in self.children) + self.border * 2 if self.children else 0) return self._x @property def y(self): if self._y == -1: self._y = (max(child.y for child in self.children) + self.border * 2 if self.children else 0) return self._y class HBox(Box): @property def x(self): if self._x == -1: if not self.children: return 0 a = [child.x for child in self.children] self._x = self.border * 2 + sum(a) + self.spacing * (len(a) - 1) return self._x class VBox(Box): @property def y(self): if self._y == -1: if not self.children: return 0 a = [child.y for child in self.children] self._y = self.border * 2 + sum(a) + self.spacing * (len(a) - 1) return self._y if __name__ == '__main__': n = int(input()) namespace = {} pattern = re.compile(r'([^(]+?)\(([^)]+?)\)') def parse(s): return re.search(pattern, s).groups() for _ in range(n): command = input().split() if command[0] == 'Widget': name, args = parse(command[1]) namespace[name] = Widget(*tuple(map(int, args.split(',')))) elif command[0] == 'VBox': namespace[command[1]] = VBox() elif command[0] == 'HBox': namespace[command[1]] = HBox() else: name, method = command[0].split('.') method, args = parse(method) if method == 'set_border': namespace[name].set_border(int(args)) elif method == 'set_spacing': namespace[name].set_spacing(int(args)) elif method == 'pack': namespace[name].pack(namespace[args]) for name in sorted(namespace.keys()): print(f'{name} {namespace[name].x} {namespace[name].y}')
{ "input": [ "15\nWidget pack(10,10)\nHBox dummy\nHBox x\nVBox y\ny.pack(dummy)\ny.set_border(5)\ny.set_spacing(55)\ndummy.set_border(10)\ndummy.set_spacing(20)\nx.set_border(10)\nx.set_spacing(10)\nx.pack(pack)\nx.pack(dummy)\nx.pack(pack)\nx.set_border(0)\n", "12\nWidget me(50,40)\nVBox grandpa\nHBox father\ngrandpa.pack(father)\nfather.pack(me)\ngrandpa.set_border(10)\ngrandpa.set_spacing(20)\nWidget brother(30,60)\nfather.pack(brother)\nWidget friend(20,60)\nWidget uncle(100,20)\ngrandpa.pack(uncle)\n" ], "output": [ "dummy 0 0\npack 10 10\nx 40 10\ny 10 10\n", "brother 30 60\nfather 80 60\nfriend 20 60\ngrandpa 120 120\nme 50 40\nuncle 100 20\n" ] }
3,734
7
You are given a string A. Find a string B, where B is a palindrome and A is a subsequence of B. A subsequence of a string is a string that can be derived from it by deleting some (not necessarily consecutive) characters without changing the order of the remaining characters. For example, "cotst" is a subsequence of "contest". A palindrome is a string that reads the same forward or backward. The length of string B should be at most 104. It is guaranteed that there always exists such string. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. Input First line contains a string A (1 ≀ |A| ≀ 103) consisting of lowercase Latin letters, where |A| is a length of A. Output Output single line containing B consisting of only lowercase Latin letters. You do not need to find the shortest answer, the only restriction is that the length of string B should not exceed 104. If there are many possible B, print any of them. Examples Input aba Output aba Input ab Output aabaa Note In the first example, "aba" is a subsequence of "aba" which is a palindrome. In the second example, "ab" is a subsequence of "aabaa" which is a palindrome.
def superpalindrom(s): return s + s[::-1] print(superpalindrom(input()))
{ "input": [ "ab\n", "aba\n" ], "output": [ "abba\n", "abaaba\n" ] }
3,735
8
Mahmoud wants to send a message to his friend Ehab. Their language consists of n words numbered from 1 to n. Some words have the same meaning so there are k groups of words such that all the words in some group have the same meaning. Mahmoud knows that the i-th word can be sent with cost ai. For each word in his message, Mahmoud can either replace it with another word of the same meaning or leave it as it is. Can you help Mahmoud determine the minimum cost of sending the message? The cost of sending the message is the sum of the costs of sending every word in it. Input The first line of input contains integers n, k and m (1 ≀ k ≀ n ≀ 105, 1 ≀ m ≀ 105) β€” the number of words in their language, the number of groups of words, and the number of words in Mahmoud's message respectively. The second line contains n strings consisting of lowercase English letters of length not exceeding 20 which represent the words. It's guaranteed that the words are distinct. The third line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109) where ai is the cost of sending the i-th word. The next k lines describe the groups of words of same meaning. The next k lines each start with an integer x (1 ≀ x ≀ n) which means that there are x words in this group, followed by x integers which represent the indices of words in this group. It's guaranteed that each word appears in exactly one group. The next line contains m space-separated words which represent Mahmoud's message. Each of these words appears in the list of language's words. Output The only line should contain the minimum cost to send the message after replacing some words (maybe none) with some words of the same meaning. Examples Input 5 4 4 i loser am the second 100 1 1 5 10 1 1 1 3 2 2 5 1 4 i am the second Output 107 Input 5 4 4 i loser am the second 100 20 1 5 10 1 1 1 3 2 2 5 1 4 i am the second Output 116 Note In the first sample, Mahmoud should replace the word "second" with the word "loser" because it has less cost so the cost will be 100+1+5+1=107. In the second sample, Mahmoud shouldn't do any replacement so the cost will be 100+1+5+10=116.
def f(x): return int(x) - 1 n, k, m = map(int, input().split()) src = input().split() cs = list(map(int, input().split())) for _ in range(k): arr = list(map(f, input().split()))[1:] arr.sort(key=lambda x: cs[x]) for c in arr[1:]: cs[c] = cs[arr[0]] d = {x: y for x, y in zip(src, cs)} print(sum(d[x] for x in input().split()))
{ "input": [ "5 4 4\ni loser am the second\n100 20 1 5 10\n1 1\n1 3\n2 2 5\n1 4\ni am the second\n", "5 4 4\ni loser am the second\n100 1 1 5 10\n1 1\n1 3\n2 2 5\n1 4\ni am the second\n" ], "output": [ "116", "107" ] }
3,736
11
Astronaut Natasha arrived on Mars. She knows that the Martians are very poor aliens. To ensure a better life for the Mars citizens, their emperor decided to take tax from every tourist who visited the planet. Natasha is the inhabitant of Earth, therefore she had to pay the tax to enter the territory of Mars. There are n banknote denominations on Mars: the value of i-th banknote is a_i. Natasha has an infinite number of banknotes of each denomination. Martians have k fingers on their hands, so they use a number system with base k. In addition, the Martians consider the digit d (in the number system with base k) divine. Thus, if the last digit in Natasha's tax amount written in the number system with the base k is d, the Martians will be happy. Unfortunately, Natasha does not know the Martians' divine digit yet. Determine for which values d Natasha can make the Martians happy. Natasha can use only her banknotes. Martians don't give her change. Input The first line contains two integers n and k (1 ≀ n ≀ 100 000, 2 ≀ k ≀ 100 000) β€” the number of denominations of banknotes and the base of the number system on Mars. The second line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 10^9) β€” denominations of banknotes on Mars. All numbers are given in decimal notation. Output On the first line output the number of values d for which Natasha can make the Martians happy. In the second line, output all these values in increasing order. Print all numbers in decimal notation. Examples Input 2 8 12 20 Output 2 0 4 Input 3 10 10 20 30 Output 1 0 Note Consider the first test case. It uses the octal number system. If you take one banknote with the value of 12, you will get 14_8 in octal system. The last digit is 4_8. If you take one banknote with the value of 12 and one banknote with the value of 20, the total value will be 32. In the octal system, it is 40_8. The last digit is 0_8. If you take two banknotes with the value of 20, the total value will be 40, this is 50_8 in the octal system. The last digit is 0_8. No other digits other than 0_8 and 4_8 can be obtained. Digits 0_8 and 4_8 could also be obtained in other ways. The second test case uses the decimal number system. The nominals of all banknotes end with zero, so Natasha can give the Martians only the amount whose decimal notation also ends with zero.
def gcd(a, b): while b: a, b = b, a % b return a n, k = map(int, input().split()) a = list(set([int(i) % k for i in input().split()])) res = k for i in a: res = gcd(res, i) print(k // res) print(*list(range(0, k, res)))
{ "input": [ "3 10\n10 20 30\n", "2 8\n12 20\n" ], "output": [ "1\n0 ", "2\n0 4 " ] }
3,737
12
Consider some positive integer x. Its prime factorization will be of form x = 2^{k_1} β‹… 3^{k_2} β‹… 5^{k_3} β‹… ... Let's call x elegant if the greatest common divisor of the sequence k_1, k_2, ... is equal to 1. For example, numbers 5 = 5^1, 12 = 2^2 β‹… 3, 72 = 2^3 β‹… 3^2 are elegant and numbers 8 = 2^3 (GCD = 3), 2500 = 2^2 β‹… 5^4 (GCD = 2) are not. Count the number of elegant integers from 2 to n. Each testcase contains several values of n, for each of them you are required to solve the problem separately. Input The first line contains a single integer T (1 ≀ T ≀ 10^5) β€” the number of values of n in the testcase. Each of the next T lines contains a single integer n_i (2 ≀ n_i ≀ 10^{18}). Output Print T lines β€” the i-th line should contain the number of elegant numbers from 2 to n_i. Example Input 4 4 2 72 10 Output 2 1 61 6 Note Here is the list of non-elegant numbers up to 10: * 4 = 2^2, GCD = 2; * 8 = 2^3, GCD = 3; * 9 = 3^2, GCD = 2. The rest have GCD = 1.
from math import sqrt, log2 from sys import stdin from bisect import bisect import time def all_primes(n): res = [] for i in range(1, n+1): prime = True for j in range(2, min(int(sqrt(i))+2, i)): if i % j == 0: prime = False break if prime: res.append(i) return res def count_pow_nums(n, p): #don't count 1 top = int(pow(n, 1.0/p)) if pow(top+2, p) <= n: return top+1 elif pow(top+1, p) <= n: return top elif pow(top, p) <= n: return top-1 else: return top-2 primes = all_primes(64) num_set=set() max_n = 1000000000000000000 for pi in range(3, len(primes)): p = primes[pi] cnt = count_pow_nums(max_n, p) for n in range(2, cnt+5): sq2 = round(sqrt(n)) sq3 = round(pow(n, 1/3)) if sq2**2 != n and sq3**3 != n: num = pow(n, p) if num <= max_n: num_set.add(num) nums = sorted(num_set) t = int(stdin.readline()) for i in range(t): n = int(stdin.readline()) ans = n-1-count_pow_nums(n, 2)-count_pow_nums(n, 3)+count_pow_nums(n, 6) ans -= bisect(nums, n) print(ans)
{ "input": [ "4\n4\n2\n72\n10\n" ], "output": [ " 2\n 1\n 61\n 6\n" ] }
3,738
11
You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i β‰₯ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≀ n ≀ 10^5, 1 ≀ L ≀ 10^5, 1 ≀ S ≀ 10^{18}) β€” the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≀ w_i ≀ 10^9) β€” the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≀ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number β€” the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree.
def solve(n, l, s, www, children): ans = 0 dp = [{} for _ in range(n)] for v in range(n - 1, -1, -1): cv = children[v] if not cv: dp[v][1] = www[v] continue ans += len(cv) - 1 wv = www[v] if wv > s: return -1 dv = dp[v] for c in cv: for lc, wc in dp[c].items(): if lc == l: continue wt = wc + wv if wt > s: continue if lc + 1 not in dv: dv[lc + 1] = wt else: dv[lc + 1] = min(dv[lc + 1], wt) if not dv: ans += 1 dv[1] = wv return ans + 1 n, l, s = list(map(int, input().split())) www = list(map(int, input().split())) if n == 1: print(-1 if www[0] > s else 1) exit() children = [set() for _ in range(n)] for i, p in enumerate(map(int, input().split())): children[p - 1].add(i + 1) print(solve(n, l, s, www, children))
{ "input": [ "3 1 3\n1 2 3\n1 1\n", "3 3 6\n1 2 3\n1 1\n", "1 1 10000\n10001\n" ], "output": [ "3\n", "2\n", "-1\n" ] }
3,739
7
Chouti was doing a competitive programming competition. However, after having all the problems accepted, he got bored and decided to invent some small games. He came up with the following game. The player has a positive integer n. Initially the value of n equals to v and the player is able to do the following operation as many times as the player want (possibly zero): choose a positive integer x that x<n and x is not a divisor of n, then subtract x from n. The goal of the player is to minimize the value of n in the end. Soon, Chouti found the game trivial. Can you also beat the game? Input The input contains only one integer in the first line: v (1 ≀ v ≀ 10^9), the initial value of n. Output Output a single integer, the minimum value of n the player can get. Examples Input 8 Output 1 Input 1 Output 1 Note In the first example, the player can choose x=3 in the first turn, then n becomes 5. He can then choose x=4 in the second turn to get n=1 as the result. There are other ways to get this minimum. However, for example, he cannot choose x=2 in the first turn because 2 is a divisor of 8. In the second example, since n=1 initially, the player can do nothing.
def f(n): if n==2: return 2 else: return 1 n=int(input()) print(f(n))
{ "input": [ "8\n", "1\n" ], "output": [ "1\n", "1\n" ] }
3,740
7
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 by closing every k-th (2 ≀ k ≀ n - 1) tab. Only then he will decide whether he wants to study for the test or to chat on the social networks. Formally, Roman will choose one tab (let its number be b) and then close all tabs with numbers c = b + i β‹… k that satisfy the following condition: 1 ≀ c ≀ n and i is an integer (it may be positive, negative or zero). For example, if k = 3, n = 14 and Roman chooses b = 8, then he will close tabs with numbers 2, 5, 8, 11 and 14. After closing the tabs Roman will calculate the amount of remaining tabs with the information for the test (let's denote it e) and the amount of remaining social network tabs (s). Help Roman to calculate the maximal absolute value of the difference of those values |e - s| so that it would be easy to decide what to do next. Input The first line contains two integers n and k (2 ≀ k < n ≀ 100) β€” the amount of tabs opened currently and the distance between the tabs closed. The second line consists of n integers, each of them equal either to 1 or to -1. The i-th integer denotes the type of the i-th tab: if it is equal to 1, this tab contains information for the test, and if it is equal to -1, it's a social network tab. Output Output a single integer β€” the maximum absolute difference between the amounts of remaining tabs of different types |e - s|. Examples Input 4 2 1 1 -1 1 Output 2 Input 14 3 -1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1 Output 9 Note In the first example we can choose b = 1 or b = 3. We will delete then one tab of each type and the remaining tabs are then all contain test information. Thus, e = 2 and s = 0 and |e - s| = 2. In the second example, on the contrary, we can leave opened only tabs that have social networks opened in them.
def solve(xs, k): ks = [0] * k for i, x in enumerate(xs): ks[i % k] += x sum_all = sum(ks) return max([abs(sum_all - x) for x in ks]) n, k = map(int, input().split()) xs = list(map(int, input().split()))[:n] print(solve(xs, k))
{ "input": [ "14 3\n-1 1 -1 -1 1 -1 -1 1 -1 -1 1 -1 -1 1\n", "4 2\n1 1 -1 1\n" ], "output": [ "9\n", "2\n" ] }
3,741
11
One player came to a casino and found a slot machine where everything depends only on how he plays. The rules follow. A positive integer a is initially on the screen. The player can put a coin into the machine and then add 1 to or subtract 1 from any two adjacent digits. All digits must remain from 0 to 9 after this operation, and the leading digit must not equal zero. In other words, it is forbidden to add 1 to 9, to subtract 1 from 0 and to subtract 1 from the leading 1. Once the number on the screen becomes equal to b, the player wins the jackpot. a and b have the same number of digits. Help the player to determine the minimal number of coins he needs to spend in order to win the jackpot and tell how to play. Input The first line contains a single integer n (2 ≀ n ≀ 10^5) standing for the length of numbers a and b. The next two lines contain numbers a and b, each one on a separate line (10^{n-1} ≀ a, b < 10^n). Output If it is impossible to win the jackpot, print a single integer -1. Otherwise, the first line must contain the minimal possible number c of coins the player has to spend. min(c, 10^5) lines should follow, i-th of them containing two integers d_i and s_i (1≀ d_i≀ n - 1, s_i = Β± 1) denoting that on the i-th step the player should add s_i to the d_i-th and (d_i + 1)-st digits from the left (e. g. d_i = 1 means that two leading digits change while d_i = n - 1 means that there are two trailing digits which change). Please notice that the answer may be very big and in case c > 10^5 you should print only the first 10^5 moves. Your answer is considered correct if it is possible to finish your printed moves to win the jackpot in the minimal possible number of coins. In particular, if there are multiple ways to do this, you can output any of them. Examples Input 3 223 322 Output 2 1 1 2 -1 Input 2 20 42 Output 2 1 1 1 1 Input 2 35 44 Output -1 Note In the first example, we can make a +1 operation on the two first digits, transforming number 223 into 333, and then make a -1 operation on the last two digits, transforming 333 into 322. It's also possible to do these operations in reverse order, which makes another correct answer. In the last example, one can show that it's impossible to transform 35 into 44.
def main(): n = int(input()) a = list(map(int, (x for x in input()))) b = list(map(int, (x for x in input()))) x = [0] * (n - 1) x[0] = b[0] - a[0] for i in range(1, n - 1): x[i] = b[i] - a[i] - x[i - 1] if a[n - 1] + x[n - 2] != b[n - 1]: print(-1) return cnt = sum(map(abs, x)) # prevbug: ftl print(cnt) cnt = min(cnt, 10 ** 5) index = 0 def handle_zero_nine(cur_zero): nonlocal cnt nxt = index + 1 # cur_zero = True prevbug: preserved this line while True: if cur_zero and a[nxt + 1] != 9: break if not cur_zero and a[nxt + 1] != 0: break nxt += 1 cur_zero = not cur_zero while nxt > index: if cnt == 0: break if cur_zero: print(nxt + 1, 1) a[nxt] += 1 a[nxt + 1] += 1 else: print(nxt + 1, -1) a[nxt] -= 1 a[nxt + 1] -= 1 nxt -= 1 cnt -= 1 # print(a) cur_zero = not cur_zero while cnt > 0: if a[index] == b[index]: index += 1 continue elif a[index] > b[index] and a[index + 1] == 0: handle_zero_nine(True) elif a[index] < b[index] and a[index + 1] == 9: handle_zero_nine(False) elif a[index] > b[index]: print(index + 1, -1) a[index] -= 1 a[index + 1] -= 1 cnt -= 1 # print(a) elif a[index] < b[index]: print(index + 1, 1) a[index] += 1 a[index + 1] += 1 cnt -= 1 # print(a) if __name__ == '__main__': main()
{ "input": [ "3\n223\n322\n", "2\n35\n44\n", "2\n20\n42\n" ], "output": [ "2\n1 1\n2 -1\n", "-1\n", "2\n1 1\n1 1\n" ] }
3,742
10
You have a garden consisting entirely of grass and weeds. Your garden is described by an n Γ— m grid, with rows numbered 1 to n from top to bottom, and columns 1 to m from left to right. Each cell is identified by a pair (r, c) which means that the cell is located at row r and column c. Each cell may contain either grass or weeds. For example, a 4 Γ— 5 garden may look as follows (empty cells denote grass): <image> You have a land-mower with you to mow all the weeds. Initially, you are standing with your lawnmower at the top-left corner of the garden. That is, at cell (1, 1). At any moment of time you are facing a certain direction β€” either left or right. And initially, you face right. In one move you can do either one of these: 1) Move one cell in the direction that you are facing. * if you are facing right: move from cell (r, c) to cell (r, c + 1) <image> * if you are facing left: move from cell (r, c) to cell (r, c - 1) <image> 2) Move one cell down (that is, from cell (r, c) to cell (r + 1, c)), and change your direction to the opposite one. * if you were facing right previously, you will face left <image> * if you were facing left previously, you will face right <image> You are not allowed to leave the garden. Weeds will be mowed if you and your lawnmower are standing at the cell containing the weeds (your direction doesn't matter). This action isn't counted as a move. What is the minimum number of moves required to mow all the weeds? Input The first line contains two integers n and m (1 ≀ n, m ≀ 150) β€” the number of rows and columns respectively. Then follow n lines containing m characters each β€” the content of the grid. "G" means that this cell contains grass. "W" means that this cell contains weeds. It is guaranteed that the top-left corner of the grid will contain grass. Output Print a single number β€” the minimum number of moves required to mow all the weeds. Examples Input 4 5 GWGGW GGWGG GWGGG WGGGG Output 11 Input 3 3 GWW WWW WWG Output 7 Input 1 1 G Output 0 Note For the first example, this is the picture of the initial state of the grid: <image> A possible solution is by mowing the weeds as illustrated below: <image>
from sys import maxsize, stdout, stdin,stderr mod = int(1e9 + 7) def I(): return int(stdin.readline()) def lint(): return [int(x) for x in stdin.readline().split()] def S(): return input().strip() def grid(r, c): return [lint() for i in range(r)] from collections import defaultdict, Counter import math import heapq from heapq import heappop , heappush import bisect from itertools import groupby def gcd(a,b): while b: a %= b tmp = a a = b b = tmp return a def lcm(a,b): return a / gcd(a, b) * b def check_prime(n): for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True def Bs(a, x): i=0 j=0 left = 0 right = len(a) flag=False while left<right: mi = (left+right)//2 #print(smi,a[mi],x) if a[mi]<=x: left = mi+1 i+=1 else: right = mi j+=1 #print(left,right,"----") #print(i-1,j) if left>0 and a[left-1]==x: return i-1, j else: return -1, -1 def nCr(n, r): return (fact(n) // (fact(r) * fact(n - r))) # Returns factorial of n def fact(n): res = 1 for i in range(2, n+1): res = res * i return res def primefactors(n): num=0 while n % 2 == 0: num+=1 n = n / 2 for i in range(3,int(math.sqrt(n))+1,2): while n % i== 0: num+=1 n = n // i if n > 2: num+=1 return num ''' def iter_ds(src): store=[src] while len(store): tmp=store.pop() if not vis[tmp]: vis[tmp]=True for j in ar[tmp]: store.append(j) ''' def ask(a): print('? {}'.format(a),flush=True) n=lint() return n d = defaultdict(lambda:[]) def dfs(i,p): a,tmp=0,0 for j in d[i]: if j!=p: a+=1 tmp+=dfs(j,i) if a==0: return 0 return tmp/a + 1 n,m=lint() s = [input() for _ in range(n)] l=[] new_n=0 for i in range(n): mi,ma=None ,None for j in range(m): if s[i][j]=='W': if mi==None: mi=j ma=j if mi!=None: new_n=i l.append([mi,ma]) f=['R','L'] ans=0 j=0 for i in range(new_n+1): if i==n-1: if f[i%2]=='R': t=l[i][1] if l[i][1]==None: t=0 tmp=max(t,j) ans+=tmp-j j=tmp else: t=l[i][0] if l[i][0]==None: t=m tmp=min(t,j) ans+=j-tmp j=tmp else: if f[i%2]=='R': t,t2=l[i+1][1],l[i][1] if l[i+1][1]==None: t=0 if l[i][1]==None: t2=0 tmp=max(t,max(t2,j)) ans+=tmp-j j=tmp else: t,t2=l[i+1][0],l[i][0] if l[i+1][0]==None: t=m if l[i][0]==None: t2=m tmp=min(t,min(t2,j)) ans+=j-tmp j=tmp ans+=1 print(ans-1)
{ "input": [ "4 5\nGWGGW\nGGWGG\nGWGGG\nWGGGG\n", "1 1\nG\n", "3 3\nGWW\nWWW\nWWG\n" ], "output": [ "11", "0", "7" ] }
3,743
10
You are given a sequence of n pairs of integers: (a_1, b_1), (a_2, b_2), ... , (a_n, b_n). This sequence is called bad if it is sorted in non-descending order by first elements or if it is sorted in non-descending order by second elements. Otherwise the sequence is good. There are examples of good and bad sequences: * s = [(1, 2), (3, 2), (3, 1)] is bad because the sequence of first elements is sorted: [1, 3, 3]; * s = [(1, 2), (3, 2), (1, 2)] is bad because the sequence of second elements is sorted: [2, 2, 2]; * s = [(1, 1), (2, 2), (3, 3)] is bad because both sequences (the sequence of first elements and the sequence of second elements) are sorted; * s = [(1, 3), (3, 3), (2, 2)] is good because neither the sequence of first elements ([1, 3, 2]) nor the sequence of second elements ([3, 3, 2]) is sorted. Calculate the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence. A permutation p of size n is a sequence p_1, p_2, ... , p_n consisting of n distinct integers from 1 to n (1 ≀ p_i ≀ n). If you apply permutation p_1, p_2, ... , p_n to the sequence s_1, s_2, ... , s_n you get the sequence s_{p_1}, s_{p_2}, ... , s_{p_n}. For example, if s = [(1, 2), (1, 3), (2, 3)] and p = [2, 3, 1] then s turns into [(1, 3), (2, 3), (1, 2)]. Input The first line contains one integer n (1 ≀ n ≀ 3 β‹… 10^5). The next n lines contains description of sequence s. The i-th line contains two integers a_i and b_i (1 ≀ a_i, b_i ≀ n) β€” the first and second elements of i-th pair in the sequence. The sequence s may contain equal elements. Output Print the number of permutations of size n such that after applying this permutation to the sequence s it turns into a good sequence. Print the answer modulo 998244353 (a prime number). Examples Input 3 1 1 2 2 3 1 Output 3 Input 4 2 3 2 2 2 1 2 4 Output 0 Input 3 1 1 1 1 2 3 Output 4 Note In first test case there are six permutations of size 3: 1. if p = [1, 2, 3], then s = [(1, 1), (2, 2), (3, 1)] β€” bad sequence (sorted by first elements); 2. if p = [1, 3, 2], then s = [(1, 1), (3, 1), (2, 2)] β€” bad sequence (sorted by second elements); 3. if p = [2, 1, 3], then s = [(2, 2), (1, 1), (3, 1)] β€” good sequence; 4. if p = [2, 3, 1], then s = [(2, 2), (3, 1), (1, 1)] β€” good sequence; 5. if p = [3, 1, 2], then s = [(3, 1), (1, 1), (2, 2)] β€” bad sequence (sorted by second elements); 6. if p = [3, 2, 1], then s = [(3, 1), (2, 2), (1, 1)] β€” good sequence.
from collections import Counter import sys input = sys.stdin.readline MOD = 998244353 n = int(input()) s = sorted([tuple(map(int, input().split())) for _ in range(n)]) fact = [1] for i in range(1, n + 1): fact.append(fact[-1] * i % MOD) def ways(l): count = Counter(l) res = 1 for x in count.values(): res *= fact[x] res %= MOD return res a = ways([x for x, _ in s]) b = ways([y for _, y in s]) c = ways(s) if all(s[i - 1][1] <= s[i][1] for i in range(1, n)) else 0 print((fact[n] - a - b + c) % MOD)
{ "input": [ "3\n1 1\n1 1\n2 3\n", "3\n1 1\n2 2\n3 1\n", "4\n2 3\n2 2\n2 1\n2 4\n" ], "output": [ "4", "3", "0" ] }
3,744
11
You are at the top left cell (1, 1) of an n Γ— m labyrinth. Your goal is to get to the bottom right cell (n, m). You can only move right or down, one cell per step. Moving right from a cell (x, y) takes you to the cell (x, y + 1), while moving down takes you to the cell (x + 1, y). Some cells of the labyrinth contain rocks. When you move to a cell with rock, the rock is pushed to the next cell in the direction you're moving. If the next cell contains a rock, it gets pushed further, and so on. The labyrinth is surrounded by impenetrable walls, thus any move that would put you or any rock outside of the labyrinth is illegal. Count the number of different legal paths you can take from the start to the goal modulo 10^9 + 7. Two paths are considered different if there is at least one cell that is visited in one path, but not visited in the other. Input The first line contains two integers n, m β€” dimensions of the labyrinth (1 ≀ n, m ≀ 2000). Next n lines describe the labyrinth. Each of these lines contains m characters. The j-th character of the i-th of these lines is equal to "R" if the cell (i, j) contains a rock, or "." if the cell (i, j) is empty. It is guaranteed that the starting cell (1, 1) is empty. Output Print a single integer β€” the number of different legal paths from (1, 1) to (n, m) modulo 10^9 + 7. Examples Input 1 1 . Output 1 Input 2 3 ... ..R Output 0 Input 4 4 ...R .RR. .RR. R... Output 4 Note In the first sample case we can't (and don't have to) move, hence the only path consists of a single cell (1, 1). In the second sample case the goal is blocked and is unreachable. Illustrations for the third sample case can be found here: <https://assets.codeforces.com/rounds/1225/index.html>
def getSum(dp, pos, s, e, type_): if e < s: return 0 if type_=='D': if e==m-1: return dp[pos][s] return dp[pos][s]-dp[pos][e+1] else: if e==n-1: return dp[s][pos] return dp[s][pos]-dp[e+1][pos] mod = 10**9+7 n, m = map(int, input().split()) a = [list(list(map(lambda x: 1 if x=='R' else 0, input()))) for _ in range(n)] SD = [[0]*m for _ in range(n)] SN = [[0]*m for _ in range(n)] dpD = [[0]*m for _ in range(n)] dpN = [[0]*m for _ in range(n)] for i in range(n-1, -1, -1): for j in range(m-1, -1, -1): if i == n-1: SD[i][j]=a[i][j] else: SD[i][j]=SD[i+1][j]+a[i][j] if j == m-1: SN[i][j]=a[i][j] else: SN[i][j]=SN[i][j+1]+a[i][j] for j in range(m-1,-1,-1): if a[n-1][j]==1: break dpD[n-1][j]=1 dpN[n-1][j]=1 for i in range(n-1,-1,-1): if a[i][m-1]==1: break dpD[i][m-1]=1 dpN[i][m-1]=1 for j in range(m-2, -1, -1): if i==n-1: break dpD[n-1][j]+=dpD[n-1][j+1] for i in range(n-2,-1,-1): if j==m-1: break dpN[i][m-1]+=dpN[i+1][m-1] for i in range(n-2,-1,-1): for j in range(m-2,-1,-1): s, e = j, m-SN[i][j]-1 #print(i, j, s, e, 'N') dpN[i][j] = getSum(dpD, i+1, s, e, 'D') dpN[i][j] = (dpN[i][j] + dpN[i+1][j]) % mod s, e = i, n-SD[i][j]-1 #print(i, j, s, e, 'D') dpD[i][j] = getSum(dpN, j+1, s, e, 'N') if i != 0: for j in range(m-2,-1,-1): dpD[i][j] = (dpD[i][j] + dpD[i][j+1]) % mod print(dpD[0][0] % mod)
{ "input": [ "2 3\n...\n..R\n", "4 4\n...R\n.RR.\n.RR.\nR...\n", "1 1\n.\n" ], "output": [ "0\n", "4\n", "1\n" ] }
3,745
7
Petr stands in line of n people, but he doesn't know exactly which position he occupies. He can say that there are no less than a people standing in front of him and no more than b people standing behind him. Find the number of different positions Petr can occupy. Input The only line contains three integers n, a and b (0 ≀ a, b < n ≀ 100). Output Print the single number β€” the number of the sought positions. Examples Input 3 1 1 Output 2 Input 5 2 3 Output 3 Note The possible positions in the first sample are: 2 and 3 (if we number the positions starting with 1). In the second sample they are 3, 4 and 5.
def main(): n, a, b = map(int, input().split()) print(n - max(a + 1, n - b) + 1) main()
{ "input": [ "3 1 1\n", "5 2 3\n" ], "output": [ "2", "3" ] }
3,746
10
There are n children, who study at the school β„–41. It is well-known that they are good mathematicians. Once at a break, they arranged a challenge for themselves. All children arranged in a row and turned heads either to the left or to the right. Children can do the following: in one second several pairs of neighboring children who are looking at each other can simultaneously turn the head in the opposite direction. For instance, the one who was looking at the right neighbor turns left and vice versa for the second child. Moreover, every second at least one pair of neighboring children performs such action. They are going to finish when there is no pair of neighboring children who are looking at each other. You are given the number n, the initial arrangement of children and the number k. You have to find a way for the children to act if they want to finish the process in exactly k seconds. More formally, for each of the k moves, you need to output the numbers of the children who turn left during this move. For instance, for the configuration shown below and k = 2 children can do the following steps: <image> At the beginning, two pairs make move: (1, 2) and (3, 4). After that, we receive the following configuration: <image> At the second move pair (2, 3) makes the move. The final configuration is reached. Good job. <image> It is guaranteed that if the solution exists, it takes not more than n^2 "headturns". Input The first line of input contains two integers n and k (2 ≀ n ≀ 3000, 1 ≀ k ≀ 3000000) β€” the number of children and required number of moves. The next line contains a string of length n and consists only of characters L and R, where L means that the child looks to the left and R means that the child looks to the right. Output If there is no solution, print a single line with number -1. Otherwise, output k lines. Each line has to start with a number n_i (1≀ n_i ≀ n/2) β€” the number of pairs of children, who turn at this move. After that print n_i distinct integers β€” the numbers of the children who will turn left during this move. After performing all "headturns", there can't be a pair of two neighboring children looking at each other. If there are many solutions, print any of them. Examples Input 2 1 RL Output 1 1 Input 2 1 LR Output -1 Input 4 2 RLRL Output 2 1 3 1 2 Note The first sample contains a pair of children who look at each other. After one move, they can finish the process. In the second sample, children can't make any move. As a result, they can't end in k>0 moves. The third configuration is described in the statement.
import sys def print(s): return sys.stdout.write(s + '\n') n,k=map(int,input().split()) s = list(input()) mn =0 mx = 0 mvs = [] for i in range(n): j = 0 mvs.append([]) while j < n-1: if s[j] == 'R' and s[j+1] =='L': s[j],s[j+1] = 'L', 'R' mvs[-1].append(j) j +=2 mx+=1 else: j+=1 if len(mvs[-1]) == 0: break if len(mvs[-1]) == 0: mvs =mvs[:-1] mn = len(mvs) if k < mn or k> mx: print('-1') exit() i,j=0,0 ans = [] for b in range(k): if k - b > mn - i: ans.append('1 {}'.format(mvs[i][j]+1)) j += 1 if j == len(mvs[i]): i+=1 j=0 else: p = mvs[i][j:] ans.append(('{} {}'.format(len(p), ' '.join([str(kk+1) for kk in p])))) i +=1 j=0 for an in ans: print(an)
{ "input": [ "4 2\nRLRL\n", "2 1\nRL\n", "2 1\nLR\n" ], "output": [ "2 1 3 \n1 2 \n", "1 1 \n", "-1\n" ] }
3,747
7
Polycarp has spent the entire day preparing problems for you. Now he has to sleep for at least a minutes to feel refreshed. Polycarp can only wake up by hearing the sound of his alarm. So he has just fallen asleep and his first alarm goes off in b minutes. Every time Polycarp wakes up, he decides if he wants to sleep for some more time or not. If he's slept for less than a minutes in total, then he sets his alarm to go off in c minutes after it is reset and spends d minutes to fall asleep again. Otherwise, he gets out of his bed and proceeds with the day. If the alarm goes off while Polycarp is falling asleep, then he resets his alarm to go off in another c minutes and tries to fall asleep for d minutes again. You just want to find out when will Polycarp get out of his bed or report that it will never happen. Please check out the notes for some explanations of the example. Input The first line contains one integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The only line of each testcase contains four integers a, b, c, d (1 ≀ a, b, c, d ≀ 10^9) β€” the time Polycarp has to sleep for to feel refreshed, the time before the first alarm goes off, the time before every succeeding alarm goes off and the time Polycarp spends to fall asleep. Output For each test case print one integer. If Polycarp never gets out of his bed then print -1. Otherwise, print the time it takes for Polycarp to get out of his bed. Example Input 7 10 3 6 4 11 3 6 4 5 9 4 10 6 5 2 3 1 1 1 1 3947465 47342 338129 123123 234123843 13 361451236 361451000 Output 27 27 9 -1 1 6471793 358578060125049 Note In the first testcase Polycarp wakes up after 3 minutes. He only rested for 3 minutes out of 10 minutes he needed. So after that he sets his alarm to go off in 6 minutes and spends 4 minutes falling asleep. Thus, he rests for 2 more minutes, totaling in 3+2=5 minutes of sleep. Then he repeats the procedure three more times and ends up with 11 minutes of sleep. Finally, he gets out of his bed. He spent 3 minutes before the first alarm and then reset his alarm four times. The answer is 3+4 β‹… 6 = 27. The second example is almost like the first one but Polycarp needs 11 minutes of sleep instead of 10. However, that changes nothing because he gets 11 minutes with these alarm parameters anyway. In the third testcase Polycarp wakes up rested enough after the first alarm. Thus, the answer is b=9. In the fourth testcase Polycarp wakes up after 5 minutes. Unfortunately, he keeps resetting his alarm infinitely being unable to rest for even a single minute :(
import math def scanf(): return list(map(int,input().split())) for _ in range(int(input())): a,b,c,d = scanf() if(c > d): print(b+c*math.ceil(max(0,a-b)/(c-d))) else: print(b if b>=a else -1)
{ "input": [ "7\n10 3 6 4\n11 3 6 4\n5 9 4 10\n6 5 2 3\n1 1 1 1\n3947465 47342 338129 123123\n234123843 13 361451236 361451000\n" ], "output": [ "27\n27\n9\n-1\n1\n6471793\n358578060125049\n" ] }
3,748
12
The government of Berland decided to improve network coverage in his country. Berland has a unique structure: the capital in the center and n cities in a circle around the capital. The capital already has a good network coverage (so the government ignores it), but the i-th city contains a_i households that require a connection. The government designed a plan to build n network stations between all pairs of neighboring cities which will maintain connections only for these cities. In other words, the i-th network station will provide service only for the i-th and the (i + 1)-th city (the n-th station is connected to the n-th and the 1-st city). All network stations have capacities: the i-th station can provide the connection to at most b_i households. Now the government asks you to check can the designed stations meet the needs of all cities or not β€” that is, is it possible to assign each household a network station so that each network station i provides the connection to at most b_i households. Input The first line contains a single integer t (1 ≀ t ≀ 10^4) β€” the number of test cases. The first line of each test case contains the single integer n (2 ≀ n ≀ 10^6) β€” the number of cities and stations. The second line of each test case contains n integers (1 ≀ a_i ≀ 10^9) β€” the number of households in the i-th city. The third line of each test case contains n integers (1 ≀ b_i ≀ 10^9) β€” the capacities of the designed stations. It's guaranteed that the sum of n over test cases doesn't exceed 10^6. Output For each test case, print YES, if the designed stations can meet the needs of all cities, or NO otherwise (case insensitive). Example Input 5 3 2 3 4 3 3 3 3 3 3 3 2 3 4 4 2 3 4 5 3 7 2 2 4 4 5 2 3 2 3 2 7 2 1 1 10 10 Output YES YES NO YES YES Note In the first test case: * the first network station can provide 2 connections to the first city and 1 connection to the second city; * the second station can provide 2 connections to the second city and 1 connection to the third city; * the third station can provide 3 connections to the third city. In the second test case: * the 1-st station can provide 2 connections to the 1-st city; * the 2-nd station can provide 3 connections to the 2-nd city; * the 3-rd station can provide 3 connections to the 3-rd city and 1 connection to the 1-st station. In the third test case, the fourth city needs 5 connections, but the third and the fourth station has 4 connections in total.
import sys input = sys.stdin.readline def solve(): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) lo = 0 hi = min(A[0], B[-1])+1 done = False while lo < hi: take = (lo + hi) // 2 avail = take for i in range(n): v = A[i] ned = max(0, v - avail) if i < n-1: if B[i] < ned: lo = take + 1 break else: if B[i] - take < ned: hi = take break else: print('YES') return avail = B[i] - ned print('NO') for _ in range(int(input())): solve()
{ "input": [ "5\n3\n2 3 4\n3 3 3\n3\n3 3 3\n2 3 4\n4\n2 3 4 5\n3 7 2 2\n4\n4 5 2 3\n2 3 2 7\n2\n1 1\n10 10\n" ], "output": [ "YES\nYES\nNO\nYES\nYES\n" ] }
3,749
8
"You must lift the dam. With a lever. I will give it to you. You must block the canal. With a rock. I will not give the rock to you." Danik urgently needs rock and lever! Obviously, the easiest way to get these things is to ask Hermit Lizard for them. Hermit Lizard agreed to give Danik the lever. But to get a stone, Danik needs to solve the following task. You are given a positive integer n, and an array a of positive integers. The task is to calculate the number of such pairs (i,j) that i<j and a_i \& a_j β‰₯ a_i βŠ• a_j, where \& denotes the [bitwise AND operation](https://en.wikipedia.org/wiki/Bitwise_operation#AND), and βŠ• denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR). Danik has solved this task. But can you solve it? Input Each test contains multiple test cases. The first line contains one positive integer t (1 ≀ t ≀ 10) denoting the number of test cases. Description of the test cases follows. The first line of each test case contains one positive integer n (1 ≀ n ≀ 10^5) β€” length of the array. The second line contains n positive integers a_i (1 ≀ a_i ≀ 10^9) β€” elements of the array. It is guaranteed that the sum of n over all test cases does not exceed 10^5. Output For every test case print one non-negative integer β€” the answer to the problem. Example Input 5 5 1 4 3 7 10 3 1 1 1 4 6 2 5 3 2 2 4 1 1 Output 1 3 2 0 0 Note In the first test case there is only one pair: (4,7): for it 4 \& 7 = 4, and 4 βŠ• 7 = 3. In the second test case all pairs are good. In the third test case there are two pairs: (6,5) and (2,3). In the fourth test case there are no good pairs.
def and_or(l): m=[0]*32 k=0 for i in l: k+=m[i.bit_length()] m[i.bit_length()]+=1 return k for _ in range(int(input())): input() l=list(map(int,input().split())) print(and_or(l))
{ "input": [ "5\n5\n1 4 3 7 10\n3\n1 1 1\n4\n6 2 5 3\n2\n2 4\n1\n1\n" ], "output": [ "1\n3\n2\n0\n0\n" ] }
3,750
7
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 operation: select 3 different cells that belong to one 2 Γ— 2 square and change the symbols in these cells (change 0 to 1 and 1 to 0). Your task is to make all symbols in the table equal to 0. You are allowed to make at most 3nm operations. You don't need to minimize the number of operations. It can be proved that it is always possible. Input The first line contains a single integer t (1 ≀ t ≀ 5000) β€” the number of test cases. The next lines contain descriptions of test cases. The first line of the description of each test case contains two integers n, m (2 ≀ n, m ≀ 100). Each of the next n lines contains a binary string of length m, describing the symbols of the next row of the table. It is guaranteed that the sum of nm for all test cases does not exceed 20000. Output For each test case print the integer k (0 ≀ k ≀ 3nm) β€” the number of operations. In the each of the next k lines print 6 integers x_1, y_1, x_2, y_2, x_3, y_3 (1 ≀ x_1, x_2, x_3 ≀ n, 1 ≀ y_1, y_2, y_3 ≀ m) describing the next operation. This operation will be made with three cells (x_1, y_1), (x_2, y_2), (x_3, y_3). These three cells should be different. These three cells should belong into some 2 Γ— 2 square. Example Input 5 2 2 10 11 3 3 011 101 110 4 4 1111 0110 0110 1111 5 5 01011 11001 00010 11011 10000 2 3 011 101 Output 1 1 1 2 1 2 2 2 2 1 3 1 3 2 1 2 1 3 2 3 4 1 1 1 2 2 2 1 3 1 4 2 3 3 2 4 1 4 2 3 3 4 3 4 4 4 1 2 2 1 2 2 1 4 1 5 2 5 4 1 4 2 5 1 4 4 4 5 3 4 2 1 3 2 2 2 3 1 2 2 1 2 2 Note In the first test case, it is possible to make only one operation with cells (1, 1), (2, 1), (2, 2). After that, all symbols will be equal to 0. In the second test case: * operation with cells (2, 1), (3, 1), (3, 2). After it the table will be: 011 001 000 * operation with cells (1, 2), (1, 3), (2, 3). After it the table will be: 000 000 000 In the fifth test case: * operation with cells (1, 3), (2, 2), (2, 3). After it the table will be: 010 110 * operation with cells (1, 2), (2, 1), (2, 2). After it the table will be: 000 000
def ans(i,j): x=i+1 if i<n else i-1 y=j+1 if j<m else j-1 print(i,j,i,y,x,y) print(i,j,x,j,x,y) print(i,j,i,y,x,j) for _ in range(int(input())): n,m=map(int,input().split()) l=[list(map(int,list(input()))) for i in range(n)] print(sum(sum(z) for z in l)*3) for i in range(n): for j in range(m): if l[i][j]==1: ans(i+1,j+1)
{ "input": [ "5\n2 2\n10\n11\n3 3\n011\n101\n110\n4 4\n1111\n0110\n0110\n1111\n5 5\n01011\n11001\n00010\n11011\n10000\n2 3\n011\n101\n" ], "output": [ "1\n1 1 2 1 2 2 \n6\n1 1 1 2 2 2 \n1 1 2 1 2 2 \n1 2 1 3 2 2 \n1 2 2 2 2 3 \n2 1 2 2 3 1 \n2 1 2 2 3 2 \n20\n1 1 1 2 2 2 \n1 2 1 3 2 2 \n1 2 2 2 2 3 \n1 3 1 4 2 3 \n1 3 1 4 2 4 \n1 4 2 3 2 4 \n2 1 2 2 3 2 \n2 1 3 1 3 2 \n2 2 3 1 3 2 \n2 2 2 3 3 3 \n2 2 3 2 3 3 \n2 3 3 2 3 3 \n3 1 3 2 4 1 \n3 1 3 2 4 2 \n3 2 3 3 4 3 \n3 2 4 2 4 3 \n3 3 4 2 4 3 \n3 3 3 4 4 4 \n3 3 4 3 4 4 \n3 4 4 3 4 4 \n20\n1 2 2 1 2 2 \n1 3 1 4 2 3 \n1 3 1 4 2 4 \n1 4 2 3 2 4 \n1 4 1 5 2 4 \n1 4 2 4 2 5 \n2 3 2 4 3 4 \n2 3 3 3 3 4 \n2 4 3 3 3 4 \n3 1 3 2 4 1 \n3 1 3 2 4 2 \n3 3 3 4 4 4 \n3 3 4 3 4 4 \n3 4 4 3 4 4 \n3 4 3 5 4 5 \n3 4 4 4 4 5 \n3 5 4 4 4 5 \n4 1 4 2 5 1 \n4 1 5 1 5 2 \n4 2 5 1 5 2 \n4\n1 1 1 2 2 2 \n1 1 2 1 2 2 \n1 2 1 3 2 2 \n1 2 2 2 2 3 \n" ] }
3,751
7
Polycarp calls an array dense if the greater of any two adjacent elements is not more than twice bigger than the smaller. More formally, for any i (1 ≀ i ≀ n-1), this condition must be satisfied: $$$(max(a[i], a[i+1]))/(min(a[i], a[i+1])) ≀ 2$$$ For example, the arrays [1, 2, 3, 4, 3], [1, 1, 1] and [5, 10] are dense. And the arrays [5, 11], [1, 4, 2], [6, 6, 1] are not dense. You are given an array a of n integers. What is the minimum number of numbers you need to add to an array to make it dense? You can insert numbers anywhere in the array. If the array is already dense, no numbers need to be added. For example, if a=[4,2,10,1], then the answer is 5, and the array itself after inserting elements into it may look like this: a=[4,2,\underline{3},\underline{5},10,\underline{6},\underline{4},\underline{2},1] (there are other ways to build such a). Input The first line contains one integer t (1 ≀ t ≀ 1000). Then t test cases follow. The first line of each test case contains one integer n (2 ≀ n ≀ 50) β€” the length of the array a. The next line contains n integers a_1, a_2, …, a_n (1 ≀ a_i ≀ 50). Output For each test case, output one integer β€” the minimum number of numbers that must be added to the array to make it dense. Example Input 6 4 4 2 10 1 2 1 3 2 6 1 3 1 4 2 5 1 2 3 4 3 12 4 31 25 50 30 20 34 46 42 16 15 16 Output 5 1 2 1 0 3 Note The first test case is explained in the statements. In the second test case, you can insert one element, a=[1,\underline{2},3]. In the third test case, you can insert two elements, a=[6,\underline{4},\underline{2},1]. In the fourth test case, you can insert one element, a=[1,\underline{2},4,2]. In the fifth test case, the array a is already dense.
def count1(arr,n): c=0 for i in range(n-1): a=max(arr[i],arr[i+1]) b=min(arr[i],arr[i+1]) if (a/b)>2: temp=b while (a/temp)>2: c=c+1 temp=temp*2 return c t=int(input()) for i in range(t): n=int(input()) arr=list(map(int,input().split())) print(count1(arr,n))
{ "input": [ "6\n4\n4 2 10 1\n2\n1 3\n2\n6 1\n3\n1 4 2\n5\n1 2 3 4 3\n12\n4 31 25 50 30 20 34 46 42 16 15 16\n" ], "output": [ "\n5\n1\n2\n1\n0\n3\n" ] }
3,752
10
You are given a number n and an array b_1, b_2, …, b_{n+2}, obtained according to the following algorithm: * some array a_1, a_2, …, a_n was guessed; * array a was written to array b, i.e. b_i = a_i (1 ≀ i ≀ n); * The (n+1)-th element of the array b is the sum of the numbers in the array a, i.e. b_{n+1} = a_1+a_2+…+a_n; * The (n+2)-th element of the array b was written some number x (1 ≀ x ≀ 10^9), i.e. b_{n+2} = x; The * array b was shuffled. For example, the array b=[2, 3, 7, 12 ,2] it could be obtained in the following ways: * a=[2, 2, 3] and x=12; * a=[3, 2, 7] and x=2. For the given array b, find any array a that could have been guessed initially. Input The first line contains a single integer t (1 ≀ t ≀ 10^4). Then t test cases follow. The first line of each test case contains a single integer n (1 ≀ n ≀ 2 β‹… 10^5). The second row of each test case contains n+2 integers b_1, b_2, …, b_{n+2} (1 ≀ b_i ≀ 10^9). It is guaranteed that the sum of n over all test cases does not exceed 2 β‹… 10^5. Output For each test case, output: * "-1", if the array b could not be obtained from any array a; * n integers a_1, a_2, …, a_n, otherwise. If there are several arrays of a, you can output any. Example Input 4 3 2 3 7 12 2 4 9 1 7 1 6 5 5 18 2 2 3 2 9 2 3 2 6 9 2 1 Output 2 3 7 -1 2 2 2 3 9 1 2 6
from collections import Counter t = int(input()) def solve(b): total = sum(b) c = Counter(b) for x in b: c.subtract([x]) if (total - x ) & 1 == 0 and c[(total-x) >> 1] > 0: c.subtract([(total-x) >> 1]) return list(c.elements()) c.update([x]) return [] for _ in range(t): n = int(input()) b = list(map(int, input().split())) ans = solve(b) if len(ans) > 0 : print(*ans, sep=' ') else: print(-1)
{ "input": [ "4\n3\n2 3 7 12 2\n4\n9 1 7 1 6 5\n5\n18 2 2 3 2 9 2\n3\n2 6 9 2 1\n" ], "output": [ "\n2 3 7 \n-1\n2 2 2 3 9 \n1 2 6 \n" ] }
3,753
11
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≀ n ≀ 107) β€” the required length of the cyclic path. Output Print the only integer β€” the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
n = int(input()) def a(n): p,q=0,3 if n==1: return 0 for i in range(n-2): p,q = q, (2*q+3*p) % 1000000007 return q print(a(n))
{ "input": [ "2\n", "4\n" ], "output": [ "3\n", "21\n" ] }
3,754
10
Vasya, like many others, likes to participate in a variety of sweepstakes and lotteries. Now he collects wrappings from a famous chocolate bar "Jupiter". According to the sweepstake rules, each wrapping has an integer written on it β€” the number of points that the participant adds to his score as he buys the bar. After a participant earns a certain number of points, he can come to the prize distribution center and exchange the points for prizes. When somebody takes a prize, the prize's cost is simply subtracted from the number of his points. Vasya didn't only bought the bars, he also kept a record of how many points each wrapping cost. Also, he remembers that he always stucks to the greedy strategy β€” as soon as he could take at least one prize, he went to the prize distribution centre and exchanged the points for prizes. Moreover, if he could choose between multiple prizes, he chose the most expensive one. If after an exchange Vasya had enough points left to get at least one more prize, then he continued to exchange points. The sweepstake has the following prizes (the prizes are sorted by increasing of their cost): * a mug (costs a points), * a towel (costs b points), * a bag (costs c points), * a bicycle (costs d points), * a car (costs e points). Now Vasya wants to recollect what prizes he has received. You know sequence p1, p2, ..., pn, where pi is the number of points Vasya got for the i-th bar. The sequence of points is given in the chronological order. You also know numbers a, b, c, d, e. Your task is to find, how many prizes Vasya received, what prizes they are and how many points he's got left after all operations are completed. Input The first line contains a single integer n (1 ≀ n ≀ 50) β€” the number of chocolate bar wrappings that brought points to Vasya. The second line contains space-separated integers p1, p2, ..., pn (1 ≀ pi ≀ 109). The third line contains 5 integers a, b, c, d, e (1 ≀ a < b < c < d < e ≀ 109) β€” the prizes' costs. Output Print on the first line 5 integers, separated by a space β€” the number of mugs, towels, bags, bicycles and cars that Vasya has got, respectively. On the second line print a single integer β€” the number of points Vasya will have left after all operations of exchange are completed. Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 3 10 4 2 4 10 15 20 Output 1 1 1 0 0 1 Input 4 10 4 39 2 3 5 10 11 12 Output 3 0 1 0 3 0 Note In the first sample Vasya gets 3 points after eating the first chocolate bar. Then he exchanges 2 points and gets a mug. Vasya wins a bag after eating the second chocolate bar. Then he wins a towel after eating the third chocolate bar. After all chocolate bars 3 - 2 + 10 - 10 + 4 - 4 = 1 points remains.
def readln(inp=None): return tuple(map(int, (inp or input()).split())) n, = readln() p = readln() abcde = readln() ans = [0] * 5 cur = 0 for c in p: cur += c for i in range(4, -1, -1): ans[i] += cur // abcde[i] cur %= abcde[i] print(*ans) print(cur)
{ "input": [ "4\n10 4 39 2\n3 5 10 11 12\n", "3\n3 10 4\n2 4 10 15 20\n" ], "output": [ "3 0 1 0 3\n0\n", "1 1 1 0 0\n1\n" ] }
3,755
7
Bob is preparing to pass IQ test. The most frequent task in this test is to find out which one of the given n numbers differs from the others. Bob observed that one number usually differs from the others in evenness. Help Bob β€” to check his answers, he needs a program that among the given n numbers finds one that is different in evenness. Input The first line contains integer n (3 ≀ n ≀ 100) β€” amount of numbers in the task. The second line contains n space-separated natural numbers, not exceeding 100. It is guaranteed, that exactly one of these numbers differs from the others in evenness. Output Output index of number that differs from the others in evenness. Numbers are numbered from 1 in the input order. Examples Input 5 2 4 7 8 10 Output 3 Input 4 1 2 1 1 Output 2
def p(x): return int(x)%2 input();*l,=map(p,input().split()) print((l.index(0)if sum(l)-1 else l.index(1))+1)
{ "input": [ "4\n1 2 1 1\n", "5\n2 4 7 8 10\n" ], "output": [ "2\n", "3\n" ] }
3,756
7
Bessie and the cows are playing with sequences and need your help. They start with a sequence, initially containing just the number 0, and perform n operations. Each operation is one of the following: 1. Add the integer xi to the first ai elements of the sequence. 2. Append an integer ki to the end of the sequence. (And hence the size of the sequence increases by 1) 3. Remove the last element of the sequence. So, the size of the sequence decreases by one. Note, that this operation can only be done if there are at least two elements in the sequence. After each operation, the cows would like to know the average of all the numbers in the sequence. Help them! Input The first line contains a single integer n (1 ≀ n ≀ 2Β·105) β€” the number of operations. The next n lines describe the operations. Each line will start with an integer ti (1 ≀ ti ≀ 3), denoting the type of the operation (see above). If ti = 1, it will be followed by two integers ai, xi (|xi| ≀ 103; 1 ≀ ai). If ti = 2, it will be followed by a single integer ki (|ki| ≀ 103). If ti = 3, it will not be followed by anything. It is guaranteed that all operations are correct (don't touch nonexistent elements) and that there will always be at least one element in the sequence. Output Output n lines each containing the average of the numbers in the sequence after the corresponding operation. The answer will be considered correct if its absolute or relative error doesn't exceed 10 - 6. Examples Input 5 2 1 3 2 3 2 1 3 Output 0.500000 0.000000 1.500000 1.333333 1.500000 Input 6 2 1 1 2 20 2 2 1 2 -3 3 3 Output 0.500000 20.500000 14.333333 12.333333 17.500000 17.000000 Note In the second sample, the sequence becomes <image>
import sys def get_array(): return list(map(int, sys.stdin.readline().strip().split())) n=int(input()) l=[0] dp=[0] s=0 c=1 while n: #print(l) t=get_array() if t[0]==2: l.append(t[1]) dp.append(0) s+=t[1] c+=1 print(s/c) elif t[0]==3: s-=(l[-1]+dp[-1]) dp[-2]+=dp[-1] l.pop() dp.pop() c-=1 print(s/c) else: dp[t[1]-1]+=t[2] s+=t[1]*t[2] print(s/c) n-=1 #r=s/c #r="{0:.6f}".format(r) #print(r)
{ "input": [ "6\n2 1\n1 2 20\n2 2\n1 2 -3\n3\n3\n", "5\n2 1\n3\n2 3\n2 1\n3\n" ], "output": [ "0.500000\n20.500000\n14.333333\n12.333333\n17.500000\n17.000000\n", "0.500000\n0.000000\n1.500000\n1.333333\n1.500000\n" ] }
3,757
11
Two people play the following string game. Initially the players have got some string s. The players move in turns, the player who cannot make a move loses. Before the game began, the string is written on a piece of paper, one letter per cell. <image> An example of the initial situation at s = "abacaba" A player's move is the sequence of actions: 1. The player chooses one of the available pieces of paper with some string written on it. Let's denote it is t. Note that initially, only one piece of paper is available. 2. The player chooses in the string t = t1t2... t|t| character in position i (1 ≀ i ≀ |t|) such that for some positive integer l (0 < i - l; i + l ≀ |t|) the following equations hold: ti - 1 = ti + 1, ti - 2 = ti + 2, ..., ti - l = ti + l. 3. Player cuts the cell with the chosen character. As a result of the operation, he gets three new pieces of paper, the first one will contain string t1t2... ti - 1, the second one will contain a string consisting of a single character ti, the third one contains string ti + 1ti + 2... t|t|. <image> An example of making action (i = 4) with string s = Β«abacabaΒ» Your task is to determine the winner provided that both players play optimally well. If the first player wins, find the position of character that is optimal to cut in his first move. If there are multiple positions, print the minimal possible one. Input The first line contains string s (1 ≀ |s| ≀ 5000). It is guaranteed that string s only contains lowercase English letters. Output If the second player wins, print in the single line "Second" (without the quotes). Otherwise, print in the first line "First" (without the quotes), and in the second line print the minimal possible winning move β€” integer i (1 ≀ i ≀ |s|). Examples Input abacaba Output First 2 Input abcde Output Second Note In the first sample the first player has multiple winning moves. But the minimum one is to cut the character in position 2. In the second sample the first player has no available moves.
U = input() memo = {} DP = [0]*(len(U)+1) DP[0] = 0 for j in range(1, len(U) + 1): s = set() for i in range(j): s.add(DP[max(0, i - 1)] ^ DP[max(0, j - i - 2)]) mex = 0 while mex in s: mex += 1 DP[j] = mex memo2 = {} def Grundy(S): """ Basically we transform the game. From a game where we can pick only center of palindrom to a game with several pile where we can pick anything (but it removes adjacent stone) In this new game, only the remaining size matters (since we can pick anywhere) """ if S in memo2: return memo2[S] total = 0 consec = 0 for i in range(1, len(S) - 1): if S[i - 1] == S[i + 1]: consec += 1 else: total ^= DP[consec] consec = 0 total ^= DP[consec] memo2[S] = total return total import sys sys.setrecursionlimit(3000) if (Grundy(U) != 0): #print(Grundy(U)) for i in range(1, len(U) - 1): if U[i - 1] == U[i + 1]: if ((Grundy(U[:i]) ^ Grundy(U[i + 1:])) == 0): print("First") print(i + 1) break else: print("Second")
{ "input": [ "abcde\n", "abacaba\n" ], "output": [ "Second\n", "First\n2\n" ] }
3,758
9
Yet another Armageddon is coming! This time the culprit is the Julya tribe calendar. The beavers in this tribe knew math very well. Smart Beaver, an archaeologist, got a sacred plate with a magic integer on it. The translation from Old Beaverish is as follows: "May the Great Beaver bless you! May your chacres open and may your third eye never turn blind from beholding the Truth! Take the magic number, subtract a digit from it (the digit must occur in the number) and get a new magic number. Repeat this operation until a magic number equals zero. The Earth will stand on Three Beavers for the time, equal to the number of subtractions you perform!" Distinct subtraction sequences can obviously get you different number of operations. But the Smart Beaver is ready to face the worst and is asking you to count the minimum number of operations he needs to reduce the magic number to zero. Input The single line contains the magic integer n, 0 ≀ n. * to get 20 points, you need to solve the problem with constraints: n ≀ 106 (subproblem C1); * to get 40 points, you need to solve the problem with constraints: n ≀ 1012 (subproblems C1+C2); * to get 100 points, you need to solve the problem with constraints: n ≀ 1018 (subproblems C1+C2+C3). Output Print a single integer β€” the minimum number of subtractions that turns the magic number to a zero. Examples Input 24 Output 5 Note In the first test sample the minimum number of operations can be reached by the following sequence of subtractions: 24 β†’ 20 β†’ 18 β†’ 10 β†’ 9 β†’ 0
c = '0123456789' F = {c[a] + c[b]: (c[10 - a + b], 1) if a > b else (c[10 - a], 2) for a in range(1, 10) for b in range(10)} for b in range(1, 10): F['0' + c[b]] = ('0', 1) F['00'] = ('0', 0) def f(x): global F if x in F: return F[x] a, b, y, s = int(x[0]), int(x[1]), x[2: ], 0 for i in range(b, a, -1): y, d = f(c[i] + y) s += d for i in range(min(a, b) + 1): y, d = f(x[0] + y) s += d F[x] = ('9' + y, s) return F[x] print(f('0' + input())[1])
{ "input": [ "24\n" ], "output": [ " 5\n" ] }
3,759
10
There are n schoolchildren, boys and girls, lined up in the school canteen in front of the bun stall. The buns aren't ready yet and the line is undergoing some changes. Each second all boys that stand right in front of girls, simultaneously swap places with the girls (so that the girls could go closer to the beginning of the line). In other words, if at some time the i-th position has a boy and the (i + 1)-th position has a girl, then in a second, the i-th position will have a girl and the (i + 1)-th one will have a boy. Let's take an example of a line of four people: a boy, a boy, a girl, a girl (from the beginning to the end of the line). Next second the line will look like that: a boy, a girl, a boy, a girl. Next second it will be a girl, a boy, a girl, a boy. Next second it will be a girl, a girl, a boy, a boy. The line won't change any more. Your task is: given the arrangement of the children in the line to determine the time needed to move all girls in front of boys (in the example above it takes 3 seconds). Baking buns takes a lot of time, so no one leaves the line until the line stops changing. Input The first line contains a sequence of letters without spaces s1s2... sn (1 ≀ n ≀ 106), consisting of capital English letters M and F. If letter si equals M, that means that initially, the line had a boy on the i-th position. If letter si equals F, then initially the line had a girl on the i-th position. Output Print a single integer β€” the number of seconds needed to move all the girls in the line in front of the boys. If the line has only boys or only girls, print 0. Examples Input MFM Output 1 Input MMFF Output 3 Input FFMMM Output 0 Note In the first test case the sequence of changes looks as follows: MFM β†’ FMM. The second test sample corresponds to the sample from the statement. The sequence of changes is: MMFF β†’ MFMF β†’ FMFM β†’ FFMM.
#------------------------template--------------------------# import os import sys from math import * from collections import * # from fractions import * from heapq import* from bisect import * from io import BytesIO, IOBase def vsInput(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') 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.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ALPHA='abcdefghijklmnopqrstuvwxyz' M = 10**9 + 7 EPS = 1e-6 def Ceil(a,b): return a//b+int(a%b>0) def value():return tuple(map(int,input().split())) def array():return [int(i) for i in input().split()] def Int():return int(input()) def Str():return input() def arrayS():return [i for i in input().split()] #-------------------------code---------------------------# # vsInput() s = input().lstrip('F') n = len(s) prev = 0 need = 0 steps = 0 for i in range(n): if(s[i] == 'F'): steps = max(steps+1,prev) else: prev += 1 print(steps)
{ "input": [ "MFM\n", "FFMMM\n", "MMFF\n" ], "output": [ "1", "0", "3" ] }
3,760
8
Petya works as a PR manager for a successful Berland company BerSoft. He needs to prepare a presentation on the company income growth since 2001 (the year of its founding) till now. Petya knows that in 2001 the company income amounted to a1 billion bourles, in 2002 β€” to a2 billion, ..., and in the current (2000 + n)-th year β€” an billion bourles. On the base of the information Petya decided to show in his presentation the linear progress history which is in his opinion perfect. According to a graph Petya has already made, in the first year BerSoft company income must amount to 1 billion bourles, in the second year β€” 2 billion bourles etc., each following year the income increases by 1 billion bourles. Unfortunately, the real numbers are different from the perfect ones. Among the numbers ai can even occur negative ones that are a sign of the company’s losses in some years. That is why Petya wants to ignore some data, in other words, cross some numbers ai from the sequence and leave only some subsequence that has perfect growth. Thus Petya has to choose a sequence of years y1, y2, ..., yk,so that in the year y1 the company income amounted to 1 billion bourles, in the year y2 β€” 2 billion bourles etc., in accordance with the perfect growth dynamics. Help him to choose the longest such sequence. Input The first line contains an integer n (1 ≀ n ≀ 100). The next line contains n integers ai ( - 100 ≀ ai ≀ 100). The number ai determines the income of BerSoft company in the (2000 + i)-th year. The numbers in the line are separated by spaces. Output Output k β€” the maximum possible length of a perfect sequence. In the next line output the sequence of years y1, y2, ..., yk. Separate the numbers by spaces. If the answer is not unique, output any. If no solution exist, output one number 0. Examples Input 10 -2 1 1 3 2 3 4 -10 -2 5 Output 5 2002 2005 2006 2007 2010 Input 3 -1 -2 -3 Output 0
def main(): d = input() vals = [int(v) for v in input().split()] cur = 0 s = 1 res = [] for i, c in enumerate(vals): if c == s: s+=1 res.append(2001+i) print(len(res)) print(" ".join([str(r) for r in res])) if __name__ == "__main__": main()
{ "input": [ "10\n-2 1 1 3 2 3 4 -10 -2 5\n", "3\n-1 -2 -3\n" ], "output": [ "5\n2002 2005 2006 2007 2010 ", "0\n" ] }
3,761
9
People in the Tomskaya region like magic formulas very much. You can see some of them below. Imagine you are given a sequence of positive integer numbers p1, p2, ..., pn. Lets write down some magic formulas: <image><image> Here, "mod" means the operation of taking the residue after dividing. The expression <image> means applying the bitwise xor (excluding "OR") operation to integers x and y. The given operation exists in all modern programming languages. For example, in languages C++ and Java it is represented by "^", in Pascal β€” by "xor". People in the Tomskaya region like magic formulas very much, but they don't like to calculate them! Therefore you are given the sequence p, calculate the value of Q. Input The first line of the input contains the only integer n (1 ≀ n ≀ 106). The next line contains n integers: p1, p2, ..., pn (0 ≀ pi ≀ 2Β·109). Output The only line of output should contain a single integer β€” the value of Q. Examples Input 3 1 2 3 Output 3
def getXorSuffix(i, n, xor): res = 0 if (n//(i+1)) % 2 == 0 else xor[i] return res^xor[n%(i+1)] n = int(input()) p = [int(x) for x in input().split()] xor = [0 for i in range(n+1)] for i in range(1, n+1): xor[i] = i^xor[i-1] ans = 0 for i in range(len(p)): ans ^= p[i]^getXorSuffix(i,n,xor) print(ans)
{ "input": [ "3\n1 2 3\n" ], "output": [ "3" ] }
3,762
7
Jzzhu has a big rectangular chocolate bar that consists of n Γ— m unit squares. He wants to cut this bar exactly k times. Each cut must meet the following requirements: * each cut should be straight (horizontal or vertical); * each cut should go along edges of unit squares (it is prohibited to divide any unit chocolate square with cut); * each cut should go inside the whole chocolate bar, and all cuts must be distinct. The picture below shows a possible way to cut a 5 Γ— 6 chocolate for 5 times. <image> Imagine Jzzhu have made k cuts and the big chocolate is splitted into several pieces. Consider the smallest (by area) piece of the chocolate, Jzzhu wants this piece to be as large as possible. What is the maximum possible area of smallest piece he can get with exactly k cuts? The area of a chocolate piece is the number of unit squares in it. Input A single line contains three integers n, m, k (1 ≀ n, m ≀ 109; 1 ≀ k ≀ 2Β·109). Output Output a single integer representing the answer. If it is impossible to cut the big chocolate k times, print -1. Examples Input 3 4 1 Output 6 Input 6 4 2 Output 8 Input 2 3 4 Output -1 Note In the first sample, Jzzhu can cut the chocolate following the picture below: <image> In the second sample the optimal division looks like this: <image> In the third sample, it's impossible to cut a 2 Γ— 3 chocolate 4 times.
def cut(n,m,k): if k > m+n-2: return -1 if k < max(m,n): return max(n*(m//(k+1)), m*(n//(k+1))) return max(n//(k-m+2), m//(k-n+2)) n,m,k = map(int, input().split()) print(cut(n,m,k))
{ "input": [ "6 4 2\n", "2 3 4\n", "3 4 1\n" ], "output": [ "8\n", "-1\n", "6\n" ] }
3,763
9
Vasya follows a basketball game and marks the distances from which each team makes a throw. He knows that each successful throw has value of either 2 or 3 points. A throw is worth 2 points if the distance it was made from doesn't exceed some value of d meters, and a throw is worth 3 points if the distance is larger than d meters, where d is some non-negative integer. Vasya would like the advantage of the points scored by the first team (the points of the first team minus the points of the second team) to be maximum. For that he can mentally choose the value of d. Help him to do that. Input The first line contains integer n (1 ≀ n ≀ 2Β·105) β€” the number of throws of the first team. Then follow n integer numbers β€” the distances of throws ai (1 ≀ ai ≀ 2Β·109). Then follows number m (1 ≀ m ≀ 2Β·105) β€” the number of the throws of the second team. Then follow m integer numbers β€” the distances of throws of bi (1 ≀ bi ≀ 2Β·109). Output Print two numbers in the format a:b β€” the score that is possible considering the problem conditions where the result of subtraction a - b is maximum. If there are several such scores, find the one in which number a is maximum. Examples Input 3 1 2 3 2 5 6 Output 9:6 Input 5 6 7 8 9 10 5 1 2 3 4 5 Output 15:10
from itertools import chain from bisect import bisect_left as bisect def main(): n = int(input().strip()) aa = list(map(int, input().strip().split())) aa.sort() m = int(input().strip()) bb = list(map(int, input().strip().split())) bb.sort() res = [] dd = set(chain(aa, bb)) for d in chain(aa, bb): dd.add(d + 1) la = len(aa) * 3 lb = len(bb) * 3 for d in dd: a = la - bisect(aa, d) b = lb - bisect(bb, d) res.append((a - b, a)) b, a = max(res) print('{:n}:{:n}'.format(a, a - b)) main()
{ "input": [ "3\n1 2 3\n2\n5 6\n", "5\n6 7 8 9 10\n5\n1 2 3 4 5\n" ], "output": [ "9:6", "15:10" ] }
3,764
8
Little Tanya decided to present her dad a postcard on his Birthday. She has already created a message β€” string s of length n, consisting of uppercase and lowercase English letters. Tanya can't write yet, so she found a newspaper and decided to cut out the letters and glue them into the postcard to achieve string s. The newspaper contains string t, consisting of uppercase and lowercase English letters. We know that the length of string t greater or equal to the length of the string s. The newspaper may possibly have too few of some letters needed to make the text and too many of some other letters. That's why Tanya wants to cut some n letters out of the newspaper and make a message of length exactly n, so that it looked as much as possible like s. If the letter in some position has correct value and correct letter case (in the string s and in the string that Tanya will make), then she shouts joyfully "YAY!", and if the letter in the given position has only the correct value but it is in the wrong case, then the girl says "WHOOPS". Tanya wants to make such message that lets her shout "YAY!" as much as possible. If there are multiple ways to do this, then her second priority is to maximize the number of times she says "WHOOPS". Your task is to help Tanya make the message. Input The first line contains line s (1 ≀ |s| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text of Tanya's message. The second line contains line t (|s| ≀ |t| ≀ 2Β·105), consisting of uppercase and lowercase English letters β€” the text written in the newspaper. Here |a| means the length of the string a. Output Print two integers separated by a space: * the first number is the number of times Tanya shouts "YAY!" while making the message, * the second number is the number of times Tanya says "WHOOPS" while making the message. Examples Input AbC DCbA Output 3 0 Input ABC abc Output 0 3 Input abacaba AbaCaBA Output 3 4
from collections import Counter def rev(c): return str.upper(c) if str.islower(c) else str.lower(c) s = Counter(input()) t = Counter(input()) #print(s,t) y=0 o=0 for k in s: d = min(s[k],t[k]) s[k]-=d t[k]-=d y+=d for k in s: l = rev(k) d=min(s[k],t[l]) o+=d s[k]-=d t[l]-=d print(y,o)
{ "input": [ "ABC\nabc\n", "AbC\nDCbA\n", "abacaba\nAbaCaBA\n" ], "output": [ "0 3\n", "3 0\n", "3 4\n" ] }
3,765
8
A map of some object is a rectangular field consisting of n rows and n columns. Each cell is initially occupied by the sea but you can cover some some cells of the map with sand so that exactly k islands appear on the map. We will call a set of sand cells to be island if it is possible to get from each of them to each of them by moving only through sand cells and by moving from a cell only to a side-adjacent cell. The cells are called to be side-adjacent if they share a vertical or horizontal side. It is easy to see that islands do not share cells (otherwise they together form a bigger island). Find a way to cover some cells with sand so that exactly k islands appear on the n Γ— n map, or determine that no such way exists. Input The single line contains two positive integers n, k (1 ≀ n ≀ 100, 0 ≀ k ≀ n2) β€” the size of the map and the number of islands you should form. Output If the answer doesn't exist, print "NO" (without the quotes) in a single line. Otherwise, print "YES" in the first line. In the next n lines print the description of the map. Each of the lines of the description must consist only of characters 'S' and 'L', where 'S' is a cell that is occupied by the sea and 'L' is the cell covered with sand. The length of each line of the description must equal n. If there are multiple answers, you may print any of them. You should not maximize the sizes of islands. Examples Input 5 2 Output YES SSSSS LLLLL SSSSS LLLLL SSSSS Input 5 25 Output NO
def solve(n, k): if k > (n**2+1)//2: return 'NO' A = [['S' for _ in range(n)] for _ in range(n)] t = 0 for i in range(n): for j in range(n): if t >= k: break if (i+j) % 2 == 0: A[i][j] = 'L' t += 1 return 'YES\n' + '\n'.join(''.join(row) for row in A) def main(): n, k = map(int, input().split()) ans = solve(n, k) print(ans) main()
{ "input": [ "5 2\n", "5 25\n" ], "output": [ "YES\nLSLSS\nSSSSS\nSSSSS\nSSSSS\nSSSSS\n", "NO" ] }
3,766
8
Ari the monster always wakes up very early with the first ray of the sun and the first thing she does is feeding her squirrel. Ari draws a regular convex polygon on the floor and numbers it's vertices 1, 2, ..., n in clockwise order. Then starting from the vertex 1 she draws a ray in the direction of each other vertex. The ray stops when it reaches a vertex or intersects with another ray drawn before. Ari repeats this process for vertex 2, 3, ..., n (in this particular order). And then she puts a walnut in each region inside the polygon. <image> Ada the squirrel wants to collect all the walnuts, but she is not allowed to step on the lines drawn by Ari. That means Ada have to perform a small jump if she wants to go from one region to another. Ada can jump from one region P to another region Q if and only if P and Q share a side or a corner. Assuming that Ada starts from outside of the picture, what is the minimum number of jumps she has to perform in order to collect all the walnuts? Input The first and only line of the input contains a single integer n (3 ≀ n ≀ 54321) - the number of vertices of the regular polygon drawn by Ari. Output Print the minimum number of jumps Ada should make to collect all the walnuts. Note, that she doesn't need to leave the polygon after. Examples Input 5 Output 9 Input 3 Output 1 Note One of the possible solutions for the first sample is shown on the picture above.
def belochka(n): return (n - 2) ** 2 print(belochka(int(input())))
{ "input": [ "5\n", "3\n" ], "output": [ "9\n", "1\n" ] }
3,767
9
Robbers, who attacked the Gerda's cab, are very successful in covering from the kingdom police. To make the goal of catching them even harder, they use their own watches. First, as they know that kingdom police is bad at math, robbers use the positional numeral system with base 7. Second, they divide one day in n hours, and each hour in m minutes. Personal watches of each robber are divided in two parts: first of them has the smallest possible number of places that is necessary to display any integer from 0 to n - 1, while the second has the smallest possible number of places that is necessary to display any integer from 0 to m - 1. Finally, if some value of hours or minutes can be displayed using less number of places in base 7 than this watches have, the required number of zeroes is added at the beginning of notation. Note that to display number 0 section of the watches is required to have at least one place. Little robber wants to know the number of moments of time (particular values of hours and minutes), such that all digits displayed on the watches are distinct. Help her calculate this number. Input The first line of the input contains two integers, given in the decimal notation, n and m (1 ≀ n, m ≀ 109) β€” the number of hours in one day and the number of minutes in one hour, respectively. Output Print one integer in decimal notation β€” the number of different pairs of hour and minute, such that all digits displayed on the watches are distinct. Examples Input 2 3 Output 4 Input 8 2 Output 5 Note In the first sample, possible pairs are: (0: 1), (0: 2), (1: 0), (1: 2). In the second sample, possible pairs are: (02: 1), (03: 1), (04: 1), (05: 1), (06: 1).
from itertools import permutations n, m = map(int, input().split()) def l(x): r = x == 0 while x: r += 1 x //= 7 return r ans, ln, lm = 0, l(n - 1), l(m - 1) for s in permutations('0123456', ln + lm): s = ''.join(s) ans += int(s[:ln], 7) < n and int(s[ln:], 7) < m print(ans)
{ "input": [ "8 2\n", "2 3\n" ], "output": [ "5\n", "4\n" ] }
3,768
8
Vasya takes part in the orienteering competition. There are n checkpoints located along the line at coordinates x1, x2, ..., xn. Vasya starts at the point with coordinate a. His goal is to visit at least n - 1 checkpoint in order to finish the competition. Participant are allowed to visit checkpoints in arbitrary order. Vasya wants to pick such checkpoints and the order of visiting them that the total distance travelled is minimized. He asks you to calculate this minimum possible value. Input The first line of the input contains two integers n and a (1 ≀ n ≀ 100 000, - 1 000 000 ≀ a ≀ 1 000 000) β€” the number of checkpoints and Vasya's starting position respectively. The second line contains n integers x1, x2, ..., xn ( - 1 000 000 ≀ xi ≀ 1 000 000) β€” coordinates of the checkpoints. Output Print one integer β€” the minimum distance Vasya has to travel in order to visit at least n - 1 checkpoint. Examples Input 3 10 1 7 12 Output 7 Input 2 0 11 -10 Output 10 Input 5 0 0 0 1000 0 0 Output 0 Note In the first sample Vasya has to visit at least two checkpoints. The optimal way to achieve this is the walk to the third checkpoints (distance is 12 - 10 = 2) and then proceed to the second one (distance is 12 - 7 = 5). The total distance is equal to 2 + 5 = 7. In the second sample it's enough to visit only one checkpoint so Vasya should just walk to the point - 10.
def s(): [n,a] = list(map(int,input().split())) x = list(map(int,input().split())) x.sort() if n == 1: print(0) return print(min(x[-1]-x[1]+min(abs(x[-1]-a),abs(x[1]-a)),x[-2]-x[0]+min(abs(x[-2]-a),abs(x[0]-a)))) s()
{ "input": [ "3 10\n1 7 12\n", "5 0\n0 0 1000 0 0\n", "2 0\n11 -10\n" ], "output": [ "7\n", "0\n", "10\n" ] }
3,769
7
After Fox Ciel won an onsite round of a programming contest, she took a bus to return to her castle. The fee of the bus was 220 yen. She met Rabbit Hanako in the bus. They decided to play the following game because they got bored in the bus. * Initially, there is a pile that contains x 100-yen coins and y 10-yen coins. * They take turns alternatively. Ciel takes the first turn. * In each turn, they must take exactly 220 yen from the pile. In Ciel's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 100-yen coins. In Hanako's turn, if there are multiple ways to take 220 yen, she will choose the way that contains the maximal number of 10-yen coins. * If Ciel or Hanako can't take exactly 220 yen from the pile, she loses. Determine the winner of the game. Input The first line contains two integers x (0 ≀ x ≀ 106) and y (0 ≀ y ≀ 106), separated by a single space. Output If Ciel wins, print "Ciel". Otherwise, print "Hanako". Examples Input 2 2 Output Ciel Input 3 22 Output Hanako Note In the first turn (Ciel's turn), she will choose 2 100-yen coins and 2 10-yen coins. In the second turn (Hanako's turn), she will choose 1 100-yen coin and 12 10-yen coins. In the third turn (Ciel's turn), she can't pay exactly 220 yen, so Ciel will lose.
def f(a, b): k = min(a, 2) return a - k, b - 22 + 10 * k def g(a, b): if b > 21: return a, b - 22 if b > 11: return a - 1, b - 12 return a - 2, b - 2 def main(): a, b = map(int, input().split()) k = min(a // 2, b // 24) a -= 2 * k b -= 24 * k while a > 0: a, b = f(a, b) if a < 0 or b < 0: return 0 a, b = g(a, b) if a < 0 or b < 0: return 1 if a == 0: return (b // 22) % 2 print(['Hanako', 'Ciel'][main()])
{ "input": [ "2 2\n", "3 22\n" ], "output": [ "Ciel", "Hanako" ] }
3,770
9
After the educational reform Polycarp studies only two subjects at school, Safety Studies and PE (Physical Education). During the long months of the fourth term, he received n marks in them. When teachers wrote a mark in the journal, they didn't write in what subject the mark was for, they just wrote the mark. Now it's time to show the journal to his strict parents. Polycarp knows that recently at the Parent Meeting the parents were told that he received a Safety Studies marks and b PE marks (a + b = n). Now Polycarp wants to write a subject's name in front of each mark so that: * there are exactly a Safety Studies marks, * there are exactly b PE marks, * the total average score in both subjects is maximum. An average subject grade is the sum of all marks in it, divided by the number of them. Of course, the division is performed in real numbers without rounding up or down. Polycarp aims to maximize the x1 + x2, where x1 is the average score in the first subject (Safety Studies), and x2 is the average score in the second one (Physical Education). Input The first line contains an integer n (2 ≀ n ≀ 105), n is the number of marks in Polycarp's Journal. The second line contains two positive integers a, b (1 ≀ a, b ≀ n - 1, a + b = n). The third line contains a sequence of integers t1, t2, ..., tn (1 ≀ ti ≀ 5), they are Polycarp's marks. Output Print the sequence of integers f1, f2, ..., fn, where fi (1 ≀ fi ≀ 2) is the number of a subject to which the i-th mark should be attributed. If there are several possible solutions, then print such that the sequence f1, f2, ..., fn is the smallest lexicographically. The sequence p1, p2, ..., pn is lexicographically less than q1, q2, ..., qn if there exists such j (1 ≀ j ≀ n) that pi = qi for all 1 ≀ i < j, Π°nd pj < qj. Examples Input 5 3 2 4 4 5 4 4 Output 1 1 2 1 2 Input 4 2 2 3 5 4 5 Output 1 1 2 2 Input 6 1 5 4 4 4 5 4 4 Output 2 2 2 1 2 2 Note In the first sample the average score in the first subject is equal to 4, and in the second one β€” to 4.5. The total average score is 8.5.
import sys from math import * def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) n = mint() a, b = mints() t = list(mints()) c = [0]*n for i in range(n): c[i] = (t[i] if a != b else 0, -i if a<b else i) c.sort(reverse=a<b) f = [0]*n for i in range(a): f[abs(c[i][1])] = 1 for i in range(a,a+b): f[abs(c[i][1])] = 2 print(*f)
{ "input": [ "4\n2 2\n3 5 4 5\n", "5\n3 2\n4 4 5 4 4\n", "6\n1 5\n4 4 4 5 4 4\n" ], "output": [ "1 1 2 2\n", "1 1 2 1 2\n", "2 2 2 1 2 2\n" ] }
3,771
7
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 remember the number of flights you have made in either direction. However, for each of the last n days you know whether you were in San Francisco office or in Seattle office. You always fly at nights, so you never were at both offices on the same day. Given this information, determine if you flew more times from Seattle to San Francisco during the last n days, or not. Input The first line of input contains single integer n (2 ≀ n ≀ 100) β€” the number of days. The second line contains a string of length n consisting of only capital 'S' and 'F' letters. If the i-th letter is 'S', then you were in Seattle office on that day. Otherwise you were in San Francisco. The days are given in chronological order, i.e. today is the last day in this sequence. Output Print "YES" if you flew more times from Seattle to San Francisco, and "NO" otherwise. You can print each letter in any case (upper or lower). Examples Input 4 FSSF Output NO Input 2 SF Output YES Input 10 FFFFFFFFFF Output NO Input 10 SSFFSFFSFF Output YES Note In the first example you were initially at San Francisco, then flew to Seattle, were there for two days and returned to San Francisco. You made one flight in each direction, so the answer is "NO". In the second example you just flew from Seattle to San Francisco, so the answer is "YES". In the third example you stayed the whole period in San Francisco, so the answer is "NO". In the fourth example if you replace 'S' with ones, and 'F' with zeros, you'll get the first few digits of Ο€ in binary representation. Not very useful information though.
def main(): _ = input() s, *_, f = input() print(('NO', 'YES')[f < s]) if __name__ == '__main__': main()
{ "input": [ "10\nFFFFFFFFFF\n", "10\nSSFFSFFSFF\n", "4\nFSSF\n", "2\nSF\n" ], "output": [ "NO\n", "YES\n", "NO\n", "YES\n" ] }
3,772
9
You have an array a with length n, you can perform operations. Each operation is like this: choose two adjacent elements from a, say x and y, and replace one of them with gcd(x, y), where gcd denotes the [greatest common divisor](https://en.wikipedia.org/wiki/Greatest_common_divisor). What is the minimum number of operations you need to make all of the elements equal to 1? Input The first line of the input contains one integer n (1 ≀ n ≀ 2000) β€” the number of elements in the array. The second line contains n space separated integers a1, a2, ..., an (1 ≀ ai ≀ 109) β€” the elements of the array. Output Print -1, if it is impossible to turn all numbers to 1. Otherwise, print the minimum number of operations needed to make all numbers equal to 1. Examples Input 5 2 2 3 4 6 Output 5 Input 4 2 4 6 8 Output -1 Input 3 2 6 9 Output 4 Note In the first sample you can turn all numbers to 1 using the following 5 moves: * [2, 2, 3, 4, 6]. * [2, 1, 3, 4, 6] * [2, 1, 3, 1, 6] * [2, 1, 1, 1, 6] * [1, 1, 1, 1, 6] * [1, 1, 1, 1, 1] We can prove that in this case it is not possible to make all numbers one using less than 5 moves.
import math def slve(n,a): c1=a.count(1);ans=10**20 if c1>0:return n-c1 for i in range(n): g=a[i] for j in range(i+1,n): g=math.gcd(g,a[j]) if g==1:ans=min(ans,j-i) return -1 if ans==10**20 else n-1+ans n=int(input());a=list(map(int,input().split()));print(slve(n,a))
{ "input": [ "4\n2 4 6 8\n", "3\n2 6 9\n", "5\n2 2 3 4 6\n" ], "output": [ "-1\n", "4\n", "5\n" ] }
3,773
9
The Travelling Salesman spends a lot of time travelling so he tends to get bored. To pass time, he likes to perform operations on numbers. One such operation is to take a positive integer x and reduce it to the number of bits set to 1 in the binary representation of x. For example for number 13 it's true that 1310 = 11012, so it has 3 bits set and 13 will be reduced to 3 in one operation. He calls a number special if the minimum number of operations to reduce it to 1 is k. He wants to find out how many special numbers exist which are not greater than n. Please help the Travelling Salesman, as he is about to reach his destination! Since the answer can be large, output it modulo 109 + 7. Input The first line contains integer n (1 ≀ n < 21000). The second line contains integer k (0 ≀ k ≀ 1000). Note that n is given in its binary representation without any leading zeros. Output Output a single integer β€” the number of special numbers not greater than n, modulo 109 + 7. Examples Input 110 2 Output 3 Input 111111011 2 Output 169 Note In the first sample, the three special numbers are 3, 5 and 6. They get reduced to 2 in one operation (since there are two set bits in each of 3, 5 and 6) and then to 1 in one more operation (since there is only one set bit in 2).
def Numb(a,k): if a == 0: return 0 m = len(bin(a))-3 if m + 1 < k: return 0 if k == 1: return m+1 if m + 1 == k: return Numb(a & ((1<<m)-1), k-1) return C[m][k]+Numb(a & ((1<<m)-1), k-1) s = input() nDec = int(s,2) n = len(s) k = int(input()) C = [[1],[1,1]] for i in range(n): tmp = [1] for j in range(1,i+2): tmp.append(C[-1][j-1]+C[-1][j]) tmp.append(1) C.append(tmp) if k == 0: print(1) else: NumOfOp = [0 for i in range(n+1)] for i in range(2,n+1): NumOfOp[i] = NumOfOp[bin(i).count('1')] + 1 res = 0 for i in range(1,n+1): if NumOfOp[i] == k-1: res += Numb(nDec,i) if k == 1: res -= 1 print(res%(10**9+7))
{ "input": [ "110\n2\n", "111111011\n2\n" ], "output": [ "3\n", "169\n" ] }
3,774
7
The recent All-Berland Olympiad in Informatics featured n participants with each scoring a certain amount of points. As the head of the programming committee, you are to determine the set of participants to be awarded with diplomas with respect to the following criteria: * At least one participant should get a diploma. * None of those with score equal to zero should get awarded. * When someone is awarded, all participants with score not less than his score should also be awarded. Determine the number of ways to choose a subset of participants that will receive the diplomas. Input The first line contains a single integer n (1 ≀ n ≀ 100) β€” the number of participants. The next line contains a sequence of n integers a1, a2, ..., an (0 ≀ ai ≀ 600) β€” participants' scores. It's guaranteed that at least one participant has non-zero score. Output Print a single integer β€” the desired number of ways. Examples Input 4 1 3 3 2 Output 3 Input 3 1 1 1 Output 1 Input 4 42 0 0 42 Output 1 Note There are three ways to choose a subset in sample case one. 1. Only participants with 3 points will get diplomas. 2. Participants with 2 or 3 points will get diplomas. 3. Everyone will get a diploma! The only option in sample case two is to award everyone. Note that in sample case three participants with zero scores cannot get anything.
def answer(): n = int(input()) b = [int(x) for x in input().split() if int(x)>0] b = len(set(b)) print(b) answer()
{ "input": [ "4\n42 0 0 42\n", "4\n1 3 3 2\n", "3\n1 1 1\n" ], "output": [ "1\n", "3\n", "1\n" ] }
3,775
9
You are given a positive integer n, written without leading zeroes (for example, the number 04 is incorrect). In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros. Determine the minimum number of operations that you need to consistently apply to the given integer n to make from it the square of some positive integer or report that it is impossible. An integer x is the square of some positive integer if and only if x=y^2 for some positive integer y. Input The first line contains a single integer n (1 ≀ n ≀ 2 β‹… 10^{9}). The number is given without leading zeroes. Output If it is impossible to make the square of some positive integer from n, print -1. In the other case, print the minimal number of operations required to do it. Examples Input 8314 Output 2 Input 625 Output 0 Input 333 Output -1 Note In the first example we should delete from 8314 the digits 3 and 4. After that 8314 become equals to 81, which is the square of the integer 9. In the second example the given 625 is the square of the integer 25, so you should not delete anything. In the third example it is impossible to make the square from 333, so the answer is -1.
def f(s, i): if len(s) > 0 and s[0] != '0': ss = int(s) x = int(ss**0.5+0.5) if x*x == ss and x > 0: return 0 r = 1000 for j in range(i,len(s)): r = min(r, 1 + f(s[:j]+s[j+1:], j)) return r n = input() r = f(n,0) if r >= 1000: print(-1) else: print(r)
{ "input": [ "625\n", "333\n", "8314\n" ], "output": [ "0\n", "-1\n", "2\n" ] }
3,776
7
Sonya decided that having her own hotel business is the best way of earning money because she can profit and rest wherever she wants. The country where Sonya lives is an endless line. There is a city in each integer coordinate on this line. She has n hotels, where the i-th hotel is located in the city with coordinate x_i. Sonya is a smart girl, so she does not open two or more hotels in the same city. Sonya understands that her business needs to be expanded by opening new hotels, so she decides to build one more. She wants to make the minimum distance from this hotel to all others to be equal to d. The girl understands that there are many possible locations to construct such a hotel. Thus she wants to know the number of possible coordinates of the cities where she can build a new hotel. Because Sonya is lounging in a jacuzzi in one of her hotels, she is asking you to find the number of cities where she can build a new hotel so that the minimum distance from the original n hotels to the new one is equal to d. Input The first line contains two integers n and d (1≀ n≀ 100, 1≀ d≀ 10^9) β€” the number of Sonya's hotels and the needed minimum distance from a new hotel to all others. The second line contains n different integers in strictly increasing order x_1, x_2, …, x_n (-10^9≀ x_i≀ 10^9) β€” coordinates of Sonya's hotels. Output Print the number of cities where Sonya can build a new hotel so that the minimum distance from this hotel to all others is equal to d. Examples Input 4 3 -3 2 9 16 Output 6 Input 5 2 4 8 11 18 19 Output 5 Note In the first example, there are 6 possible cities where Sonya can build a hotel. These cities have coordinates -6, 5, 6, 12, 13, and 19. In the second example, there are 5 possible cities where Sonya can build a hotel. These cities have coordinates 2, 6, 13, 16, and 21.
def scanf(t=int): return list(map(t, input().split())) n, d = scanf() m = scanf() ans = sum([ 2 - (m[i] - m[i-1] == 2 * d) for i in range(1, n) if m[i] - m[i-1] >= 2 * d]) print(ans + 2)
{ "input": [ "5 2\n4 8 11 18 19\n", "4 3\n-3 2 9 16\n" ], "output": [ "5\n", "6\n" ] }
3,777
7
Consider a table of size n Γ— m, initially fully white. Rows are numbered 1 through n from top to bottom, columns 1 through m from left to right. Some square inside the table with odd side length was painted black. Find the center of this square. Input The first line contains two integers n and m (1 ≀ n, m ≀ 115) β€” the number of rows and the number of columns in the table. The i-th of the next n lines contains a string of m characters s_{i1} s_{i2} … s_{im} (s_{ij} is 'W' for white cells and 'B' for black cells), describing the i-th row of the table. Output Output two integers r and c (1 ≀ r ≀ n, 1 ≀ c ≀ m) separated by a space β€” the row and column numbers of the center of the black square. Examples Input 5 6 WWBBBW WWBBBW WWBBBW WWWWWW WWWWWW Output 2 4 Input 3 3 WWW BWW WWW Output 2 1
def main(): n, m = map(int, input().split()) for i in range(n): l = input().split('B') if len(l) > 1: print(i + len(l) // 2, len(l[0]) + len(l) // 2) break if __name__ == '__main__': main()
{ "input": [ "3 3\nWWW\nBWW\nWWW\n", "5 6\nWWBBBW\nWWBBBW\nWWBBBW\nWWWWWW\nWWWWWW\n" ], "output": [ "2 1\n", "2 4\n" ] }
3,778
12
Elections in Berland are coming. There are only two candidates β€” Alice and Bob. The main Berland TV channel plans to show political debates. There are n people who want to take part in the debate as a spectator. Each person is described by their influence and political views. There are four kinds of political views: * supporting none of candidates (this kind is denoted as "00"), * supporting Alice but not Bob (this kind is denoted as "10"), * supporting Bob but not Alice (this kind is denoted as "01"), * supporting both candidates (this kind is denoted as "11"). The direction of the TV channel wants to invite some of these people to the debate. The set of invited spectators should satisfy three conditions: * at least half of spectators support Alice (i.e. 2 β‹… a β‰₯ m, where a is number of spectators supporting Alice and m is the total number of spectators), * at least half of spectators support Bob (i.e. 2 β‹… b β‰₯ m, where b is number of spectators supporting Bob and m is the total number of spectators), * the total influence of spectators is maximal possible. Help the TV channel direction to select such non-empty set of spectators, or tell that this is impossible. Input The first line contains integer n (1 ≀ n ≀ 4β‹…10^5) β€” the number of people who want to take part in the debate as a spectator. These people are described on the next n lines. Each line describes a single person and contains the string s_i and integer a_i separated by space (1 ≀ a_i ≀ 5000), where s_i denotes person's political views (possible values β€” "00", "10", "01", "11") and a_i β€” the influence of the i-th person. Output Print a single integer β€” maximal possible total influence of a set of spectators so that at least half of them support Alice and at least half of them support Bob. If it is impossible print 0 instead. Examples Input 6 11 6 10 4 01 3 00 3 00 7 00 9 Output 22 Input 5 11 1 01 1 00 100 10 1 01 1 Output 103 Input 6 11 19 10 22 00 18 00 29 11 29 10 28 Output 105 Input 3 00 5000 00 5000 00 5000 Output 0 Note In the first example 4 spectators can be invited to maximize total influence: 1, 2, 3 and 6. Their political views are: "11", "10", "01" and "00". So in total 2 out of 4 spectators support Alice and 2 out of 4 spectators support Bob. The total influence is 6+4+3+9=22. In the second example the direction can select all the people except the 5-th person. In the third example the direction can select people with indices: 1, 4, 5 and 6. In the fourth example it is impossible to select any non-empty set of spectators.
import sys a = [] b = [] c = [] d = [] def main(): #sys.stdin = open('D:\\Sublime\\in.txt', 'r') #sys.stdout = open('D:\\Sublime\\out.txt', 'w') n = int(sys.stdin.readline().strip('\n')) for i in range(n): opt,num=[int(line) for line in sys.stdin.readline().strip('\n').split()[:2]] if opt==0: a.append(num) if opt==10: b.append(num) if opt==1: c.append(num) if opt==11: d.append(num) res = sum(d) b.sort(reverse = True) c.sort(reverse = True) if len(b) > len(c): res += sum(c) + sum(b[:len(c)]) a.extend(b[len(c):]) else: res += sum(b) + sum(c[:len(b)]) a.extend(c[len(b):]) a.sort(reverse = True) res += sum(a[:len(d)]) print(res) if __name__ == '__main__': main()
{ "input": [ "5\n11 1\n01 1\n00 100\n10 1\n01 1\n", "6\n11 6\n10 4\n01 3\n00 3\n00 7\n00 9\n", "3\n00 5000\n00 5000\n00 5000\n", "6\n11 19\n10 22\n00 18\n00 29\n11 29\n10 28\n" ], "output": [ "103\n", "22\n", "0\n", "105\n" ] }
3,779
8
There are n students in a university. The number of students is even. The i-th student has programming skill equal to a_i. The coach wants to form n/2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team). Students can solve problems to increase their skill. One solved problem increases the skill by one. The coach wants to know the minimum total number of problems students should solve to form exactly n/2 teams (i.e. each pair of students should form a team). Your task is to find this number. Input The first line of the input contains one integer n (2 ≀ n ≀ 100) β€” the number of students. It is guaranteed that n is even. The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≀ a_i ≀ 100), where a_i is the skill of the i-th student. Output Print one number β€” the minimum total number of problems students should solve to form exactly n/2 teams. Examples Input 6 5 10 2 3 14 5 Output 5 Input 2 1 100 Output 99 Note In the first example the optimal teams will be: (3, 4), (1, 6) and (2, 5), where numbers in brackets are indices of students. Then, to form the first team the third student should solve 1 problem, to form the second team nobody needs to solve problems and to form the third team the second student should solve 4 problems so the answer is 1 + 4 = 5. In the second example the first student should solve 99 problems to form a team with the second one.
def min_a(a): k = min(a) del(a[a.index(min(a))]) k = abs(k-min(a)) del(a[a.index(min(a))]) return k n = int(input()) a = list(map(int,input().split())) ans = 0 for i in range(n//2): ans += min_a(a) print(ans)
{ "input": [ "6\n5 10 2 3 14 5\n", "2\n1 100\n" ], "output": [ "5\n", "99\n" ] }
3,780
11
Let's denote that some array b is bad if it contains a subarray b_l, b_{l+1}, ..., b_{r} of odd length more than 1 (l < r and r - l + 1 is odd) such that βˆ€ i ∈ \{0, 1, ..., r - l\} b_{l + i} = b_{r - i}. If an array is not bad, it is good. Now you are given an array a_1, a_2, ..., a_n. Some elements are replaced by -1. Calculate the number of good arrays you can obtain by replacing each -1 with some integer from 1 to k. Since the answer can be large, print it modulo 998244353. Input The first line contains two integers n and k (2 ≀ n, k ≀ 2 β‹… 10^5) β€” the length of array a and the size of "alphabet", i. e., the upper bound on the numbers you may use to replace -1. The second line contains n integers a_1, a_2, ..., a_n (a_i = -1 or 1 ≀ a_i ≀ k) β€” the array a. Output Print one integer β€” the number of good arrays you can get, modulo 998244353. Examples Input 2 3 -1 -1 Output 9 Input 5 2 1 -1 -1 1 2 Output 0 Input 5 3 1 -1 -1 1 2 Output 2 Input 4 200000 -1 -1 12345 -1 Output 735945883
def solve1(a, l, r, k, mod): n = len(a) if l == 0 and r == n: return k * (k - 1) ** (n - 1) if l == 0 or r == n: return (k - 1) ** (r - l) x = a[l - 1] y = a[r] dp0 = [0] * (r - l) dp1 = [0] * (r - l) if x != y: dp0[0] = k - 2 dp1[0] = 1 else: dp0[0] = k - 1 dp1[0] = 0 for i in range(1, (r - l)): dp0[i] = dp0[i - 1] * (k - 2) + dp1[i - 1] * (k - 1) dp1[i] = dp0[i - 1] dp0[i]%=mod dp1[i]%=mod return dp0[-1] def solve(a, k, mod): n = len(a) res = 1 i = 0 while i < n: if i < n - 1 and a[i] != -1 and a[i] == a[i + 1]: return 0 if a[i] != -1: i += 1 continue j = i while j < n and a[i] == a[j]: j += 1 res *= solve1(a, i, j, k, mod) i = j return res n, k = map(int, (input().split())) src = list(map(int, (input().split()))) e = src[0::2] o = src[1::2] mod = 998244353 print(solve(e, k, mod) * solve(o, k, mod) % mod)
{ "input": [ "2 3\n-1 -1\n", "5 3\n1 -1 -1 1 2\n", "4 200000\n-1 -1 12345 -1\n", "5 2\n1 -1 -1 1 2\n" ], "output": [ "9\n", "2\n", "735945883\n", "0\n" ] }
3,781
9
n boys and m girls came to the party. Each boy presented each girl some integer number of sweets (possibly zero). All boys are numbered with integers from 1 to n and all girls are numbered with integers from 1 to m. For all 1 ≀ i ≀ n the minimal number of sweets, which i-th boy presented to some girl is equal to b_i and for all 1 ≀ j ≀ m the maximal number of sweets, which j-th girl received from some boy is equal to g_j. More formally, let a_{i,j} be the number of sweets which the i-th boy give to the j-th girl. Then b_i is equal exactly to the minimum among values a_{i,1}, a_{i,2}, …, a_{i,m} and g_j is equal exactly to the maximum among values b_{1,j}, b_{2,j}, …, b_{n,j}. You are interested in the minimum total number of sweets that boys could present, so you need to minimize the sum of a_{i,j} for all (i,j) such that 1 ≀ i ≀ n and 1 ≀ j ≀ m. You are given the numbers b_1, …, b_n and g_1, …, g_m, determine this number. Input The first line contains two integers n and m, separated with space β€” the number of boys and girls, respectively (2 ≀ n, m ≀ 100 000). The second line contains n integers b_1, …, b_n, separated by spaces β€” b_i is equal to the minimal number of sweets, which i-th boy presented to some girl (0 ≀ b_i ≀ 10^8). The third line contains m integers g_1, …, g_m, separated by spaces β€” g_j is equal to the maximal number of sweets, which j-th girl received from some boy (0 ≀ g_j ≀ 10^8). Output If the described situation is impossible, print -1. In another case, print the minimal total number of sweets, which boys could have presented and all conditions could have satisfied. Examples Input 3 2 1 2 1 3 4 Output 12 Input 2 2 0 1 1 0 Output -1 Input 2 3 1 0 1 1 2 Output 4 Note In the first test, the minimal total number of sweets, which boys could have presented is equal to 12. This can be possible, for example, if the first boy presented 1 and 4 sweets, the second boy presented 3 and 2 sweets and the third boy presented 1 and 1 sweets for the first and the second girl, respectively. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 12. In the second test, the boys couldn't have presented sweets in such way, that all statements satisfied. In the third test, the minimal total number of sweets, which boys could have presented is equal to 4. This can be possible, for example, if the first boy presented 1, 1, 2 sweets for the first, second, third girl, respectively and the second boy didn't present sweets for each girl. It's easy to see, that all conditions are satisfied and the total number of sweets is equal to 4.
def getn(): return int(input()) def getns(): return [int(x) for x in input().split()] n,m=getns() ns=getns() ms=getns() if max(ns)>min(ms): print(-1) quit() ans=sum(ns)*m if max(ns)==min(ms): ans+=sum(ms)-max(ns)*m print(ans) quit() ns.sort() ans+=sum(ms)-max(ns)*m ans+=ns[-1]-ns[-2] print(ans)
{ "input": [ "2 2\n0 1\n1 0\n", "2 3\n1 0\n1 1 2\n", "3 2\n1 2 1\n3 4\n" ], "output": [ "-1\n", "4\n", "12\n" ] }
3,782
9
Innokenty works at a flea market and sells some random stuff rare items. Recently he found an old rectangular blanket. It turned out that the blanket is split in n β‹… m colored pieces that form a rectangle with n rows and m columns. The colored pieces attracted Innokenty's attention so he immediately came up with the following business plan. If he cuts out a subrectangle consisting of three colored stripes, he can sell it as a flag of some country. Innokenty decided that a subrectangle is similar enough to a flag of some country if it consists of three stripes of equal heights placed one above another, where each stripe consists of cells of equal color. Of course, the color of the top stripe must be different from the color of the middle stripe; and the color of the middle stripe must be different from the color of the bottom stripe. Innokenty has not yet decided what part he will cut out, but he is sure that the flag's boundaries should go along grid lines. Also, Innokenty won't rotate the blanket. Please help Innokenty and count the number of different subrectangles Innokenty can cut out and sell as a flag. Two subrectangles located in different places but forming the same flag are still considered different. <image> <image> <image> These subrectangles are flags. <image> <image> <image> <image> <image> <image> These subrectangles are not flags. Input The first line contains two integers n and m (1 ≀ n, m ≀ 1 000) β€” the number of rows and the number of columns on the blanket. Each of the next n lines contains m lowercase English letters from 'a' to 'z' and describes a row of the blanket. Equal letters correspond to equal colors, different letters correspond to different colors. Output In the only line print the number of subrectangles which form valid flags. Examples Input 4 3 aaa bbb ccb ddd Output 6 Input 6 1 a a b b c c Output 1 Note <image> <image> The selected subrectangles are flags in the first example.
def countFlagNum(x): y = 0 flagNum = 0 while y < m: curColor = a[x][y] colorCountByX = 1 isItFlag = True while x + colorCountByX < n and a[x + colorCountByX][y] == curColor: colorCountByX += 1 if not(x + colorCountByX * 3 > n): color2 = a[x + colorCountByX][y] color3 = a[x + colorCountByX * 2][y] if color3 != color2 and color2 != curColor: offY = 0 while y + offY < m and isItFlag: i = 0 while i < colorCountByX and isItFlag: if (a[x + i][y + offY] != curColor or a[x + colorCountByX + i][y + offY] != color2 or a[x + colorCountByX * 2 + i][y + offY] != color3): isItFlag = False if offY == 0: offY = 1 i += 1 if isItFlag: flagNum = flagNum + 1 + offY offY += 1 y += offY - 1 y += 1 return flagNum n, m = map(int, input().split()) a = [] totalFlagNum = 0 for i in range(n): row = input() a.append(row) for i in range(n - 2): totalFlagNum += countFlagNum(i) print(totalFlagNum)
{ "input": [ "6 1\na\na\nb\nb\nc\nc\n", "4 3\naaa\nbbb\nccb\nddd\n" ], "output": [ "1\n", "6\n" ] }
3,783
12
You work as a system administrator in a dormitory, which has n rooms one after another along a straight hallway. Rooms are numbered from 1 to n. You have to connect all n rooms to the Internet. You can connect each room to the Internet directly, the cost of such connection for the i-th room is i coins. Some rooms also have a spot for a router. The cost of placing a router in the i-th room is also i coins. You cannot place a router in a room which does not have a spot for it. When you place a router in the room i, you connect all rooms with the numbers from max(1,~i - k) to min(n,~i + k) inclusive to the Internet, where k is the range of router. The value of k is the same for all routers. Calculate the minimum total cost of connecting all n rooms to the Internet. You can assume that the number of rooms which have a spot for a router is not greater than the number of routers you have. Input The first line of the input contains two integers n and k (1 ≀ n, k ≀ 2 β‹… 10^5) β€” the number of rooms and the range of each router. The second line of the input contains one string s of length n, consisting only of zeros and ones. If the i-th character of the string equals to '1' then there is a spot for a router in the i-th room. If the i-th character of the string equals to '0' then you cannot place a router in the i-th room. Output Print one integer β€” the minimum total cost of connecting all n rooms to the Internet. Examples Input 5 2 00100 Output 3 Input 6 1 000000 Output 21 Input 4 1 0011 Output 4 Input 12 6 000010000100 Output 15 Note In the first example it is enough to place the router in the room 3, then all rooms will be connected to the Internet. The total cost of connection is 3. In the second example you can place routers nowhere, so you need to connect all rooms directly. Thus, the total cost of connection of all rooms is 1 + 2 + 3 + 4 + 5 + 6 = 21. In the third example you need to connect the room 1 directly and place the router in the room 3. Thus, the total cost of connection of all rooms is 1 + 3 = 4. In the fourth example you need to place routers in rooms 5 and 10. Then all rooms will be connected to the Internet. The total cost of connection is 5 + 10 = 15.
def get(n,k,s): nxt=[0]*(n+1) cur=1<<30 for i in range(n,0,-1): if s[i-1]=='1': cur=i nxt[i]=cur dp=[0] for i in range(1,n+1): dp.append(dp[-1]+i) c=nxt[max(i-k,1)] if c<=i+k: dp[i]=min(dp[i],dp[max(1,c-k)-1]+c) return dp[n] n,k=map(int,input().split()) s=input() print(get(n,k,s))
{ "input": [ "5 2\n00100\n", "4 1\n0011\n", "12 6\n000010000100\n", "6 1\n000000\n" ], "output": [ "3\n", "4\n", "15\n", "21\n" ] }
3,784
8
You are given an infinite checkered field. You should get from a square (x1; y1) to a square (x2; y2). Using the shortest path is not necessary. You can move on the field squares in four directions. That is, when you are positioned in any square, you can move to any other side-neighboring one. A square (x; y) is considered bad, if at least one of the two conditions is fulfilled: * |x + y| ≑ 0 (mod 2a), * |x - y| ≑ 0 (mod 2b). Your task is to find the minimum number of bad cells one will have to visit on the way from (x1; y1) to (x2; y2). Input The only line contains integers a, b, x1, y1, x2 and y2 β€” the parameters of the bad squares, the coordinates of the initial and the final squares correspondingly (2 ≀ a, b ≀ 109 and |x1|,|y1|,|x2|,|y2| ≀ 109). It is guaranteed that the initial and the final square aren't bad. Output Print a single number β€” the minimum number of bad cells that one will have to visit in order to travel from square (x1; y1) to square (x2; y2). Examples Input 2 2 1 0 0 1 Output 1 Input 2 2 10 11 0 1 Output 5 Input 2 4 3 -1 3 7 Output 2 Note In the third sample one of the possible paths in (3;-1)->(3;0)->(3;1)->(3;2)->(4;2)->(4;3)->(4;4)->(4;5)->(4;6)->(4;7)->(3;7). Squares (3;1) and (4;4) are bad.
#!/usr/bin/python3 def cds(a, b, x, y): return (x + y) // (2 * a), (x - y) // (2 * b) def norm(x, y): return max(x, y) a, b, x1, y1, x2, y2 = map(int, input().split()) xp1, yp1 = cds(a, b, x1, y1) xp2, yp2 = cds(a, b, x2, y2) print(norm(abs(xp1 - xp2), abs(yp1 - yp2)))
{ "input": [ "2 4 3 -1 3 7\n", "2 2 10 11 0 1\n", "2 2 1 0 0 1\n" ], "output": [ "2\n", "5\n", "1\n" ] }
3,785
11
Welcome! Everything is fine. You have arrived in The Medium Place, the place between The Good Place and The Bad Place. You are assigned a task that will either make people happier or torture them for eternity. You have a list of k pairs of people who have arrived in a new inhabited neighborhood. You need to assign each of the 2k people into one of the 2k houses. Each person will be the resident of exactly one house, and each house will have exactly one resident. Of course, in the neighborhood, it is possible to visit friends. There are 2k - 1 roads, each of which connects two houses. It takes some time to traverse a road. We will specify the amount of time it takes in the input. The neighborhood is designed in such a way that from anyone's house, there is exactly one sequence of distinct roads you can take to any other house. In other words, the graph with the houses as vertices and the roads as edges is a tree. The truth is, these k pairs of people are actually soulmates. We index them from 1 to k. We denote by f(i) the amount of time it takes for the i-th pair of soulmates to go to each other's houses. As we have said before, you will need to assign each of the 2k people into one of the 2k houses. You have two missions, one from the entities in The Good Place and one from the entities of The Bad Place. Here they are: * The first mission, from The Good Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is minimized. Let's define this minimized sum as G. This makes sure that soulmates can easily and efficiently visit each other; * The second mission, from The Bad Place, is to assign the people into the houses such that the sum of f(i) over all pairs i is maximized. Let's define this maximized sum as B. This makes sure that soulmates will have a difficult time to visit each other. What are the values of G and B? Input The first line of input contains a single integer t (1 ≀ t ≀ 500) denoting the number of test cases. The next lines contain descriptions of the test cases. The first line of each test case contains a single integer k denoting the number of pairs of people (1 ≀ k ≀ 10^5). The next 2k - 1 lines describe the roads; the i-th of them contains three space-separated integers a_i, b_i, t_i which means that the i-th road connects the a_i-th and b_i-th houses with a road that takes t_i units of time to traverse (1 ≀ a_i, b_i ≀ 2k, a_i β‰  b_i, 1 ≀ t_i ≀ 10^6). It is guaranteed that the given roads define a tree structure. It is guaranteed that the sum of the k in a single file is at most 3 β‹… 10^5. Output For each test case, output a single line containing two space-separated integers G and B. Example Input 2 3 1 2 3 3 2 4 2 4 3 4 5 6 5 6 5 2 1 2 1 1 3 2 1 4 3 Output 15 33 6 6 Note For the sample test case, we have a minimum sum equal to G = 15. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 5 and 6, giving us f(1) = 5; * The second pair of people get assigned to houses 1 and 4, giving us f(2) = 6; * The third pair of people get assigned to houses 3 and 2, giving us f(3) = 4. Note that the sum of the f(i) is 5 + 6 + 4 = 15. We also have a maximum sum equal to B = 33. One way this can be achieved is with the following assignment: * The first pair of people get assigned to houses 1 and 4, giving us f(1) = 6; * The second pair of people get assigned to houses 6 and 2, giving us f(2) = 14; * The third pair of people get assigned to houses 3 and 5, giving us f(3) = 13. Note that the sum of the f(i) is 6 + 14 + 13 = 33.
import sys def input(): return sys.stdin.readline().strip() def solve(): k = int(input()) n = 2*k e = [[] for i in range(n)] p = [None]*(n) for i in range(n-1): a, b, t = map(int, input().split()) a -= 1 b -= 1 e[a].append((b,t)) e[b].append((a,t)) q = [0] qi = 0 while qi < len(q): x = q[qi] qi += 1 px = p[x] for v, w in e[x]: if v != px: q.append(v) p[v] = x d1 = [False] * n d2 = [0] * n m = 0 M = 0 for qi in range(len(q)-1,-1,-1): x = q[qi] px = p[x] cnt = 1 c1 = 1 for v, w in e[x]: if v != px: if d1[v]: m += w cnt += 1 dv = d2[v] M += w * min(dv, n - dv) c1 += dv d1[x] = cnt % 2 d2[x] = c1 print(m, M) for i in range(int(input())): solve()
{ "input": [ "2\n3\n1 2 3\n3 2 4\n2 4 3\n4 5 6\n5 6 5\n2\n1 2 1\n1 3 2\n1 4 3\n" ], "output": [ "15 33\n6 6\n" ] }
3,786
11
Warawreh created a great company called Nanosoft. The only thing that Warawreh still has to do is to place a large picture containing its logo on top of the company's building. The logo of Nanosoft can be described as four squares of the same size merged together into one large square. The top left square is colored with red, the top right square is colored with green, the bottom left square is colored with yellow and the bottom right square is colored with blue. An Example of some correct logos: <image> An Example of some incorrect logos: <image> Warawreh went to Adhami's store in order to buy the needed picture. Although Adhami's store is very large he has only one picture that can be described as a grid of n rows and m columns. The color of every cell in the picture will be green (the symbol 'G'), red (the symbol 'R'), yellow (the symbol 'Y') or blue (the symbol 'B'). Adhami gave Warawreh q options, in every option he gave him a sub-rectangle from that picture and told him that he can cut that sub-rectangle for him. To choose the best option, Warawreh needs to know for every option the maximum area of sub-square inside the given sub-rectangle that can be a Nanosoft logo. If there are no such sub-squares, the answer is 0. Warawreh couldn't find the best option himself so he asked you for help, can you help him? Input The first line of input contains three integers n, m and q (1 ≀ n , m ≀ 500, 1 ≀ q ≀ 3 β‹… 10^{5}) β€” the number of row, the number columns and the number of options. For the next n lines, every line will contain m characters. In the i-th line the j-th character will contain the color of the cell at the i-th row and j-th column of the Adhami's picture. The color of every cell will be one of these: {'G','Y','R','B'}. For the next q lines, the input will contain four integers r_1, c_1, r_2 and c_2 (1 ≀ r_1 ≀ r_2 ≀ n, 1 ≀ c_1 ≀ c_2 ≀ m). In that option, Adhami gave to Warawreh a sub-rectangle of the picture with the upper-left corner in the cell (r_1, c_1) and with the bottom-right corner in the cell (r_2, c_2). Output For every option print the maximum area of sub-square inside the given sub-rectangle, which can be a NanoSoft Logo. If there are no such sub-squares, print 0. Examples Input 5 5 5 RRGGB RRGGY YYBBG YYBBR RBBRG 1 1 5 5 2 2 5 5 2 2 3 3 1 1 3 5 4 4 5 5 Output 16 4 4 4 0 Input 6 10 5 RRRGGGRRGG RRRGGGRRGG RRRGGGYYBB YYYBBBYYBB YYYBBBRGRG YYYBBBYBYB 1 1 6 10 1 3 3 10 2 2 6 6 1 7 6 10 2 1 5 10 Output 36 4 16 16 16 Input 8 8 8 RRRRGGGG RRRRGGGG RRRRGGGG RRRRGGGG YYYYBBBB YYYYBBBB YYYYBBBB YYYYBBBB 1 1 8 8 5 2 5 7 3 1 8 6 2 3 5 8 1 2 6 8 2 1 5 5 2 1 7 7 6 5 7 5 Output 64 0 16 4 16 4 36 0 Note Picture for the first test: <image> The pictures from the left to the right corresponds to the options. The border of the sub-rectangle in the option is marked with black, the border of the sub-square with the maximal possible size, that can be cut is marked with gray.
import sys readline = sys.stdin.readline def accumulate2d(X): N = len(X) M = len(X[0]) for i in range(0, N): for j in range(1, M): X[i][j] += X[i][j-1] for j in range(0, M): for i in range(1, N): X[i][j] += X[i-1][j] return X N, M, Q = map(int, readline().split()) table = [None]*100 table[ord('R')] = 0 table[ord('G')] = 1 table[ord('B')] = 2 table[ord('Y')] = 3 INF = 10**3 D = [[table[ord(s)] for s in readline().strip()] for _ in range(N)] G = [[0]*M for _ in range(N)] BS = 25 candi = [] geta = M for i in range(N-1): for j in range(M-1): if D[i][j] == 0 and D[i][j+1] == 1 and D[i+1][j+1] == 2 and D[i+1][j] == 3: G[i][j] = 1 nh, nw = i, j while True: k = G[nh][nw] fh, fw = nh-k, nw-k k2 = 2*(k+1) kh = k+1 if fh < 0 or fw < 0 or N < fh+k2-1 or M < fw+k2-1: break if any(D[fh][j] != 0 for j in range(fw, fw+kh)) or\ any(D[j][fw] != 0 for j in range(fh, fh+kh)) or\ any(D[fh][j] != 1 for j in range(fw+kh, fw+k2)) or\ any(D[j][fw+k2-1] != 1 for j in range(fh, fh+kh)) or\ any(D[j][fw+k2-1] != 2 for j in range(fh+kh, fh+k2)) or\ any(D[fh+k2-1][j] != 2 for j in range(fw+kh, fw+k2)) or\ any(D[fh+k2-1][j] != 3 for j in range(fw, fw+kh)) or\ any(D[j][fw] != 3 for j in range(fh+kh, fh+k2)): break G[nh][nw] += 1 if G[nh][nw] > BS: candi.append((nh, nw)) Gnum = [None] + [[[0]*M for _ in range(N)] for _ in range(BS)] for h in range(N): for w in range(M): if G[h][w] > 0: for k in range(1, min(BS, G[h][w])+1): Gnum[k][h][w] = 1 Gnum = [None] + [accumulate2d(g) for g in Gnum[1:]] Ans = [None]*Q for qu in range(Q): h1, w1, h2, w2 = map(lambda x: int(x)-1, readline().split()) res = 0 for k in range(min(BS, h2-h1+1, w2-w1+1), 0, -1): hs, ws = h1+k-1, w1+k-1 he, we = h2-k, w2-k if hs <= he and ws <= we: cnt = Gnum[k][he][we] if hs: cnt -= Gnum[k][hs-1][we] if ws: cnt -= Gnum[k][he][ws-1] if hs and ws: cnt += Gnum[k][hs-1][ws-1] if cnt: res = k break for nh, nw in candi: if h1 <= nh <= h2 and w1 <= nw <= w2: res = max(res, min(nh-h1+1, h2-nh, nw-w1+1, w2-nw, G[nh][nw])) Ans[qu] = 4*res**2 print('\n'.join(map(str, Ans)))
{ "input": [ "8 8 8\nRRRRGGGG\nRRRRGGGG\nRRRRGGGG\nRRRRGGGG\nYYYYBBBB\nYYYYBBBB\nYYYYBBBB\nYYYYBBBB\n1 1 8 8\n5 2 5 7\n3 1 8 6\n2 3 5 8\n1 2 6 8\n2 1 5 5\n2 1 7 7\n6 5 7 5\n", "5 5 5\nRRGGB\nRRGGY\nYYBBG\nYYBBR\nRBBRG\n1 1 5 5\n2 2 5 5\n2 2 3 3\n1 1 3 5\n4 4 5 5\n", "6 10 5\nRRRGGGRRGG\nRRRGGGRRGG\nRRRGGGYYBB\nYYYBBBYYBB\nYYYBBBRGRG\nYYYBBBYBYB\n1 1 6 10\n1 3 3 10\n2 2 6 6\n1 7 6 10\n2 1 5 10\n" ], "output": [ "64\n0\n16\n4\n16\n4\n36\n0\n", "16\n4\n4\n4\n0\n", "36\n4\n16\n16\n16\n" ] }
3,787
11
You are given an array a of length n that has a special condition: every element in this array has at most 7 divisors. Find the length of the shortest non-empty subsequence of this array product of whose elements is a perfect square. A sequence a is a subsequence of an array b if a can be obtained from b by deletion of several (possibly, zero or all) elements. Input The first line contains an integer n (1 ≀ n ≀ 10^5) β€” the length of a. The second line contains n integers a_1, a_2, …, a_{n} (1 ≀ a_i ≀ 10^6) β€” the elements of the array a. Output Output the length of the shortest non-empty subsequence of a product of whose elements is a perfect square. If there are several shortest subsequences, you can find any of them. If there's no such subsequence, print "-1". Examples Input 3 1 4 6 Output 1 Input 4 2 3 6 6 Output 2 Input 3 6 15 10 Output 3 Input 4 2 3 5 7 Output -1 Note In the first sample, you can choose a subsequence [1]. In the second sample, you can choose a subsequence [6, 6]. In the third sample, you can choose a subsequence [6, 15, 10]. In the fourth sample, there is no such subsequence.
from collections import deque import sys input=sys.stdin.readline def make_mf(): res=[-1]*(mxa+5) ptoi=[0]*(mxa+5) pn=1 for i in range(2,mxa+5): if res[i]==-1: res[i]=i ptoi[i]=pn pn+=1 for j in range(i**2,mxa+5,i): if res[j]==-1:res[j]=i return res,ptoi,pn def make_to(): to=[[] for _ in range(pn)] ss=set() for a in aa: pp=[] while a>1: p=mf[a] e=0 while p==mf[a]: a//=p e^=1 if e:pp.append(p) if len(pp)==0:ext(1) elif len(pp)==1:pp.append(1) u,v=ptoi[pp[0]],ptoi[pp[1]] to[u].append(v) to[v].append(u) if pp[0]**2<=mxa:ss.add(u) if pp[1]**2<=mxa:ss.add(v) return to,ss def ext(ans): print(ans) exit() def solve(): ans=inf for u in ss: ans=bfs(u,ans) if ans==inf:ans=-1 return ans def bfs(u,ans): dist=[-1]*pn q=deque() q.append((u,0,-1)) dist[u]=0 while q: u,d,pu=q.popleft() if d*2>=ans:break for v in to[u]: if v==pu:continue if dist[v]!=-1:ans=min(ans,d+dist[v]+1) dist[v]=d+1 q.append((v,d+1,u)) return ans inf=10**9 n=int(input()) aa=list(map(int,input().split())) mxa=max(aa) mf,ptoi,pn=make_mf() to,ss=make_to() print(solve())
{ "input": [ "3\n6 15 10\n", "4\n2 3 6 6\n", "4\n2 3 5 7\n", "3\n1 4 6\n" ], "output": [ "3", "2", "-1", "1" ] }
3,788
10
Uh oh! Applications to tech companies are due soon, and you've been procrastinating by doing contests instead! (Let's pretend for now that it is actually possible to get a job in these uncertain times.) You have completed many programming projects. In fact, there are exactly n types of programming projects, and you have completed a_i projects of type i. Your rΓ©sumΓ© has limited space, but you want to carefully choose them in such a way that maximizes your chances of getting hired. You want to include several projects of the same type to emphasize your expertise, but you also don't want to include so many that the low-quality projects start slipping in. Specifically, you determine the following quantity to be a good indicator of your chances of getting hired: $$$ f(b_1,…,b_n)=βˆ‘_{i=1}^n b_i(a_i-b_i^2). $$$ Here, b_i denotes the number of projects of type i you include in your rΓ©sumΓ©. Of course, you cannot include more projects than you have completed, so you require 0≀ b_i ≀ a_i for all i. Your rΓ©sumΓ© only has enough room for k projects, and you will absolutely not be hired if your rΓ©sumΓ© has empty space, so you require βˆ‘_{i=1}^n b_i=k. Find values for b_1,…, b_n that maximize the value of f(b_1,…,b_n) while satisfying the above two constraints. Input The first line contains two integers n and k (1≀ n≀ 10^5, 1≀ k≀ βˆ‘_{i=1}^n a_i) β€” the number of types of programming projects and the rΓ©sumΓ© size, respectively. The next line contains n integers a_1,…,a_n (1≀ a_i≀ 10^9) β€” a_i is equal to the number of completed projects of type i. Output In a single line, output n integers b_1,…, b_n that achieve the maximum value of f(b_1,…,b_n), while satisfying the requirements 0≀ b_i≀ a_i and βˆ‘_{i=1}^n b_i=k. If there are multiple solutions, output any. Note that you do not have to output the value f(b_1,…,b_n). Examples Input 10 32 1 2 3 4 5 5 5 5 5 5 Output 1 2 3 3 3 4 4 4 4 4 Input 5 8 4 4 8 2 1 Output 2 2 2 1 1 Note For the first test, the optimal answer is f=-269. Note that a larger f value is possible if we ignored the constraint βˆ‘_{i=1}^n b_i=k. For the second test, the optimal answer is f=9.
import sys import heapq as hq readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) eps = 10**-7 def solve(): n, k = nm() a = nl() ans = [0]*n ok = 10**9; ng = -4*10**18 while ok - ng > 1: mid = (ok + ng) // 2 ck = 0 for i in range(n): d = 9 - 12 * (mid + 1 - a[i]) if d < 0: continue ck += min(a[i], int((3 + d**.5) / 6 + eps)) # print(mid, ck) if ck > k: ng = mid else: ok = mid for i in range(n): d = 9 - 12 * (ok + 1 - a[i]) if d < 0: continue ans[i] = min(a[i], int((3 + d**.5) / 6 + eps)) # print(ans) rk = k - sum(ans) l = list() for i in range(n): if ans[i] < a[i]: hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i)) for _ in range(rk): v, i = hq.heappop(l) ans[i] += 1 if ans[i] < a[i]: hq.heappush(l, (-a[i] + 3 * ans[i]**2 - 3 * ans[i] + 1, i)) print(*ans) return solve()
{ "input": [ "5 8\n4 4 8 2 1\n", "10 32\n1 2 3 4 5 5 5 5 5 5\n" ], "output": [ "2 2 2 1 1 ", "1 2 3 3 3 4 4 4 4 4 " ] }
3,789
10
You are given n integers a_1, a_2, ..., a_n. For each a_i find its two divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 (where \gcd(a, b) is the greatest common divisor of a and b) or say that there is no such pair. Input The first line contains single integer n (1 ≀ n ≀ 5 β‹… 10^5) β€” the size of the array a. The second line contains n integers a_1, a_2, ..., a_n (2 ≀ a_i ≀ 10^7) β€” the array a. Output To speed up the output, print two lines with n integers in each line. The i-th integers in the first and second lines should be corresponding divisors d_1 > 1 and d_2 > 1 such that \gcd(d_1 + d_2, a_i) = 1 or -1 and -1 if there is no such pair. If there are multiple answers, print any of them. Example Input 10 2 3 4 5 6 7 8 9 10 24 Output -1 -1 -1 -1 3 -1 -1 -1 2 2 -1 -1 -1 -1 2 -1 -1 -1 5 3 Note Let's look at a_7 = 8. It has 3 divisors greater than 1: 2, 4, 8. As you can see, the sum of any pair of divisors is divisible by 2 as well as a_7. There are other valid pairs of d_1 and d_2 for a_{10}=24, like (3, 4) or (8, 3). You can print any of them.
def generate_LPF(N): LPF = [None]*(N+1) for p in range(2,N+1): if LPF[p]==None: for n in range(p,N+1,p): LPF[n] = p return LPF import sys n = int(sys.stdin.readline()) a = list(map(int,sys.stdin.readline().split())) LPF = generate_LPF(max(a)) d1 = [None]*n d2 = [None]*n for i in range(n): x = 1 p = LPF[a[i]] while LPF[a[i]]==p: a[i] //= p x *= p if x > 1 and a[i] > 1: d1[i], d2[i] = x, a[i] else: d1[i] = d2[i] = -1 print(*d1) print(*d2)
{ "input": [ "10\n2 3 4 5 6 7 8 9 10 24\n" ], "output": [ "-1 -1 -1 -1 2 -1 -1 -1 2 2\n-1 -1 -1 -1 3 -1 -1 -1 5 3\n" ] }
3,790
7
You are given an undirected graph where each edge has one of two colors: black or red. Your task is to assign a real number to each node so that: * for each black edge the sum of values at its endpoints is 1; * for each red edge the sum of values at its endpoints is 2; * the sum of the absolute values of all assigned numbers is the smallest possible. Otherwise, if it is not possible, report that there is no feasible assignment of the numbers. Input The first line contains two integers N (1 ≀ N ≀ 100 000) and M (0 ≀ M ≀ 200 000): the number of nodes and the number of edges, respectively. The nodes are numbered by consecutive integers: 1, 2, …, N. The next M lines describe the edges. Each line contains three integers a, b and c denoting that there is an edge between nodes a and b (1 ≀ a, b ≀ N) with color c (1 denotes black, 2 denotes red). Output If there is a solution, the first line should contain the word "YES" and the second line should contain N space-separated numbers. For each i (1 ≀ i ≀ N), the i-th number should be the number assigned to the node i. Output should be such that: * the sum of the numbers at the endpoints of each edge differs from the precise value by less than 10^{-6}; * the sum of the absolute values of all assigned numbers differs from the smallest possible by less than 10^{-6}. If there are several valid solutions, output any of them. If there is no solution, the only line should contain the word "NO". Scoring Subtasks: 1. (5 points) N ≀ 5, M ≀ 14 2. (12 points) N ≀ 100 3. (17 points) N ≀ 1000 4. (24 points) N ≀ 10 000 5. (42 points) No further constraints Examples Input 4 4 1 2 1 2 3 2 1 3 2 3 4 1 Output YES 0.5 0.5 1.5 -0.5 Input 2 1 1 2 1 Output YES 0.3 0.7 Input 3 2 1 2 2 2 3 2 Output YES 0 2 0 Input 3 4 1 2 2 2 2 1 2 1 1 1 2 2 Output NO Note Note that in the second example the solution is not unique.
import os import sys from io import BytesIO, IOBase # region fastio 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.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline() # ------------------------------ def RL(): return map(int, sys.stdin.readline().split()) def RLL(): return list(map(int, sys.stdin.readline().split())) def N(): return int(input()) def print_list(l): print(' '.join(map(str,l))) # import heapq as hq # import bisect as bs # from collections import deque as dq # from collections import defaultdict as dc # from math import ceil,floor,sqrt # from collections import Counter n,m = RL() dic = [[] for _ in range(n+1)] for _ in range(m): u,v,t = RL() dic[u].append((v,t)) dic[v].append((u,t)) v = [None] * (n+1) f = [True] * (n+1) key = {} color = [0]*(n+1) flag = True for s in range(1,n+1): if v[s] is not None: continue v[s] = 0 color[s] = s now = [s] ss = [0] while now and flag: p = now.pop() for child,t in dic[p]: if v[child] is not None: if f[child]!=f[p]: if v[child]+v[p]!=t: flag = False break elif f[child] is True: if s not in key: key[s] = (v[child]+v[p]-t)/(-2) elif v[child]+v[p]+key[s]*2!=t: flag = False break else: if s not in key: key[s] = (v[child]+v[p]-t)/2 elif v[child]+v[p]-key[s]*2!=t: flag = False break else: v[child] = t-v[p] f[child] = not f[p] if f[child]: ss.append(-1*v[child]) else: ss.append(v[child]) color[child] = s now.append(child) if not flag: break if s not in key: ss.sort() nn = len(ss) key[s] = (ss[nn>>1]+ss[nn-1>>1])/2 if flag: print("YES") res = [] for i in range(1,n+1): if f[i]: res.append(v[i]+key[color[i]]) else: res.append(v[i]-key[color[i]]) print_list(res) else: print("NO")
{ "input": [ "2 1\n1 2 1\n", "3 4\n1 2 2\n2 2 1\n2 1 1\n1 2 2\n", "4 4\n1 2 1\n2 3 2\n1 3 2\n3 4 1\n", "3 2\n1 2 2\n2 3 2\n" ], "output": [ "YES\n1 0 \n", "NO", "YES\n0.50 0.50 1.50 -0.50 ", "YES\n0.00 2.00 0.00 " ] }
3,791
10
There are n robbers at coordinates (a_1, b_1), (a_2, b_2), ..., (a_n, b_n) and m searchlight at coordinates (c_1, d_1), (c_2, d_2), ..., (c_m, d_m). In one move you can move each robber to the right (increase a_i of each robber by one) or move each robber up (increase b_i of each robber by one). Note that you should either increase all a_i or all b_i, you can't increase a_i for some points and b_i for some other points. Searchlight j can see a robber i if a_i ≀ c_j and b_i ≀ d_j. A configuration of robbers is safe if no searchlight can see a robber (i.e. if there is no pair i,j such that searchlight j can see a robber i). What is the minimum number of moves you need to perform to reach a safe configuration? Input The first line of input contains two integers n and m (1 ≀ n, m ≀ 2000): the number of robbers and the number of searchlight. Each of the next n lines contains two integers a_i, b_i (0 ≀ a_i, b_i ≀ 10^6), coordinates of robbers. Each of the next m lines contains two integers c_i, d_i (0 ≀ c_i, d_i ≀ 10^6), coordinates of searchlights. Output Print one integer: the minimum number of moves you need to perform to reach a safe configuration. Examples Input 1 1 0 0 2 3 Output 3 Input 2 3 1 6 6 1 10 1 1 10 7 7 Output 4 Input 1 2 0 0 0 0 0 0 Output 1 Input 7 3 0 8 3 8 2 7 0 10 5 5 7 0 3 5 6 6 3 11 11 5 Output 6 Note In the first test, you can move each robber to the right three times. After that there will be one robber in the coordinates (3, 0). The configuration of the robbers is safe, because the only searchlight can't see the robber, because it is in the coordinates (2, 3) and 3 > 2. In the second test, you can move each robber to the right two times and two times up. After that robbers will be in the coordinates (3, 8), (8, 3). It's easy the see that the configuration of the robbers is safe. It can be proved that you can't reach a safe configuration using no more than 3 moves.
import sys,math from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) n,m = inpl() ab = [inpl() for _ in range(n)] cd = [inpl() for _ in range(m)] up = [0] * 1000010 for a,b in ab: for c,d in cd: if a > c: continue #right:c-a+1 or up:d-b+1 up[c-a] = max(up[c-a], d-b+1) mx = 0 res = INF for right in range(1000010)[::-1]: mx = max(mx, up[right]) res = min(res, right+mx) print(res)
{ "input": [ "7 3\n0 8\n3 8\n2 7\n0 10\n5 5\n7 0\n3 5\n6 6\n3 11\n11 5\n", "2 3\n1 6\n6 1\n10 1\n1 10\n7 7\n", "1 1\n0 0\n2 3\n", "1 2\n0 0\n0 0\n0 0\n" ], "output": [ "6\n", "4\n", "3\n", "1\n" ] }
3,792
8
You are asked to watch your nephew who likes to play with toy blocks in a strange way. He has n boxes and the i-th box has a_i blocks. His game consists of two steps: 1. he chooses an arbitrary box i; 2. he tries to move all blocks from the i-th box to other boxes. If he can make the same number of blocks in each of n - 1 other boxes then he will be happy, otherwise, will be sad. Note that your nephew can only move the blocks from the chosen box to the other boxes; he cannot move blocks from the other boxes. You don't want to make your nephew sad, so you decided to put several extra blocks into some boxes in such a way that no matter which box i he chooses he won't be sad. What is the minimum number of extra blocks you need to put? Input The first line contains a single integer t (1 ≀ t ≀ 1000) β€” the number of test cases. The first line of each test case contains the integer n (2 ≀ n ≀ 10^5) β€” the number of boxes. The second line of each test case contains n integers a_1, a_2, ..., a_n (0 ≀ a_i ≀ 10^9) β€” the number of blocks in each box. It's guaranteed that the sum of n over test cases doesn't exceed 10^5. Output For each test case, print a single integer β€” the minimum number of blocks you need to put. It can be proved that the answer always exists, i. e. the number of blocks is finite. Example Input 3 3 3 2 2 4 2 2 3 2 3 0 3 0 Output 1 0 3 Note In the first test case, you can, for example, put one extra block into the first box and make a = [4, 2, 2]. If your nephew chooses the box with 4 blocks, then we will move two blocks to the second box and two blocks to the third box. If he chooses the box with 2 blocks then he will move these two blocks to the other box with 2 blocks. In the second test case, you don't need to put any extra blocks, since no matter which box your nephew chooses, he can always make other boxes equal. In the third test case, you should put 3 extra blocks. For example, you can put 2 blocks in the first box and 1 block in the third box. You'll get array a = [2, 3, 1].
from math import ceil def blocks(arr): n=len(arr) s=sum(arr) k=max(ceil(s/(n-1)),max(arr)) return ((n-1)*k)-s t=int(input()) for i in range(t): input() print(blocks(list(map(int,input().strip().split()))))
{ "input": [ "3\n3\n3 2 2\n4\n2 2 3 2\n3\n0 3 0\n" ], "output": [ "\n1\n0\n3\n" ] }
3,793
7
You are given an array a of 2n distinct integers. You want to arrange the elements of the array in a circle such that no element is equal to the the arithmetic mean of its 2 neighbours. More formally, find an array b, such that: * b is a permutation of a. * For every i from 1 to 2n, b_i β‰  \frac{b_{i-1}+b_{i+1}}{2}, where b_0 = b_{2n} and b_{2n+1} = b_1. It can be proved that under the constraints of this problem, such array b always exists. Input The first line of input contains a single integer t (1 ≀ t ≀ 1000) β€” the number of testcases. The description of testcases follows. The first line of each testcase contains a single integer n (1 ≀ n ≀ 25). The second line of each testcase contains 2n integers a_1, a_2, …, a_{2n} (1 ≀ a_i ≀ 10^9) β€” elements of the array. Note that there is no limit to the sum of n over all testcases. Output For each testcase, you should output 2n integers, b_1, b_2, … b_{2n}, for which the conditions from the statement are satisfied. Example Input 3 3 1 2 3 4 5 6 2 123 456 789 10 1 6 9 Output 3 1 4 2 5 6 123 10 456 789 9 6 Note In the first testcase, array [3, 1, 4, 2, 5, 6] works, as it's a permutation of [1, 2, 3, 4, 5, 6], and (3+4)/(2)β‰  1, (1+2)/(2)β‰  4, (4+5)/(2)β‰  2, (2+6)/(2)β‰  5, (5+3)/(2)β‰  6, (6+1)/(2)β‰  3.
def solve(a, n): i = 0 while i < n: a[i], a[2*n - i - 1] = a[2*n - i - 1], a[i] i += 2 return a for _ in range(int(input())): n = int(input()) a = sorted(list(map(int, input().split()))) print(*solve(a, n))
{ "input": [ "3\n3\n1 2 3 4 5 6\n2\n123 456 789 10\n1\n6 9\n" ], "output": [ "\n3 1 4 2 5 6\n123 10 456 789\n9 6\n" ] }
3,794
7
You've got a rectangular parallelepiped with integer edge lengths. You know the areas of its three faces that have a common vertex. Your task is to find the sum of lengths of all 12 edges of this parallelepiped. Input The first and the single line contains three space-separated integers β€” the areas of the parallelepiped's faces. The area's values are positive ( > 0) and do not exceed 104. It is guaranteed that there exists at least one parallelepiped that satisfies the problem statement. Output Print a single number β€” the sum of all edges of the parallelepiped. Examples Input 1 1 1 Output 12 Input 4 6 6 Output 28 Note In the first sample the parallelepiped has sizes 1 Γ— 1 Γ— 1, in the second one β€” 2 Γ— 2 Γ— 3.
import math def i(a,b,c):return int(math.sqrt((a*b)/c)) a,b,c=map(int,input().split()) print((i(a,b,c)+i(b,c,a)+i(a,c,b))*4)
{ "input": [ "4 6 6\n", "1 1 1\n" ], "output": [ "28", "12" ] }
3,795
10
For he knew every Who down in Whoville beneath, Was busy now, hanging a mistletoe wreath. "And they're hanging their stockings!" he snarled with a sneer, "Tomorrow is Christmas! It's practically here!" Dr. Suess, How The Grinch Stole Christmas Christmas celebrations are coming to Whoville. Cindy Lou Who and her parents Lou Lou Who and Betty Lou Who decided to give sweets to all people in their street. They decided to give the residents of each house on the street, one kilogram of sweets. So they need as many kilos of sweets as there are homes on their street. The street, where the Lou Who family lives can be represented as n consecutive sections of equal length. You can go from any section to a neighbouring one in one unit of time. Each of the sections is one of three types: an empty piece of land, a house or a shop. Cindy Lou and her family can buy sweets in a shop, but no more than one kilogram of sweets in one shop (the vendors care about the residents of Whoville not to overeat on sweets). After the Lou Who family leave their home, they will be on the first section of the road. To get to this section of the road, they also require one unit of time. We can assume that Cindy and her mom and dad can carry an unlimited number of kilograms of sweets. Every time they are on a house section, they can give a kilogram of sweets to the inhabitants of the house, or they can simply move to another section. If the family have already given sweets to the residents of a house, they can't do it again. Similarly, if they are on the shop section, they can either buy a kilo of sweets in it or skip this shop. If they've bought a kilo of sweets in a shop, the seller of the shop remembered them and the won't sell them a single candy if they come again. The time to buy and give sweets can be neglected. The Lou Whos do not want the people of any house to remain without food. The Lou Whos want to spend no more than t time units of time to give out sweets, as they really want to have enough time to prepare for the Christmas celebration. In order to have time to give all the sweets, they may have to initially bring additional k kilos of sweets. Cindy Lou wants to know the minimum number of k kilos of sweets they need to take with them, to have time to give sweets to the residents of each house in their street. Your task is to write a program that will determine the minimum possible value of k. Input The first line of the input contains two space-separated integers n and t (2 ≀ n ≀ 5Β·105, 1 ≀ t ≀ 109). The second line of the input contains n characters, the i-th of them equals "H" (if the i-th segment contains a house), "S" (if the i-th segment contains a shop) or "." (if the i-th segment doesn't contain a house or a shop). It is guaranteed that there is at least one segment with a house. Output If there isn't a single value of k that makes it possible to give sweets to everybody in at most t units of time, print in a single line "-1" (without the quotes). Otherwise, print on a single line the minimum possible value of k. Examples Input 6 6 HSHSHS Output 1 Input 14 100 ...HHHSSS...SH Output 0 Input 23 50 HHSS.......SSHHHHHHHHHH Output 8 Note In the first example, there are as many stores, as houses. If the family do not take a single kilo of sweets from home, in order to treat the inhabitants of the first house, they will need to make at least one step back, and they have absolutely no time for it. If they take one kilogram of sweets, they won't need to go back. In the second example, the number of shops is equal to the number of houses and plenty of time. Available at all stores passing out candy in one direction and give them when passing in the opposite direction. In the third example, the shops on the street are fewer than houses. The Lou Whos have to take the missing number of kilograms of sweets with them from home.
def check(n, casas): #print('n:',n) global T,N,street current = n time = T need = 0 last_house = 0 for ind, i in enumerate(street): time -= 1 if i == 'S': current += 1 elif i == 'H': need += 1 if need == 1: last_house = ind if need > 0 and current >= need: #print('p',time, ind-last_house) current -= need casas -= need need = 0 if casas > 0: if (ind-last_house)*2 >= N-last_house-1: time -= N-last_house-1 + N-ind-1 return time >= 0 time -= (ind-last_house)*2 else: time -= ind-last_house #print('lugar:',i,ind,current, time, need, last_house) if casas == 0: break #print(time) return time >= 0 and casas == 0 N,T = [int(i) for i in input().split()] street = input().rstrip('.') N = len(street) C = street.count('H') S = street.count('S') l = max(C-S, 0) r = 500005 #print(N, C) while l < r: mid = (l+r)//2 if check(mid, C): r = mid else: l = mid + 1 print(l if l < 500005 else -1)
{ "input": [ "23 50\nHHSS.......SSHHHHHHHHHH\n", "14 100\n...HHHSSS...SH\n", "6 6\nHSHSHS\n" ], "output": [ "8", "0", "1" ] }
3,796
8
Yaroslav thinks that two strings s and w, consisting of digits and having length n are non-comparable if there are two numbers, i and j (1 ≀ i, j ≀ n), such that si > wi and sj < wj. Here sign si represents the i-th digit of string s, similarly, wj represents the j-th digit of string w. A string's template is a string that consists of digits and question marks ("?"). Yaroslav has two string templates, each of them has length n. Yaroslav wants to count the number of ways to replace all question marks by some integers in both templates, so as to make the resulting strings incomparable. Note that the obtained strings can contain leading zeroes and that distinct question marks can be replaced by distinct or the same integers. Help Yaroslav, calculate the remainder after dividing the described number of ways by 1000000007 (109 + 7). Input The first line contains integer n (1 ≀ n ≀ 105) β€” the length of both templates. The second line contains the first template β€” a string that consists of digits and characters "?". The string's length equals n. The third line contains the second template in the same format. Output In a single line print the remainder after dividing the answer to the problem by number 1000000007 (109 + 7). Examples Input 2 90 09 Output 1 Input 2 11 55 Output 0 Input 5 ????? ????? Output 993531194 Note The first test contains no question marks and both strings are incomparable, so the answer is 1. The second test has no question marks, but the given strings are comparable, so the answer is 0.
#!/usr/bin/python3 def build(n, s, t): ans = 1 for i in range(n): if s[i] == '?' and t[i] == '?': ans = (55 * ans) % (10 ** 9 + 7) elif s[i] == '?': ans = ((ord(t[i]) - ord('0') + 1) * ans) % (10 ** 9 + 7) elif t[i] == '?': ans = ((ord('9') - ord(s[i]) + 1) * ans) % (10 ** 9 + 7) return ans n = int(input()) s = input() t = input() sltt = True tlts = True qm = 0 cqm = 0 for i in range(n): if t[i] == '?': qm += 1 if s[i] == '?': qm += 1 if t[i] == '?' and s[i] == '?': cqm += 1 if t[i] == '?' or s[i] == '?': continue if ord(s[i]) < ord(t[i]): tlts = False if ord(t[i]) < ord(s[i]): sltt = False if not sltt and not tlts: print(pow(10, qm, 10 ** 9 + 7)) elif sltt and tlts: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t) - build(n, t, s) + pow(10, cqm, 10 ** 9 + 7)) % (10 ** 9 + 7)) elif sltt: print((pow(10, qm, 10 ** 9 + 7) - build(n, s, t)) % (10 ** 9 + 7)) else: print((pow(10, qm, 10 ** 9 + 7) - build(n, t, s)) % (10 ** 9 + 7))
{ "input": [ "2\n90\n09\n", "2\n11\n55\n", "5\n?????\n?????\n" ], "output": [ "1", "0", "993531194" ] }
3,797
11
In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) β€” add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a β‰  b) β€” answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≀ n ≀ 105). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES
n=int(input()) intervals={} idx=0 adj={} def is_path(s,e): if s==e: return True vis[s]=1 for i in adj[s]: if not vis[i]: if is_path(i,e): return True return False for i in range(n): a,b,c=map(int,input().split()) if a==1: idx+=1 adj[idx]=[] for j in intervals: (d,e)=intervals[j] if d<b<e or d<c<e: adj[idx].append(j) if b<d<c or b<e<c: adj[j].append(idx) intervals[idx]=(b,c) else: vis=[0]*101 if is_path(b,c): print("YES") else: print("NO")
{ "input": [ "5\n1 1 5\n1 5 11\n2 1 2\n1 2 9\n2 1 2\n" ], "output": [ "NO\nYES\n" ] }
3,798
8
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)Β·p ≀ n; q β‰₯ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements. Sereja needs to rush to the gym, so he asked to find all the described positions of q. Input The first line contains three integers n, m and p (1 ≀ n, m ≀ 2Β·105, 1 ≀ p ≀ 2Β·105). The next line contains n integers a1, a2, ..., an (1 ≀ ai ≀ 109). The next line contains m integers b1, b2, ..., bm (1 ≀ bi ≀ 109). Output In the first line print the number of valid qs. In the second line, print the valid values in the increasing order. Examples Input 5 3 1 1 2 3 2 1 1 2 3 Output 2 1 3 Input 6 3 2 1 3 2 2 3 1 1 2 3 Output 2 1 2
from collections import Counter n, m, p = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) def try_from(start, a, b): result = [] seq = a[start::p] i = 0 if len(seq) < len(b): return [] counts_a = Counter(seq[:len(b)]) counts_b = Counter(b) if counts_a == counts_b: result.append(start) for i in range(1, len(seq) - len(b) + 1): counts_a[seq[i-1]] -= 1 counts_a[seq[i+len(b) - 1]] += 1 if not counts_a[seq[i-1]]: del counts_a[seq[i-1]] ok = counts_a == counts_b #ok = sorted(seq[i:i+len(b)]) == sorted(b) if ok: result.append(start + p * i) return [x + 1 for x in result] result = [] for start in range(p): result += try_from(start, a, b) print(len(result)) print(' '.join(map(str, sorted(result))))
{ "input": [ "5 3 1\n1 2 3 2 1\n1 2 3\n", "6 3 2\n1 3 2 2 3 1\n1 2 3\n" ], "output": [ "2\n1 3 ", "2\n1 2 " ] }
3,799
7
Vasya has n pairs of socks. In the morning of each day Vasya has to put on a pair of socks before he goes to school. When he comes home in the evening, Vasya takes off the used socks and throws them away. Every m-th day (at days with numbers m, 2m, 3m, ...) mom buys a pair of socks to Vasya. She does it late in the evening, so that Vasya cannot put on a new pair of socks before the next day. How many consecutive days pass until Vasya runs out of socks? Input The single line contains two integers n and m (1 ≀ n ≀ 100; 2 ≀ m ≀ 100), separated by a space. Output Print a single integer β€” the answer to the problem. Examples Input 2 2 Output 3 Input 9 3 Output 13 Note In the first sample Vasya spends the first two days wearing the socks that he had initially. Then on day three he puts on the socks that were bought on day two. In the second sample Vasya spends the first nine days wearing the socks that he had initially. Then he spends three days wearing the socks that were bought on the third, sixth and ninth days. Than he spends another day wearing the socks that were bought on the twelfth day.
def main(): n, m = list(map(int, input().split())) print (n+(n-1)//(m-1)) main()
{ "input": [ "2 2\n", "9 3\n" ], "output": [ "3\n", "13\n" ] }