text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Tags: dp, strings
Correct Solution:
```
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().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def c(chr): return ord(chr)-ord('a')
def main():
n, k = RL()
s = input()
dp = [[0]*(n+1) for i in range(n+1)]
rec = [-1]*26
pre = [-1]*n
for i in range(n+1):
dp[i][0] = 1
for i in range(n):
now = c(s[i])
pre[i] = rec[now]
rec[now] = i
for i in range(1, n+1):
for j in range(1, i+1):
# if j>i: break
dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
# if i == 6 and j == 1: print(dp[i-1][j], dp[i-1][j-1])
if pre[i-1]!=-1:
# if i==5 and j==4: print(pre[i-1], '+++')
# if i==6 and j==1: print(pre[i-1], dp[pre[i-1]][j], dp[i][j])
dp[i][j] -= dp[pre[i-1]][j-1]
res = 0
for j in range(n, -1, -1):
if k:
num = min(k, dp[-1][j])
k-=num
res += (n-j)*num
# for i in dp: print(i)
print(res if k==0 else -1)
if __name__ == "__main__":
main()
```
| 100 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Tags: dp, strings
Correct Solution:
```
from sys import stdin
n, k = [int(i) for i in stdin.readline().strip().split()]
s = stdin.readline().strip()
def get_f(s):
F = [len(s) * [0] for _ in range((len(s) + 1))]
size = 0
for index in range(len(s)):
F[size][index] = 1
F[1][0] = 1
p = {s[0]: 0}
for i in range(1, len(s)):
for k in range(1, len(s) + 1):
if k > i + 1:
val = 0
else:
val = F[k][i - 1] + F[k - 1][i - 1]
if s[i] in p:
# sic: if k - 1 == 0 then answer is always 1
# if k - 1 == 0:
# print(i)
# val -= 1
if p[s[i]] - 1 >= 0:
val -= F[k - 1][p[s[i]] - 1]
elif p[s[i]] == 0 and k - 1 == 0:
val -= 1
F[k][i] = val
p[s[i]] = i
return F
_F = get_f(s)
# for sz in range(len(s) + 1):
# for index in range(len(s)):
# print(_F[sz][index], end=' ')
# print()
def count(size, index = None):
return _F[size][index or (len(s) - 1)]
# recursive solution with memoization
previous_letter_index = {}
found = {}
for index, letter in enumerate(s):
if letter in found:
previous_letter_index[(letter, index)] = found[letter]
found[letter] = index
_subsequences = {}
def subsequences(size, index):
"""Get number of distinct subsequences of given size in sequence[0:index + 1] slice"""
if (size, index) not in _subsequences:
if size == 0:
res = 1
elif size > index + 1:
res = 0
else:
res = subsequences(size, index - 1) + subsequences(size - 1, index - 1)
letter = s[index]
if (letter, index) in previous_letter_index:
res -= subsequences(size - 1, previous_letter_index[(letter, index)] - 1)
_subsequences[(size, index)] = res
return _subsequences[(size, index)]
total_cost = 0
for size in range(len(s), -1, -1):
if k == 0:
break
step_cost = n - size
sequence_count = count(size, len(s) - 1)
# print('size = ', size, 'count = ', sequence_count)
if sequence_count > k:
sequence_count = k
total_cost += step_cost * sequence_count
k -= sequence_count
if k == 0:
print(total_cost)
else:
print(-1)
```
| 101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Tags: dp, strings
Correct Solution:
```
def naiveSolve():
return
def charToInt(c): #'a'->0
return ord(c)-ord('a')
def main():
n,k=readIntArr()
s=input()
arr=[charToInt(c) for c in s]
dp=[[0 for _ in range(n+1)] for __ in range(n)]
# dp[i][l]
for i in range(n):
dp[i][1]=1
prevLatestIdx=[-1]*26
# to avoid repeated counting like ababa -> aba x 3,
# take only from the latest appearance of each character
for i in range(n):
for l in range(2,n+1):
for c in range(26):
if prevLatestIdx[c]!=-1:
dp[i][l]+=dp[prevLatestIdx[c]][l-1]
prevLatestIdx[arr[i]]=i
cnts=[0]*(n+1)
for c in range(26):
if prevLatestIdx[c]!=-1:
for l in range(1,n+1):
cnts[l]+=dp[prevLatestIdx[c]][l]
cnts[0]=1
cost=0
for l in range(n,-1,-1):
diff=min(k,cnts[l])
cost+=diff*(n-l)
k-=diff
if k==0:
print(cost)
else:
print(-1)
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(l,r):
print('? {} {}'.format(l,r))
sys.stdout.flush()
return int(input())
def answerInteractive(x):
print('! {}'.format(x))
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()
```
| 102 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Tags: dp, strings
Correct Solution:
```
def main():
from sys import stdin
input = stdin.readline
# input = open('25-B.txt', 'r').readline
n, k = map(int, input().split())
s = input()[:-1]
dp = [[0] * 26 for i in range(n + 1)]
dp[0][0] = 1
for ch in s:
j = ord(ch) - ord('a')
for i in range(n, 0, -1):
dp[i][j] = sum(dp[i - 1])
x = 0
y = 0
for i in range(n, -1, -1):
if x + sum(dp[i]) >= k:
print(k * n - y - (k - x) * i)
break
x += sum(dp[i])
y += i * sum(dp[i])
else:
print(-1)
main()
```
| 103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Tags: dp, strings
Correct Solution:
```
[n, k] = [int(i) for i in input().split()]
s = input()
cntsz = [0 for i in range(105)]
dp = [[0 for i in range(105)] for j in range(105)]
lst = [0 for i in range(105)]
prv = [0 for i in range(26)]
n = len(s)
s = '%' + s
for i in range(n + 1):
dp[i][0]=1
for i in range(1, n + 1):
lst[i] = prv[ord(s[i])-ord('a')]
prv[ord(s[i]) - ord('a')] = i
for sz in range(1, n + 1):
for i in range(1, n + 1):
dp[i][sz] += dp[i - 1][sz]
dp[i][sz] += dp[i - 1][sz - 1]
if lst[i] != 0:
dp[i][sz] -= dp[lst[i]-1][sz-1]
for sz in range(1, n + 1):
for i in range(1, n + 1):
cntsz[sz] += dp[i][sz]
cntsz[sz] -= dp[i - 1][sz]
cntsz[0] += 1
done = 0
ans = 0
for i in range(n, -1, -1):
if done + cntsz[i] >= k:
ans += (n - i) * (k - done)
done = k
break
done += cntsz[i]
ans += cntsz[i] * (n - i)
if done < k:
print(-1)
else:
print(ans)
```
| 104 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
import sys
import math
from collections import defaultdict,deque
import heapq
n,k = map(int,sys.stdin.readline().split())
ss = sys.stdin.readline()[:-1]
dp = [[0 for _ in range(n+1)] for i in range(n+1)]
dp[n][1]=1
dp[n][0]=1
dic=defaultdict(list)
for i in range(n):
dic[ss[i]].append(i+1)
#print(dic,'dic')
for i in range(n-1,0,-1):
#vis=defaultdict(int)
for j in range(1,n+1):
s=0
for x in range(i+1,n+1):
s+=dp[x][j-1]
z=-1
cnt=0
#print(ss[i-1])
#print(dic[ss[i-1]])
for y in dic[ss[i-1]]:
cnt+=1
if y==i:
break
sub=0
if len(dic[ss[i-1]])>cnt:
for q in range(cnt,len(dic[ss[i-1]])):
sub+=dp[dic[ss[i-1]][q]][j]
#print(dic[ss[i-1]][q],'row',j,'col',sub,'sub')
#sub=dp[dic[ss[i-1]][cnt]][j]
#print(cnt,'cnt',i,'i',j,'j',s,'sssss',sub,'sub',cnt,'cnt',dic[ss[i-1]])
dp[i][j]+=s-sub
#print(s,'s',sub,'sub')
'''for i in range(n+1):
print(dp[i],'dp')'''
cost=0
for i in range(n,-1,-1):
for j in range(n+1):
#print(k,'k',i,'i',j,'j')
if dp[j][i]<=k:
cost+=(n-i)*dp[j][i]
k-=dp[j][i]
else:
#print(n,'n',i,'i',k,'k')
cost+=k*(n-i)
k=0
break
#print(cost,'cost',k,'k')
if k!=0:
print(-1)
else:
print(cost)
```
Yes
| 105 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
#import sys
#input = sys.stdin.buffer.readline
def main():
n, K = map(int, input().split())
s = str(input())
next = [[10**18]*26 for _ in range(n+1)]
for i in reversed(range(n)):
for j in range(26):
next[i][j] = next[i+1][j]
if s[i] == chr(j+ord('a')):
next[i][j] = i
#print(next)
dp = [[0]*(n+1) for i in range(n+1)]
dp[0][0] = 1
for i in range(n):
for j in range(n+1):
#dp[i+1][j] += dp[i][j]
for k in range(26):
if next[i][k] >= n:
continue
else:
if j+1 <= n:
dp[next[i][k]+1][j+1] += dp[i][j]
#print(dp)
d = {}
V = [0]*(n+1)
for i in range(n+1):
for j in range(n+1):
V[j] += dp[i][j]
V.reverse()
#print(V)
ans = 0
for i, v in enumerate(V):
if v >= K:
ans += K*i
break
else:
ans += v*i
K -= v
else:
print(-1)
exit()
print(ans)
if __name__ == '__main__':
main()
```
Yes
| 106 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
n, k = map(int, input().split(' '))
s = input()
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
for l in range(0, n):
for i in range(l, n + 1):
used = [False] * 26
for j in range(i + 1, n + 1):
ch = ord(s[j - 1]) - ord('a')
if not used[ch]:
dp[l + 1][j] += dp[l][i]
used[ch] = True
total = 0
for l in range(n, -1, -1):
sums = sum(dp[l])
if sums >= k:
total += (n - l) * k
k = 0
break
total += (n - l) * sums
k -= sums
if k > 0:
total = -1
print(total)
```
Yes
| 107 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
alpha = list("abcdefghijklmnopqrstuvwxyz ")
def count_subseq(s):
n = len(s)
dp = [[[0]*27 for i in range(n+10)] for j in range(n+10)]
dp[0][0][26] = 1
for i in range(1, n+1):
st = s[i-1]
for j in range(i+1):
v = sum(dp[i-1][j-1][p] for p in range(27))
for last_string in range(27):
if alpha[last_string]!=st:
dp[i][j][last_string] = dp[i-1][j][last_string]
else:
#lastalpha == st
dp[i][j][last_string] = v
result = [0]*(n+1)
for l in range(n+1):
result[l] = sum(dp[n][l][v] for v in range(27))
return result
def solution():
n, k = map(int, input().split())
s = input()
cntlist = count_subseq(s)
res = 0
for length in range(n, -1, -1):
if k == 0:
break
cnt = cntlist[length]
if cnt >= k:
res += (n-length)*k
k = 0
elif cnt < k:
res += (n-length)*cnt
k -= cnt
if k > 0:
print(-1)
else:
print(res)
return
def main():
test = 1
for i in range(test):
solution()
return
if __name__ == "__main__":
main()
```
Yes
| 108 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
import sys
n,k=map(int,input().split())
s=input()
b=[]
for j in s:
b.append(j)
dp=[[0 for i in range(n+1)] for j in range(n)]
last=dict()
dp[0][0]=1
dp[0][1]=1
last[b[0]]=0
for i in range(1,n):
dp[i][0]=1
for j in range(1,n+1):
if b[i] in last.keys():
dp[i][j]=dp[i-1][j]+dp[i-1][j-1]-dp[last[b[i]]][j]
else:
dp[i][j] = dp[i - 1][j] + dp[i - 1][j- 1]
last[b[i]]=i
s=0
res=0
if sum(dp[-1])<k:
print(-1)
sys.exit()
j=n
while(j>=0):
if s+dp[-1][j]<k:
s+=dp[-1][j]
res+=dp[-1][j]*(n-j)
else:
res+=(k-s)*(n-j)
break
j+=-1
print(res)
```
No
| 109 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
from sys import stdout, stdin
n, kk = map(int, stdin.readline().split())
s = stdin.readline().strip()
s += "$"
n = n+1
dp = [[0 for i in range(n)] for j in range(n)]
p = 10**12+5
for i in range(n):
dp[i][0] = 1
for end in range(n):
for length in range(1, n):
seen = []
ans = 0
for k in range(end-1, -1, -1):
if s[k] not in seen:
seen.append(s[k])
ans += dp[k][length-1]
ans %= p
dp[end][length] = ans
totals = [dp[n-1][length] for length in range(n)]
#print(totals)
ans = 0
idx = n-1
while idx >= 0 and kk > 0:
ans += min(totals[idx], kk)*(n-1-idx)
kk -= totals[idx]
idx -= 1
if kk <= 0:
stdout.write(str(ans) +"\n")
else:
print(-1)
```
No
| 110 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
n, k = map(int, input().split(' '))
s = input()
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
prev = [None] * 26
for i in range(1, n + 1):
for l in range(2, i + 1):
for j in range(26):
if prev[j] is not None:
dp[l][i] += dp[l - 1][prev[j]]
ch = ord(s[i - 1]) - ord('a')
if prev[ch] is None:
dp[1][i] = 1
prev[ch] = i
total = 0
for l in range(n, -1, -1):
sums = sum(dp[l])
if sums >= k:
total += (n - l) * k
k = 0
break
total += (n - l) * sums
k -= sums
if k > 0:
total = -1
print(total)
```
No
| 111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The only difference between the easy and the hard versions is constraints.
A subsequence is a string that can be derived from another string by deleting some or no symbols without changing the order of the remaining symbols. Characters to be deleted are not required to go successively, there can be any gaps between them. For example, for the string "abaca" the following strings are subsequences: "abaca", "aba", "aaa", "a" and "" (empty string). But the following strings are not subsequences: "aabaca", "cb" and "bcaa".
You are given a string s consisting of n lowercase Latin letters.
In one move you can take any subsequence t of the given string and add it to the set S. The set S can't contain duplicates. This move costs n - |t|, where |t| is the length of the added subsequence (i.e. the price equals to the number of the deleted characters).
Your task is to find out the minimum possible total cost to obtain a set S of size k or report that it is impossible to do so.
Input
The first line of the input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10^{12}) — the length of the string and the size of the set, correspondingly.
The second line of the input contains a string s consisting of n lowercase Latin letters.
Output
Print one integer — if it is impossible to obtain the set S of size k, print -1. Otherwise, print the minimum possible total cost to do it.
Examples
Input
4 5
asdf
Output
4
Input
5 6
aaaaa
Output
15
Input
5 7
aaaaa
Output
-1
Input
10 100
ajihiushda
Output
233
Note
In the first example we can generate S = { "asdf", "asd", "adf", "asf", "sdf" }. The cost of the first element in S is 0 and the cost of the others is 1. So the total cost of S is 4.
Submitted Solution:
```
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().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def c(chr): return ord(chr)-ord('a')
def main():
n, k = RL()
s = input()
dp = [[0]*(n+1) for i in range(n+1)]
rec = [-1]*26
pre = [-1]*n
dp[0][0] = 1
for i in range(n):
now = c(s[i])
pre[i] = rec[now]
rec[now] = i
for i in range(1, n+1):
for j in range(1, i+1):
if j>i: break
if i==j: dp[i][j] = 1; continue;
dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
if pre[i-1]!=-1:
# if i==5 and j==4: print(pre[i-1], '+++')
dp[i][j] -= dp[pre[i-1]][j-1]
res = 0
for j in range(n, -1, -1):
for i in range(n, -1, -1):
if k:
num = min(k, dp[i][j])
k-=num
res += (n-j)*num
print(res if k==0 else -1)
if __name__ == "__main__":
main()
```
No
| 112 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
# 1201C Maximum Median
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
m = n // 2; a.sort()
fst = 1; lst = int(2e9)
while fst != lst:
mid = (fst + lst + 1) // 2
tmp = 0
for i in range(m, n):
if mid - a[i] > 0:
tmp += (mid - a[i])
if tmp > k:
lst = mid - 1
break
if tmp <= k:
fst = mid
print(fst)
```
| 113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
n,k=map(int,input().split())
arr=list(map(int,input().split()))
arr.sort()
mid=n//2
itr=1
tot=0
for i in range(mid+1,n):
if tot+(arr[i]-arr[i-1])*itr>k:
break
else:
tot+= (arr[i]-arr[i-1])*itr
itr+=1
final=arr[mid+itr-1]+((k-tot)//(itr))
print(final)
```
| 114 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush,heappop,heapify
from itertools import permutations,combinations
from itertools import accumulate as ac
mod = int(1e9)+7
#mod = 998244353
ip = lambda : int(stdin.readline())
inp = lambda: map(int,stdin.readline().split())
ips = lambda: stdin.readline().rstrip()
out = lambda x : stdout.write(str(x)+"\n")
t = 1
for _ in range(t):
n,k = inp()
arr = list(inp())
arr.sort()
arr = arr[n//2:]
ct = 1
arr = deque(arr)
while len(arr) != 1:
if arr[0] == arr[1]:
ct += 1
arr.popleft()
else:
diff = arr[1]-arr[0]
if k>= diff*ct:
k -= ct*diff
ct += 1
arr.popleft()
else:
break
add = k//ct
ans = arr[0]+add
print(ans)
```
| 115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
n, k = map(int, input().split())
arr = list(map(int, input().split()))
if n == 1:
print(arr[0]+k)
else:
res = 0
arr.sort()
a = arr[n//2:]
diff = []
for i in range(1,len(a)):
diff.append(a[i]-a[i-1])
l = 0
while(k>0 and l<len(diff)):
if k>diff[l]*(l+1):
k-=diff[l]*(l+1)
l+=1
else:
res=a[l]+k//(l+1)
k=0
if k>0:
res=a[~0]+k//len(a)
print(res)
```
| 116 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
n,k = [int(i) for i in input().split(" ")]
a = [int(i) for i in input().split(" ")]
a.sort()
b = a[n//2:]
def p(m):
ans = 0
for s in b:
if m <= s:
break
else:
ans += m-s
return ans <= k
low = b[0]
high = b[0]+k
while low < high:
mid = low +(high-low + 1)//2
if p(mid):
low = mid
else:
high = mid -1
print(low)
```
| 117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
n,k = map(int,input().split())
A = [int(x) for x in input().split()]
A.sort()
median = A[n//2]
inf = 10**16
from collections import defaultdict as dd, deque
C = dd(int)
for x in A[n//2:]:
C[x] += 1
C[inf] = 123
nmedian = C[median]
S = sorted(C.items())
i = 0
while i < len(S) and S[i][0] < median:
i += 1
while True:
who,count = S[i+1]
afford = k//nmedian
if who != inf:
can = who - median
else:
can = inf
if min(afford,can) == can:
k -= can*nmedian
median = who
nmedian += count
else:
median += afford
break
i += 1
print(median)
```
| 118 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
p = [0] * (n // 2)
m = n // 2
ans = a[m]
s = 0
for i in range(m + 1, n):
p[i - m - 1] = (a[i] - a[i -1])
s += p[i - m - 1] * (i - m)
if (k < s):
for i in range(m):
r = p[i] * (i + 1)
if k >= r:
k -= r
ans += p[i]
else:
ans += k // (i + 1)
break
else:
k -= s
ans = a[-1]
ans += k // (m + 1)
print(ans)
```
| 119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Tags: binary search, greedy, math, sortings
Correct Solution:
```
size, k = map(int, input().split())
array = sorted(list(map(int, input().split())))
median_pos = size//2
increase_pos = list()
dif = list()
for x in range(median_pos+1, size):
cur = array[x]
prev = array[x - 1]
if cur != prev:
increase_pos.append(x)
dif.append(cur-prev)
increased = 0
stop = size
for x in range(len(increase_pos)):
dif_range = increase_pos[x] - median_pos
k_waste = dif_range * dif[x]
if k_waste > k:
stop = increase_pos[x]
break
increased += dif[x]
k -= k_waste
stop = increase_pos[x] + 1
num = stop - size//2
times = k // num
result = increased + array[median_pos] + times
print(result)
```
| 120 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
n,k = map(int,input().split())
arr = sorted(list(map(int,input().split())))
mid = n // 2
##dif = []
##for i in range(mid+1,n):
## dif.append(arr[i]-arr[i-1])
q = 1
i = 0
ans = arr[mid]
while mid+1 < n:
for i in arr[mid+1:]:
if i != ans:
break
q += 1
mid += 1
if k - q * (i-ans) < 0:
break
k = k - q * (i-ans)
ans = i
if k > 0 and k // q:
ans = ans + k // q
print(ans)
```
Yes
| 121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
r = k
m = (n-1)//2
p = m + 1
v = a[m]
while p < n:
u = (p-m) * (a[p]-v)
if u <= r:
v = a[p]
r -= u
else:
break
p += 1
d = r // (p-m)
u = d * (p-m)
r -= u
v = v + d
print(v)
```
Yes
| 122 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
n,k = list(map(int, input().split()))
a = list(map(int, input().split()))
if n==1:
print(a[0]+k)
exit(0)
a = sorted(a)
a = a[int(n/2):]+[10**10]
n= int(n/2)+2
m, next = a[0], a[1]
ans,nans = m,1
while k>0:
dx = k/nans
dy = next - ans
if dx<=dy:
ans = ans + dx
break
k -= dy*nans
ans = next
nans +=1
next = a[nans]
print(int(ans))
```
Yes
| 123 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
def fun(X):
Moves = 0
for i in range(int(N//2),N):
if(X-List[i]>0):
Moves += X- List[i]
if(Moves>K):
return False
return True
N,K = map(int,input().split())
List = [int(x) for x in input().split()]
List.sort()
Big = 2 * (10**9)
Small = 0
while(Small!=Big):
mid = (Small + Big +1) //2
if(fun(mid)):
Small = mid
else:
Big = mid-1
print(Small)
```
Yes
| 124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
n, k = map(int, input().split())
a = sorted(list(map(int, input().split())))
a = a[(len(a) // 2):]
m = 0
while m + 1 < len(a) and k - (a[m + 1] - a[0]) * (m + 1) >= 0:
k -= (a[m + 1] - a[0]) * (m + 1)
a[0] = a[m + 1]
m += 1
#print(a[0], k)
#print(a[0])
a[0] += k // len(a)
print(a[0])
```
No
| 125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
#def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
#for ad in range(int(input())):
n,k=get_ints()
l=list(get_ints())
s=0
for i in range(n//2,n):
s+=l[i]
if (l[i]*(i-n//2+1)-s)>k:
break
x=(i-n//2)
if i!=n+1:s-=l[i]
y=(k+s)//x
print(y)
```
No
| 126 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
import atexit
import io
import sys
# _INPUT_LINES = sys.stdin.read().splitlines()
# input = iter(_INPUT_LINES).__next__
# _OUTPUT_BUFFER = io.StringIO()
# sys.stdout = _OUTPUT_BUFFER
#
#
# @atexit.register
# def write():
# sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
R = lambda:map(int,input().split())
n,k = R()
lst1 = list(R())
id = n//2
lst1.sort()
for i in range(id,n-1):
if k-(lst1[i+1]-lst1[i])*(i+1-id)>0:
print((lst1[i]+k//(i+1-id)))
exit()
else:
k-=(lst1[i+1]-lst1[i])*(i+1-id)
print(lst1[-1]+k//(n-id))
```
No
| 127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of n integers, where n is odd. You can make the following operation with it:
* Choose one of the elements of the array (for example a_i) and increase it by 1 (that is, replace it with a_i + 1).
You want to make the median of the array the largest possible using at most k operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1, 5, 2, 3, 5] is 3.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2 ⋅ 10^5, n is odd, 1 ≤ k ≤ 10^9) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Output
Print a single integer — the maximum possible median after the operations.
Examples
Input
3 2
1 3 5
Output
5
Input
5 5
1 2 1 1 1
Output
3
Input
7 7
4 1 2 4 3 4 4
Output
5
Note
In the first example, you can increase the second element twice. Than array will be [1, 5, 5] and it's median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5, 1, 2, 5, 3, 5, 5] and the median will be 5.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
# 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations, combinations
from math import gcd
from bisect import bisect
input = lambda: sys.stdin.readline().rstrip("\r\n")
read = lambda: list(map(int, input().strip().split(" ")))
def solve():
n, k = read(); arr = read(); arr.sort()
midi = n//2
x = sum([i for i in arr[midi:]])
lo, hi = arr[midi], 10**9 * 2
last = 0
while lo <= hi:
mid = (lo+hi)//2
# print(mid, mid*(midi + 1), x, mid*(midi + 1) - x <= k)
if mid*(midi + 1) - x <= k:
last = mid
lo = mid+1
else:
hi = mid-1
print(last)
if __name__ == "__main__":
solve()
```
No
| 128 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = list(input())
b = list(input())
ml = []
for i in range(n-1):
if a[i] != b[i]:
if a[i] in a[i+1:]:
ind = i+1+a[i+1:].index(a[i])
b[i], a[ind] = a[ind], b[i]
ml.append((ind+1, i+1))
elif a[i] in b[i+1:]:
ind1 = i+1+b[i+1:].index(a[i])
a[i+1], b[ind1] = b[ind1], a[i+1]
b[i], a[i+1] = a[i+1], b[i]
ml.append((i+2, ind1+1))
ml.append((i+2, i+1))
else:
break
if a == b:
print('Yes')
print(len(ml))
for i in ml:
print(*i)
else:
print("No")
```
| 129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, deque
from bisect import bisect_left
from itertools import product
#input = stdin.buffer.readline
T = int(input())
for _ in range(T):
n = int(input())
a, b = list(input()), list(input())
cc = Counter(a+b)
if any([u%2 for u in cc.values()]):
print("No"); continue
res = []
for i in range(n):
if a[i] == b[i]: continue
if a[i] in a[i+1:]:
p = a[i+1:].index(a[i])
b[i], a[i+p+1] = a[i+p+1], b[i]
res.append((i+p+1, i))
else:
p = b[i+1:].index(a[i])
a[i+1], b[i+p+1] = b[i+p+1], a[i+1]
a[i+1], b[i] = b[i], a[i+1]
res.append((i+1, i+p+1))
res.append((i+1, i))
print("Yes")
print(len(res))
for u, v in res:
print(str(u+1)+' '+str(v+1))
```
| 130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
na = list(input())
nb = list(input())
k=0
zz = len(na)
ans = []
for i in range(zz):
f = 0
if(na[i]==nb[i]):
f= 1
if(not f):
for j in range(i+1,zz):
if(na[j]==na[i]):
ans.append((j+1,i+1))
na[j] = nb[i]
f = 1
break
if(not f):
for j in range(i+1,zz):
if(na[i]==nb[j]):
ans.append((j+1,j+1))
ans.append((j+1,i+1))
nb[j] = na[j]
na[j] = nb[i]
f = 1
break
#print(na,nb)
if(not f):
k =1
break
if(k):
print("NO")
else:
print("YES")
print(len(ans))
for t in ans:
print(t[0],t[1])
```
| 131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
T = int(input())
for t in range(T):
N = int(input())
s = list(input())
t = list(input())
i = 0
possible = True
res = []
while i < N:
# print("i : ", i)
# print("res : ", res)
# print("s[i], t[i] : ", s[i], t[i])
if s[i] != t[i]:
# Find index j such that s[i] == s[j] or s[i] == t[j]
# If no such j, then impossible
j = i + 1
found = False
while j < N:
# print("j : ", j)
# Then we just swap sj with ti
if s[i] == s[j]:
res.append((j, i))
s[j], t[i] = t[i], s[j]
found = True
break
# Then we first swap sj with tj
# Then sj with ti
elif s[i] == t[j]:
res.append((j, j))
s[j], t[j] = t[j], s[j]
res.append((j, i))
s[j], t[i] = t[i], s[j]
found = True
break
j += 1
if not (found):
possible = False
break
i += 1
if possible:
print("Yes")
print(len(res))
for i, j in res:
print(i + 1, j + 1)
else:
print("No")
```
| 132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
lis=[0]*2
lis[0]=list(input())
lis[1]=list(input())
ans=[]
gg=0
for i in range(n):
a=lis[0][i]
ind=-1
for j in range(i+1,n):
if a==lis[0][j]:
ind=j
break
if ind!=-1:
ans.append([ind+1,i+1])
lis[1][i],lis[0][ind]=lis[0][ind],lis[1][i]
else:
for j in range(i,n):
if a==lis[1][j]:
ind=j
break
if ind!=-1:
ans.append([n,ind+1])
ans.append([n,i+1])
lis[1][ind],lis[0][n-1]=lis[0][n-1],lis[1][ind]
lis[1][i],lis[0][n-1]=lis[0][n-1],lis[1][i]
else:
print("No")
gg=1
break
if gg==0:
print("Yes")
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
```
| 133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
import sys
for t in range(int(sys.stdin.readline())):
n = int(sys.stdin.readline())
s1 = [ord(c) - 97 for c in sys.stdin.readline().strip()]
s2 = [ord(c) - 97 for c in sys.stdin.readline().strip()]
pl = []
orde = True
for i in range(26):
st1 = {j for j in range(n) if s1[j] == i}
st2 = {j for j in range(n) if s2[j] == i}
if len(st2) > len(st1):
st1, st2 = st2, st1
s1, s2 = s2, s1
orde = not orde
# stb = set()
rml = []
for el in st2:
if el in st1:
rml.append(el)
for el in rml:
st1.remove(el)
st2.remove(el)
tot = len(st1) + len(st2)
if (tot) & 1:
pl = []
break
# op = -1
# for j in range(25):
# if s2[j] != i:
# op = j
# break
# if op == -1:
# continue
# k = len(st1)//2
# for j in range(k):
# k1 = st1.pop()
# k2 = st1.pop()
# op1 = -1
# while len(st1) > 2:
# k1 = st1.pop()
# k2 = st1.pop()
# pl.append((k1, k2) if orde else (k2, k1))
# s1[k1], s2[k2] = s2[k2], s1[k1]
for k in st2:
st1.add(k)
pl.append((k, k))
s1[k], s2[k] = s2[k], s1[k]
for j in range(tot//2):
k1 = st1.pop()
k2 = st1.pop()
pl.append((k1, k2) if orde else (k2, k1))
s1[k1], s2[k2] = s2[k2], s1[k1]
if pl == []:
print("No")
else:
print(f"Yes\n{len(pl)}\n" + "".join([f"{tup[0] + 1} {tup[1] + 1}\n" for tup in pl]))
```
| 134 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
from collections import defaultdict
# input = sys.stdin.readline
def case():
n = int(input())
s = input()
s = [i for i in s]
t = input()
t = [i for i in t]
d= defaultdict(int)
for i in s:
d[i]+=1
for i in t:
d[i]+=1
for i in d.values():
if i%2:
print("NO")
return
ans = []
for i in range(n):
flag = 0
for j in range(i+1, n):
if s[i] == s[j]:
t[i], s[j] = s[j], t[i]
ans.append([j+1, i+1])
flag = 1
break
if flag:
continue
for j in range(i+1, n):
if s[i] == t[j]:
s[j], t[j] = t[j], s[j]
ans.append([j+1, j+1])
t[i], s[j] = s[j], t[i]
ans.append([j+1, i+1])
flag = 1
break
if flag:
continue
print("YES")
print(len(ans))
for i in ans:
print(*i)
for _ in range(int(input())):
case()
```
| 135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Tags: strings
Correct Solution:
```
import sys
input = sys.stdin.readline
for q in range(int(input())):
N = int(input())
s = list(input().rstrip())
t = list(input().rstrip())
ans = []
for i in range(N-1):
if s[i] != t[i]:
for j in range(i + 1, N):
if s[j] == s[i]:
ans.append((j + 1, i + 1))
s[j], t[i] = t[i], s[j]
break
if t[j] == s[i]:
ans.append((i + 2, j + 1))
s[i + 1], t[j] = t[j], s[i + 1]
ans.append((i + 2, i + 1))
s[i + 1], t[i] = t[i], s[i + 1]
break
flag = True
for i in range(N):
if s[i] != t[i]: flag = False
if flag and ans:
print("Yes")
print(len(ans))
for u,v in ans:
print(u, v)
else:
print("No")
```
| 136 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
lis=[0]*2
lis[0]=list(input())
lis[1]=list(input())
# print(lis)
ans=[]
gg=0
for i in range(n):
a=lis[0][i]
ind=-1
for j in range(i+1,n):
if a==lis[0][j]:
ind=j
break
if ind!=-1:
ans.append([ind+1,i+1])
# lis[0][ind],lis[0][n-1]==lis[0][n-1],lis[0][ind]
# print(lis[1][i],lis[0][ind])
lis[1][i],lis[0][ind]=lis[0][ind],lis[1][i]
# print(lis[1][i],lis[0][ind])
else:
for j in range(i,n):
if a==lis[1][j]:
ind=j
break
if ind!=-1:
ans.append([n,ind+1])
ans.append([n,i+1])
# print(lis[1][ind],lis[0][n-1],ind,n-1)
lis[1][ind],lis[0][n-1]=lis[0][n-1],lis[1][ind]
# print(lis[1][ind],lis[0][n-1])
lis[1][i],lis[0][n-1]=lis[0][n-1],lis[1][i]
# print(lis[1][ind],lis[0][n-1])
else:
print("No")
gg=1
break
# print(lis,i)
if gg==0:
print("Yes")
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
```
Yes
| 137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = list(input())
t = list(input())
ans = []
for i in range(n):
if s[i]!=t[i]:
for j in range(i+1,n):
if s[i]==s[j]:
ans.append([j+1,i+1])
t[i],s[j] = s[j],t[i]
break
elif s[i]==t[j]:
ans.append([j+1,j+1])
s[j],t[j] = t[j],s[j]
ans.append([j+1,i+1])
t[i],s[j] = s[j],t[i]
break
flag = True
for i in range(n):
if s[i]!=t[i]:
flag = False
print('No')
break
if flag:
pp = len(ans)
print('Yes')
print(pp)
for i in range(pp):
print(*ans[i])
```
Yes
| 138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = input()
t = input()
d = {}
for i in range(ord('a'), ord('z') + 1):
d[chr(i)] = 0
for cs in s:
d[cs] += 1
for ct in t:
d[ct] += 1
ok = True
for e in d:
if d[e] % 2 == 1:
ok = False
if not ok:
print("No")
else:
print("Yes")
changes = []
s, t = list(s), list(t)
for i in range(n-1):
if s[i] != t[i]:
r = (0, -1)
for j in range(i+1, n):
if s[j] == t[i]:
r = (j, 0)
for j in range(i+1, n):
if t[j] == t[i]:
r = (j, 1)
if r[1] == 0:
changes += [(r[0], i+1), (i, i+1)]
s[r[0]], t[i+1] = t[i+1], s[r[0]]
s[i], t[i+1] = t[i+1], s[i]
elif r[1] == 1:
changes += [(i, r[0])]
s[i], t[r[0]] = t[r[0]], s[i]
print(len(changes))
for change in changes:
x, y = change
print(x+1, y+1)
```
Yes
| 139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for i in range(int(input())):
a, s, t = int(input()), input(), input()
if len([False for n in [(s+t).count(i) for i in set(s+t)] if n%2]):
print('No')
else:
print('Yes')
s = [' '] + [i for i in s]
t = [' '] + [i for i in t]
c = []
while len(s):
#print(s, t)
r, d = s.pop(), t.pop()
if r!=d:
#print(r, d)
try:
#print(t)
n = t.index(d)
c.append(str(len(s)) + ' ' + str(n))
t[n] = r
except:
c.append(str(len(s)) + ' ' + str(len(s)))
#print(t, s, r, d)
n = s.index(d)
c.append(str(n) + ' ' + str(len(s)))
s[n] = r
print(len(c))
for i in c:
print(i)
```
Yes
| 140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
na = list(input())
nb = list(input())
k=0
zz = len(na)
ans = []
for i in range(zz):
f = 0
if(na[i]==nb[i]):
f= 1
for j in range(i+1,zz):
if(na[j]==na[i]):
ans.append((i,j))
na[j] = nb[i]
f = 1
break
if(not f):
for j in range(i+1,zz):
#print(nb[i])
if(na[i]==nb[j]):
ans.append((j,j))
ans.append((i,j))
nb[j] = na[j]
na[j] = nb[i]
f = 1
break
#print(na,nb)
if(not f):
k =1
break
if(k):
print("NO")
else:
print("YES")
print(len(ans))
for t in ans:
print(t[0]+1,t[1]+1)
```
No
| 141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
cases = int(input())
for _ in range(cases):
n = int(input())
s1 = list(input())
s2 = list(input())
swaps = 0
order = []
i = 0
again = False
while i < n and swaps < 2*n:
if s1[i] == s2[i]:
i += 1
else:
if i == n-1:
swaps = 2*n+1
else:
if not again:
for j in range(i+1, n):
if s1[i] == s1[j]:
s2[i], s1[j] = s1[j], s2[i]
swaps += 1
order.append((j, i))
break
elif s2[i] == s2[j]:
s1[i], s2[j] = s2[j], s1[i]
swaps += 1
order.append((i, j))
break
elif j == n-1:
again = True
else:
for j in range(i+1, n):
if s2[i] != s1[j]:
s2[i], s1[j] = s1[j], s2[i]
swaps += 1
order.append((j, i))
again = False
break
elif s1[i] != s2[j]:
s1[i], s2[j] = s2[j], s1[i]
swaps += 1
order.append((i, j))
again = False
break
if again:
swaps = 2*n+1
if swaps >= 2*n:
print('No')
else:
print('Yes')
print(swaps)
for a, b in order:
print(a+1, b+1)
```
No
| 142 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
k = int(input())
for I in range(k):
n = int(input())
s0 = input()
t0 = input()
s = [s0[i] for i in range(n)]
t = [t0[i] for i in range(n)]
ans = "Yes"
ansArr = []
# print(s, t)
for i in range(n):
if s[i] == t[i]:
continue
elif s[i] in s[i+1:]:
ind = s.index(s[i], i+1, n)
# ansArr += [[ind, i]]
ansArr += [[ind+1, i+1]]
s[ind], t[i] = t[i], s[ind]
elif s[i] in t[i+1:]:
ind = t.index(s[i], i+1, n)
# ansArr += [[i+1, ind]]
ansArr += [[i+1+1, ind+1]]
s[i+1], t[ind] = t[ind], s[i+1]
# print(ansArr[-1])
# print(s, t)
# ansArr += [[i+1, i]]
ansArr += [[i+1+1, i+1]]
s[i+1], t[i] = t[i], s[i+1]
# print(ansArr[-1])
# print(s, t)
else:
ans = "No"
break
print(ans)
if ans == "Yes":
for item in ansArr:
print(item[0], item[1])
```
No
| 143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This problem is different from the easy version. In this version Ujan makes at most 2n swaps. In addition, k ≤ 1000, n ≤ 50 and it is necessary to print swaps themselves. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems.
After struggling and failing many times, Ujan decided to try to clean up his house again. He decided to get his strings in order first.
Ujan has two distinct strings s and t of length n consisting of only of lowercase English characters. He wants to make them equal. Since Ujan is lazy, he will perform the following operation at most 2n times: he takes two positions i and j (1 ≤ i,j ≤ n, the values i and j can be equal or different), and swaps the characters s_i and t_j.
Ujan's goal is to make the strings s and t equal. He does not need to minimize the number of performed operations: any sequence of operations of length 2n or shorter is suitable.
Input
The first line contains a single integer k (1 ≤ k ≤ 1000), the number of test cases.
For each of the test cases, the first line contains a single integer n (2 ≤ n ≤ 50), the length of the strings s and t.
Each of the next two lines contains the strings s and t, each having length exactly n. The strings consist only of lowercase English letters. It is guaranteed that strings are different.
Output
For each test case, output "Yes" if Ujan can make the two strings equal with at most 2n operations and "No" otherwise. You can print each letter in any case (upper or lower).
In the case of "Yes" print m (1 ≤ m ≤ 2n) on the next line, where m is the number of swap operations to make the strings equal. Then print m lines, each line should contain two integers i, j (1 ≤ i, j ≤ n) meaning that Ujan swaps s_i and t_j during the corresponding operation. You do not need to minimize the number of operations. Any sequence of length not more than 2n is suitable.
Example
Input
4
5
souse
houhe
3
cat
dog
2
aa
az
3
abc
bca
Output
Yes
1
1 4
No
No
Yes
3
1 2
3 1
2 3
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
s1=input()
s2=input()
s1=[i for i in s1]
s2=[i for i in s2]
freq={}
for i in s1:
if i not in freq:
freq[i]=0
freq[i]+=1
for i in s2:
if i not in freq:
freq[i]=0
freq[i]+=1
f=True
for i in freq:
if freq[i]%2!=0:
f=False
print('No')
break
if not f:
continue
pos=0
ans=[]
f=True
while pos<len(s1):
if s1[pos]==s2[pos]:
pos+=1
continue
idx=-1
for i in range(pos+1,len(s1)):
if s1[pos]==s1[i]:
idx=i
break
if idx!=-1:
s2[pos],s1[idx]=s1[idx],s2[pos]
ans.append((idx+1,pos+1))
pos+=1
continue
ans.append((pos+1,pos+1))
idx=-1
for i in range(pos+1,len(s1)):
if s2[pos]==s1[i]:
idx=i
break
s1[pos],s2[pos]=s2[pos],s1[pos]
s2[pos],s1[idx]=s1[idx],s2[pos]
ans.append((idx+1,pos+1))
pos+=1
print('Yes')
print(len(ans))
for i in ans:
print(i[0],i[1])
```
No
| 144 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
n = int(input())
for i in range(1, n + 1):
a, b, c = sorted(map(int, input().split()))
if c - a - b > 0:
print(a + b)
elif c - a - b == 0:
print(c)
else:
print(c+(a-c+b)//2)
```
| 145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
for i in range(int(input())):
ll = list(map(int, input().split()))
ll.sort(reverse=True)
count = ll.pop()
x = (ll[0] - ll[1] + count)//2
if (ll[0] - count > ll[1]):
ll[0] -= count
else:
ll[0] -= x; ll[1] -= (count - x)
count += min(ll)
print(count)
```
| 146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
# Paulo Pacitti
# RA 185447
t = int(input())
for i in range(t):
case = [int(e) for e in input().split()]
case.sort(reverse=True)
days = 0
diff = case[0] - case[1]
if diff >= case[2]:
days += case[2]
case[0] -= case[2]
days += min(case[0], case[1])
else:
days += diff
case[0] -= diff
case[2] -= diff
days += (case[2] // 2) + case[1]
print(days)
```
| 147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
import math
for _ in range(int(input())):
l=list(map(int,input().split()))
l.sort()
if l[0]+l[1]<=l[2]:
print(l[0]+l[1])
else:
t=abs(l[1]+l[0]-l[2])
print(min(l[1]+l[0],l[2])+t//2)
```
| 148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
for i in range(int(input())):
arr = [int(i) for i in input().split()]
arr.sort()
mn = arr[0]
diff = min(arr[2] - arr[1], arr[0])
x = (arr[0] - diff)//2
arr[1] -= x
arr[2] -= (arr[0] - x)
ans = min(arr[1], arr[2]) + mn
print(ans)
```
| 149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
for _ in range(int(input())):
a,b,c=sorted(map(int,input().split()),reverse=True)
if a<=b+c:
print((a+b+c)//2)
else:
print(b+c)
```
| 150 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
import math
N = int(input())
while N > 0:
a = input().split()
a[0] = int(a[0])
a[1] = int(a[1])
a[2] = int(a[2])
if a[0] > a[1]:
a[0],a[1] = a[1],a[0]
if a[0] > a[2]:
a[0],a[2] = a[2],a[0]
if a[1] > a[2]:
a[1],a[2] = a[2],a[1]
N-=1
if a[0] + a[1] >= a[2]:
print(math.floor((a[0] + a[1] + a[2]) / 2))
elif a[2] > a[0] + a[1]:
print(a[0] + a[1])
# print(a)
```
| 151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Tags: math
Correct Solution:
```
# balance
t = int(input())
for case in range(t):
arr = list(map(int, input().split()))
arr.sort()
d = arr[2] - arr[1]
if d >= arr[0]:
print(arr[0] + arr[1])
else: # d < arr[0]
arr[0] -= d
# arr[2] = arr[1]
if arr[0] & 1:
print(d + arr[1] + arr[0] - (arr[0] >> 1) - 1)
else:
print(d + arr[1] + arr[0] - (arr[0] >> 1))
```
| 152 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
for i in range(int(input())):
l=sorted(list(map(int,input().split())))
if l[0]+l[1]<=l[2]:
print(l[0]+l[1])
else:
print(sum(l)//2)
```
Yes
| 153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
n = int(input())
for i in range(n):
a,b,c = map(int,input().split())
a,b,c = sorted([a,b,c])
res = 0
if c >= b - a:
res += b - a
c -= b - a
b = a
mx = min(a, c // 2)
res += mx * 2
c -= mx * 2
a -= mx
b -= mx
res += a
print(res)#, a, b, c)
```
Yes
| 154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
for _ in range(int(input())):
l = list(map(int,input().split()))
l.sort()
print(min(sum(l)//2,l[0]+l[1]))
```
Yes
| 155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
T = int(input())
def solve(r, g, b):
r, g, b = list(sorted([r, g, b]))
#print(r, g, b)
eaten = 0
eaten += g-r
r, g, b = r, g-eaten, b-eaten
#print(r, g, b, "eaten = ", eaten)
k = min(b - g, g, b//2)
eaten += 2*k
r, g, b = r-k, g-k, b-2*k # b - 2*(b - g) =
#print(r, g, b, "eaten = ", eaten)
if r == 0: return eaten
else:
assert r == b
return eaten + (r+g+b) // 2
#print("----")
def sim(r, g, b):
r, g, b = list(sorted([r, g, b]))
eaten = 0
while g != 0:
g, b = g-1, b-1
eaten += 1
r, g, b = list(sorted([r, g, b]))
return eaten
#for r in range(100):
# for g in range(100):
# for b in range(100):
# assert sim(r, g, b) == solve(r, g, b)
#print("sim ok")
for _ in range(T):
r, g, b = [int(x) for x in input().split()]
print(solve(r, g, b))
```
Yes
| 156 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
t = int(input())
for i in range (t):
a=sorted(list(map(int,input().split())))
if a[0]==a[1] and a[1]==a[2] and a[0]==a[2]:
print(int(a[0]))
continue
elif a[1]==a[2]:
print(a[0]+min(a[2]-int(a[0]/2),a[1]-(a[0]%2)))
#print(int(a[0]+((2*a[1]-a[0])/2)))
continue
else:
print(a[1]+min(a[0],a[2]-a[1]))
continue
```
No
| 157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
t=int(input())
for i in range(0,t):
r=list(map(int,input().split()))
if(((r[0]==r[1]) and (r[1]==r[2]))or((r.count(1)==0)and(sum(r)%2==0))):
s=(r[0]+r[1]+r[2])//2
print(s)
continue
else:
if(r.count(max(r))==2):
print(sum(r)//2)
continue
else:
k=r[r.index(max(r))]
r[r.index(max(r))]=0
print(min(sum(r),k))
continue
```
No
| 158 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
t = int(input())
for i in range(t):
ans = 0
a = list(map(int, input().split()))
if a.count(max(a)) == 1:
mi = min(a)
a.pop(a.index(mi))
ma = max(a)
a[a.index(ma)] -= mi
ans += mi
mi = min(a)
ans += mi
elif a.count(max(a)) == 3:
ans += sum(a) // 2
else:
mi = min(a)
a.pop(a.index(mi))
mi1 = mi // 2
a[0] -= mi1
a[1] -= mi1
a[0] -= (mi % 2)
ans += mi + min(a)
print(ans)
```
No
| 159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have three piles of candies: red, green and blue candies:
* the first pile contains only red candies and there are r candies in it,
* the second pile contains only green candies and there are g candies in it,
* the third pile contains only blue candies and there are b candies in it.
Each day Tanya eats exactly two candies of different colors. She is free to choose the colors of eaten candies: the only restriction that she can't eat two candies of the same color in a day.
Find the maximal number of days Tanya can eat candies? Each day she needs to eat exactly two candies.
Input
The first line contains integer t (1 ≤ t ≤ 1000) — the number of test cases in the input. Then t test cases follow.
Each test case is given as a separate line of the input. It contains three integers r, g and b (1 ≤ r, g, b ≤ 10^8) — the number of red, green and blue candies, respectively.
Output
Print t integers: the i-th printed integer is the answer on the i-th test case in the input.
Example
Input
6
1 1 1
1 2 1
4 1 1
7 4 10
8 1 4
8 2 8
Output
1
2
2
10
5
9
Note
In the first example, Tanya can eat candies for one day only. She can eat any pair of candies this day because all of them have different colors.
In the second example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and green and blue candies on the second day.
In the third example, Tanya can eat candies for two days. For example, she can eat red and green candies on the first day, and red and blue candies on the second day. Note, that two red candies will remain uneaten.
Submitted Solution:
```
for _ in range(int(input())):
a = list(map(int,input().split()))
a.sort()
ans = 0
ans+= a[1]-1
a[2] -= a[1]-1
a[1]=1
a.sort()
ans+= a[1]-1
a[2] -= a[1]-1
a[1]=1
if a[2]>=2:
ans+=2
else:
ans+=1
print(ans)
```
No
| 160 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
ke = 133333333
pp = 1000000000001003
def rand():
global ke
ke = ke ** 2 % pp
return ((ke >> 10) % (1<<15)) + (1<<15)
N = int(input())
W = [rand() for _ in range(N)]
A = []
B = []
for i in range(N):
a, b, c, d = map(int, input().split())
A.append((a+1, b+2, i))
B.append((c+1, d+2, i))
def chk(L):
# NN = 18
BIT = [0] * (200200)
BITC = [0] * (200200)
SS = [0]
CC = [0]
def addrange(r0, x=1):
r = r0
SS[0] += x
CC[0] += 1
while r <= 200200:
BIT[r] -= x
BITC[r] -= 1
r += r & (-r)
def getvalue(r):
a = 0
c = 0
while r != 0:
a += BIT[r]
c += BITC[r]
r -= r&(-r)
return (SS[0] + a, CC[0] + c)
S = []
for a, b, i in L:
S.append(a)
S.append(b)
S = sorted(list(set(S)))
D = {s:i for i, s in enumerate(S)}
L = [(D[a], D[b], i) for a, b, i in L]
s = 0
L = sorted(L)
m = -1
for a, b, i in L:
v, c = getvalue(a)
s += v + c * W[i]
addrange(b, W[i])
return s
print("YES" if chk(A) == chk(B) else "NO")
```
| 161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
MOD = 10**18+13
import sys
readline = sys.stdin.readline
from random import randrange
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2, 1)}
return L2, C
N = int(readline())
T = set()
L = [None]*N
for i in range(N):
L[i] = tuple(map(int, readline().split()))
T |= set(L[i])
t2, C = compress(list(T))
Z = len(t2)
L = [[j] + [C[L[j][i]] for i in range(4)] for j in range(N)]
seed = []
while len(set(seed)) != N:
seed = [randrange(1, MOD) for _ in range(N)]
S1 = [0]*(Z+2)
S2 = [0]*(Z+2)
S3 = [0]*(Z+2)
S4 = [0]*(Z+2)
p1 = [0]*N
p2 = [0]*N
for i in range(N):
j, s1, t1, s2, t2 = L[i]
S1[s1] += seed[j]
S2[t1] += seed[j]
S3[s2] += seed[j]
S4[t2] += seed[j]
for i in range(1, Z+1):
S1[i] = (S1[i] + S1[i-1])%MOD
S2[i] = (S2[i] + S2[i-1])%MOD
S3[i] = (S3[i] + S3[i-1])%MOD
S4[i] = (S4[i] + S4[i-1])%MOD
for i in range(N):
j, s1, t1, s2, t2 = L[i]
p1[j] = (S2[s1-1] - S1[t1])%MOD
p2[j] = (S4[s2-1] - S3[t2])%MOD
print('YES' if all(a == b for a, b in zip(p1, p2)) else 'NO')
```
| 162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
W = [(i+12345)**2 % 998244353 for i in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
D = {s:i for i, s in enumerate(sorted(list(set(L + R))))}
X = [0] * 200200
for i, l in enumerate(L): X[D[l]] += W[i]
for i in range(1, 200200): X[i] += X[i-1]
return sum([X[D[r]] * W[i] for i, r in enumerate(R)])
print("YES" if chk(AL, AR) == chk(BL, BR) else "NO")
```
| 163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq
n=int(input())
C=[tuple(map(int,input().split())) for i in range(n)]
CA=[]
CB=[]
for ind,(a,b,c,d) in enumerate(C):
CA.append((a,0,ind))
CA.append((b,1,ind))
CB.append((c,0,ind))
CB.append((d,1,ind))
CA.sort()
CB.sort()
SMAX=[]
EMIN=[]
FINISHED=[0]*n
for time,flag,ind in CA:
if flag==0:
heapq.heappush(SMAX,(-C[ind][2],ind))
heapq.heappush(EMIN,(C[ind][3],ind))
while FINISHED[SMAX[0][1]]:
heapq.heappop(SMAX)
while FINISHED[EMIN[0][1]]:
heapq.heappop(EMIN)
if -SMAX[0][0]>EMIN[0][0]:
print("NO")
sys.exit()
else:
FINISHED[ind]=1
SMAX=[]
EMIN=[]
FINISHED=[0]*n
for time,flag,ind in CB:
if flag==0:
heapq.heappush(SMAX,(-C[ind][0],ind))
heapq.heappush(EMIN,(C[ind][1],ind))
while FINISHED[SMAX[0][1]]:
heapq.heappop(SMAX)
while FINISHED[EMIN[0][1]]:
heapq.heappop(EMIN)
if -SMAX[0][0]>EMIN[0][0]:
print("NO")
sys.exit()
else:
FINISHED[ind]=1
print("YES")
```
| 164 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
MOD = 10**18+13
import sys
readline = sys.stdin.readline
from random import randrange
def compress(L):
L2 = list(set(L))
L2.sort()
C = {v : k for k, v in enumerate(L2, 1)}
return L2, C
N = int(readline())
T = set()
L = [None]*N
for i in range(N):
L[i] = tuple(map(int, readline().split()))
T |= set(L[i])
t2, C = compress(list(T))
Z = len(t2)
L = [[j] + [C[L[j][i]] for i in range(4)] for j in range(N)]
seed = [0]*N
base = randrange(3, MOD)
seed[0] = base
for i in range(1, N):
seed[i] = (seed[i-1]*base)%MOD
S1 = [0]*(Z+2)
S2 = [0]*(Z+2)
S3 = [0]*(Z+2)
S4 = [0]*(Z+2)
p1 = [0]*N
p2 = [0]*N
for i in range(N):
j, s1, t1, s2, t2 = L[i]
S1[s1] += seed[j]
S2[t1] += seed[j]
S3[s2] += seed[j]
S4[t2] += seed[j]
for i in range(1, Z+1):
S1[i] = (S1[i] + S1[i-1])%MOD
S2[i] = (S2[i] + S2[i-1])%MOD
S3[i] = (S3[i] + S3[i-1])%MOD
S4[i] = (S4[i] + S4[i-1])%MOD
for i in range(N):
j, s1, t1, s2, t2 = L[i]
p1[j] = (S2[s1-1] - S1[t1])%MOD
p2[j] = (S4[s2-1] - S3[t2])%MOD
print('YES' if all(a == b for a, b in zip(p1, p2)) else 'NO')
```
| 165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
from operator import itemgetter
import sys
import bisect
input = sys.stdin.readline
class BIT():
"""区間加算、区間取得クエリをそれぞれO(logN)で答える
add: 区間[l, r)にvalを加える
get_sum: 区間[l, r)の和を求める
l, rは0-indexed
"""
def __init__(self, n):
self.n = n
self.bit0 = [0] * (n + 1)
self.bit1 = [0] * (n + 1)
def _add(self, bit, i, val):
i = i + 1
while i <= self.n:
bit[i] += val
i += i & -i
def _get(self, bit, i):
s = 0
while i > 0:
s += bit[i]
i -= i & -i
return s
def add(self, l, r, val):
"""区間[l, r)にvalを加える"""
self._add(self.bit0, l, -val * l)
self._add(self.bit0, r, val * r)
self._add(self.bit1, l, val)
self._add(self.bit1, r, -val)
def get_sum(self, l, r):
"""区間[l, r)の和を求める"""
return self._get(self.bit0, r) + r * self._get(self.bit1, r) \
- self._get(self.bit0, l) - l * self._get(self.bit1, l)
#座標圧縮したリストを返す
def compress(array):
n = len(array)
m = len(array[0])
set_ = set()
for i in array:
for j in i:
set_.add(j)
array2 = sorted(set_)
memo = {value : index for index, value in enumerate(array2)}
for i in range(n):
for j in range(m):
array[i][j] = memo[array[i][j]]
return array, len(memo)
n = int(input())
info = [list(map(int, input().split())) for i in range(n)]
info, m = compress(info)
"""
for i in range(n):
a1, a2, b1, b2 = info[i]
for j in range(i+1, n):
c1, c2, d1, d2 = info[j]
if (max(a1, c1) <= min(a2, c2)) ^ (max(b1, d1) <= min(b2, d2)):
print(2)
"""
info = sorted(info, key = itemgetter(0))
bi = [None] * n
for i in range(n):
bi[i] = (i, info[i][1])
bi = sorted(bi, key = itemgetter(1))
bii = [v for i, v in bi]
bit = BIT(m)
tmp = 0
for i in range(n):
l, r, l2, r2 = info[i]
ind = bisect.bisect_left(bii, l)
while tmp < ind:
ii = bi[tmp][0]
bit.add(info[ii][2], info[ii][3] + 1, 1)
tmp += 1
if bit.get_sum(l2, r2 + 1) >= 1:
print("NO")
exit()
for i in range(n):
info[i][0], info[i][1], info[i][2], info[i][3] = info[i][2], info[i][3], info[i][0], info[i][1]
info = sorted(info, key = itemgetter(0))
bi = [None] * n
for i in range(n):
bi[i] = (i, info[i][1])
bi = sorted(bi, key = itemgetter(1))
bii = [v for i, v in bi]
bit = BIT(m)
tmp = 0
for i in range(n):
l, r, l2, r2 = info[i]
ind = bisect.bisect_left(bii, l)
while tmp < ind:
ii = bi[tmp][0]
bit.add(info[ii][2], info[ii][3] + 1, 1)
tmp += 1
if bit.get_sum(l2, r2 + 1) >= 1:
print("NO")
exit()
print("YES")
```
| 166 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
W = [(i+1000007)**3 % 998244353 for i in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
D = {s:i for i, s in enumerate(sorted(list(set(L + R))))}
X = [0] * 200200
for i, l in enumerate(L): X[D[l]] += W[i]
for i in range(1, 200200): X[i] += X[i-1]
return sum([X[D[r]] * W[i] for i, r in enumerate(R)])
print("YES" if chk(AL, AR) == chk(BL, BR) else "NO")
```
| 167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Tags: binary search, data structures, hashing, sortings
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
from bisect import bisect_right as br
ke = 1333333333
pp = 1000000000001003
def rand():
global ke
ke = ke ** 2 % pp
return ((ke >> 10) % (1<<15)) + (1<<15)
N = int(input())
W = [rand() for _ in range(N)]
A = []
B = []
for i in range(N):
a, b, c, d = map(int, input().split())
A.append((a+2, b+3, i))
B.append((c+2, d+3, i))
def chk(L):
S = [1]
for a, b, i in L:
S.append(b)
S = sorted(list(set(S)))
D = {s:i for i, s in enumerate(S)}
L = [(D[S[br(S, a)-1]], D[b], i) for a, b, i in L]
L = sorted(L)
nn = 101010
BIT = [0] * nn
BITC = [0] * nn
SS = [0]
CC = [0]
def addrange(r0, x=1):
r = r0
SS[0] += x
CC[0] += 1
while r <= nn:
BIT[r] -= x
BITC[r] -= 1
r += r & (-r)
def getvalue(r):
a = 0
c = 0
while r != 0:
a += BIT[r]
c += BITC[r]
r -= r&(-r)
return (SS[0] + a, CC[0] + c)
s = 0
m = -1
for a, b, i in L:
v, c = getvalue(a)
s += v + c * W[i]
addrange(b, W[i])
return s
print("YES" if chk(A) == chk(B) else "NO")
```
| 168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
import time
a = time.time()
ke = (int(a*2**20) % (2**20)) + (2**20)
pp = 100001000000000000021
def rand():
global ke
ke = ke ** 2 % pp
return ((ke >> 30) % (1<<15)) + (1<<15)
N = int(input())
W = [rand() for _ in range(N)]
A = []
B = []
for i in range(N):
a, b, c, d = map(int, input().split())
A.append((a+1, b+2, i))
B.append((c+1, d+2, i))
def chk(L):
NN = 18
BIT=[0]*(2**NN+1)
BITC=[0]*(2**NN+1)
SS = [0]
CC = [0]
def addrange(r0, x=1):
r = r0
SS[0] += x
CC[0] += 1
while r <= 2**NN:
BIT[r] -= x
BITC[r] -= 1
r += r & (-r)
def getvalue(r):
a = 0
c = 0
while r != 0:
a += BIT[r]
c += BITC[r]
r -= r&(-r)
return (SS[0] + a, CC[0] + c)
S = []
for a, b, i in L:
S.append(a)
S.append(b)
S = sorted(list(set(S)))
D = {s:i for i, s in enumerate(S)}
L = [(D[a], D[b], i) for a, b, i in L]
s = 0
L = sorted(L)
m = -1
for a, b, i in L:
v, c = getvalue(a)
s += v + c * W[i]
addrange(b, W[i])
return s
print("YES" if chk(A) == chk(B) else "NO")
```
Yes
| 169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N=100101
n = int(input())
rand = [((i+12345)**3)%998244353 for i in range(N*2+20)]
al,ar,bl,br=[],[],[],[]
for _ in range(n):
a,b,c,d=map(int,input().split())
al.append(a)
ar.append(b)
bl.append(c)
br.append(d)
def calk(l,r):
ma={s:idx for idx,s in enumerate(sorted(list(set(l+r))))}
hash=[0]*N*2
for idx,v in enumerate(l):hash[ma[v]]+=rand[idx]
for i in range(1,N*2):hash[i]+=hash[i-1]
return sum([hash[ma[v]]*rand[idx] for idx,v in enumerate(r)])
print("YES" if calk(al, ar) == calk(bl, br) else "NO")
```
Yes
| 170 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
ke = 133333333
pp = 1000000000001003
def rand():
global ke
ke = ke ** 2 % pp
return ((ke >> 10) % (1<<20)) + (1<<20)
N = int(input())
W = [rand() for _ in range(N)]
AL, AR, BL, BR = [], [], [], []
for i in range(N):
a, b, c, d = map(int, input().split())
AL.append(a)
AR.append(b)
BL.append(c)
BR.append(d)
def chk(L, R):
S = sorted(list(set(L + R)))
D = {s:i for i, s in enumerate(S)}
L = [D[a] for a in L]
R = [D[a] for a in R]
X = [0] * 200200
for i, l in enumerate(L):
X[l] += W[i]
for i in range(1, 200200):
X[i] += X[i-1]
s = 0
for i, r in enumerate(R):
s += X[r] * W[i]
return s
print("YES" if chk(AL, AR) == chk(BL, BR) else "NO")
```
Yes
| 171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
# import threading
from math import inf, log2
from collections import defaultdict
# threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
# sys.setrecursionlimit(300000)
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")
#----------------------------------------------------------------------------------------------------------------
class LazySegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.lazy = [0] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def push(self, index):
"""Push the information of the root to it's children!"""
self.lazy[2*index] += self.lazy[index]
self.lazy[2*index+1] += self.lazy[index]
self.data[2 * index] += self.lazy[index]
self.data[2 * index + 1] += self.lazy[index]
self.lazy[index] = 0
def build(self, index):
"""Build data with the new changes!"""
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1]) + self.lazy[index]
index >>= 1
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
res = self.default
alpha += self.size
omega += self.size + 1
for i in range(len(bin(alpha)[2:])-1, 0, -1):
self.push(alpha >> i)
for i in range(len(bin(omega-1)[2:])-1, 0, -1):
self.push((omega-1) >> i)
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, alpha, omega, value):
"""Increases all elements in the range (inclusive) by given value!"""
alpha += self.size
omega += self.size + 1
l, r = alpha, omega
while alpha < omega:
if alpha & 1:
self.data[alpha] += value
self.lazy[alpha] += value
alpha += 1
if omega & 1:
omega -= 1
self.data[omega] += value
self.lazy[omega] += value
alpha >>= 1
omega >>= 1
self.build(l)
self.build(r-1)
#---------------------------------------------------------------------------------------------
n=int(input())
l=[]
f=0
no=set()
for i in range(n):
a,b,c,d=map(int,input().split())
l.append((a,b,c,d))
no.add(a)
no.add(a+1)
no.add(b+1)
no.add(b)
no.add(c)
no.add(c+1)
no.add(d)
no.add(d+1)
no=sorted(no)
ind=defaultdict(int)
cou=0
for i in no:
ind[i]=cou
cou+=1
l1=[]
for i in range(n):
a,b,c,d=l[i]
a=ind[a]
b=ind[b]
c=ind[c]
d=ind[d]
l[i]=(b,a,c,d)
l1.append((a,b,c,d))
l1.sort(reverse=True)
l.sort(reverse=True)
e=[0]*(10**6)
s=LazySegmentTree(e)
t=0
for i in range(n):
while (t<n and l1[t][1]>l[i][0]):
s.update(l1[t][2],l1[t][3],1)
t+=1
if s.query(l[i][2],l[i][3])>0:
f=1
break
if f==1:
print("NO")
sys.exit(0)
for i in range(n):
b,a,c,d=l[i]
l[i]=(d,c,a,b)
l1[i]=(c,d,a,b)
l1.sort(reverse=True)
l.sort(reverse=True)
e=[0]*(10**6)
s=LazySegmentTree(e)
t=0
for i in range(n):
while(t<n and l1[t][1]>l[i][0]):
s.update(l1[t][2],l1[t][3],1)
t+=1
if s.query(l[i][2],l[i][3])>0:
f=1
break
if f==1:
print("NO")
sys.exit(0)
print("YES")
```
No
| 172 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
def sol(arrl, exit, n):
arrl.sort();
exit.sort();
guests_in = 1;
max_guests = 1;
time = arrl[0];
i = 1;
j = 0;
b=[]
while (i < n and j < n):
if (arrl[i] <= exit[j]):
guests_in = guests_in + 1;
if(guests_in > max_guests):
max_guests = guests_in;
time = arrl[i];
i = i + 1;
else:
guests_in = guests_in - 1;
j = j + 1;
b.append(guests_in)
return b
n=int(input())
sa=[]
ea=[]
sb=[]
eb=[]
for i in range(n):
a,b,c,d=map(int,input().split())
sa.append(a)
ea.append(b)
sb.append(c)
eb.append(d)
x=sol(sa,ea,n)
y=sol(sb,eb,n)
if x!=y:
print('NO')
else:
print('YES')
```
No
| 173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
n = int(input())
t = 0
for i in range (n):
a = list(map(int,input().split()))
if a[2] <= a[0] or a[2] <= a[1] or a[3] <= a[0] or a[3] <= a[1] or a[1] <=a[0] or a[3] <= a[2]:
t += 1
if t >= 2:
print('NO')
else:
print('YES')
```
No
| 174 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Filled with optimism, Hyunuk will host a conference about how great this new year will be!
The conference will have n lectures. Hyunuk has two candidate venues a and b. For each of the n lectures, the speaker specified two time intervals [sa_i, ea_i] (sa_i ≤ ea_i) and [sb_i, eb_i] (sb_i ≤ eb_i). If the conference is situated in venue a, the lecture will be held from sa_i to ea_i, and if the conference is situated in venue b, the lecture will be held from sb_i to eb_i. Hyunuk will choose one of these venues and all lectures will be held at that venue.
Two lectures are said to overlap if they share any point in time in common. Formally, a lecture held in interval [x, y] overlaps with a lecture held in interval [u, v] if and only if max(x, u) ≤ min(y, v).
We say that a participant can attend a subset s of the lectures if the lectures in s do not pairwise overlap (i.e. no two lectures overlap). Note that the possibility of attending may depend on whether Hyunuk selected venue a or venue b to hold the conference.
A subset of lectures s is said to be venue-sensitive if, for one of the venues, the participant can attend s, but for the other venue, the participant cannot attend s.
A venue-sensitive set is problematic for a participant who is interested in attending the lectures in s because the participant cannot be sure whether the lecture times will overlap. Hyunuk will be happy if and only if there are no venue-sensitive sets. Determine whether Hyunuk will be happy.
Input
The first line contains an integer n (1 ≤ n ≤ 100 000), the number of lectures held in the conference.
Each of the next n lines contains four integers sa_i, ea_i, sb_i, eb_i (1 ≤ sa_i, ea_i, sb_i, eb_i ≤ 10^9, sa_i ≤ ea_i, sb_i ≤ eb_i).
Output
Print "YES" if Hyunuk will be happy. Print "NO" otherwise.
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2 3 6
3 4 7 8
Output
YES
Input
3
1 3 2 4
4 5 6 7
3 4 5 5
Output
NO
Input
6
1 5 2 9
2 4 5 8
3 6 7 11
7 10 12 16
8 11 13 17
9 12 14 18
Output
YES
Note
In second example, lecture set \{1, 3\} is venue-sensitive. Because participant can't attend this lectures in venue a, but can attend in venue b.
In first and third example, venue-sensitive set does not exist.
Submitted Solution:
```
n=int(input())
s=[]
t=[]
for i in range(n):
a,b,c,d=map(int,input().split())
s.append([a,b,i])
t.append([c,d,i])
s=sorted(s,key=lambda x:(x[0],-x[1]))
t=sorted(t,key=lambda x:(x[0],-x[1]))
p=[0]*n
q=[0]*n
c,d=[0,0,0],[0,0,0]
for i in range(n):
if s[i][0]<=c[1]:
p[s[i][2]]=1
p[c[2]]=1
c[1]=max(c[1],s[i][1])
else:
c=s[i]
if t[i][0]<=d[1]:
q[t[i][2]]=1
q[d[2]]=1
d[1]=max(d[1],t[i][1])
else:
d=t[i]
if sum(p)==sum(q)==n or sum(p)==sum(q)==0:
print("YES")
else:
print("NO")
```
No
| 175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string S and an array of strings [t_1, t_2, ..., t_k]. Each string t_i consists of lowercase Latin letters from a to n; S consists of lowercase Latin letters from a to n and no more than 14 question marks.
Each string t_i has its cost c_i — an integer number. The value of some string T is calculated as ∑_{i = 1}^{k} F(T, t_i) ⋅ c_i, where F(T, t_i) is the number of occurences of string t_i in T as a substring. For example, F(aaabaaa, aa) = 4.
You have to replace all question marks in S with pairwise distinct lowercase Latin letters from a to n so the value of S is maximum possible.
Input
The first line contains one integer k (1 ≤ k ≤ 1000) — the number of strings in the array [t_1, t_2, ..., t_k].
Then k lines follow, each containing one string t_i (consisting of lowercase Latin letters from a to n) and one integer c_i (1 ≤ |t_i| ≤ 1000, -10^6 ≤ c_i ≤ 10^6). The sum of lengths of all strings t_i does not exceed 1000.
The last line contains one string S (1 ≤ |S| ≤ 4 ⋅ 10^5) consisting of lowercase Latin letters from a to n and question marks. The number of question marks in S is not greater than 14.
Output
Print one integer — the maximum value of S after replacing all question marks with pairwise distinct lowercase Latin letters from a to n.
Examples
Input
4
abc -10
a 1
b 1
c 3
?b?
Output
5
Input
2
a 1
a 1
?
Output
2
Input
3
a 1
b 3
ab 4
ab
Output
8
Input
1
a -1
?????????????
Output
0
Input
1
a -1
??????????????
Output
-1
Submitted Solution:
```
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def Ft(t, ti):
c = 0
for i in range(len(t) - len(ti) + 1):
if t[i:i+len(ti)] == ti:
c += 1
return c
def F(t, d):
v = 0
for elt in d:
v += elt[1] * Ft(t, elt[0])
return v
def solve(d, s, letters):
m = - sys.maxsize - 1
if '?' in s:
for l in letters:
if l not in s or l == 'o' and s.count('o') <= 14 - len(letters):
p = solve(d, s.replace('?', l, 1), letters)
if p > m:
m = p
return m
else:
return F(s, d)
def output():
k = inp()
d = []
missing_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
letters = []
for i in range(k):
t, c = ''.join(insr()).split(' ')
for letter in t:
if letter in missing_letters:
missing_letters.remove(letter)
letters.append(letter)
d.append((t, int(c)))
d.append(('o', 0))
s = ''.join(insr())
letters.append('o')
m = solve(d, s, letters)
print(m)
output()
```
No
| 176 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a string S and an array of strings [t_1, t_2, ..., t_k]. Each string t_i consists of lowercase Latin letters from a to n; S consists of lowercase Latin letters from a to n and no more than 14 question marks.
Each string t_i has its cost c_i — an integer number. The value of some string T is calculated as ∑_{i = 1}^{k} F(T, t_i) ⋅ c_i, where F(T, t_i) is the number of occurences of string t_i in T as a substring. For example, F(aaabaaa, aa) = 4.
You have to replace all question marks in S with pairwise distinct lowercase Latin letters from a to n so the value of S is maximum possible.
Input
The first line contains one integer k (1 ≤ k ≤ 1000) — the number of strings in the array [t_1, t_2, ..., t_k].
Then k lines follow, each containing one string t_i (consisting of lowercase Latin letters from a to n) and one integer c_i (1 ≤ |t_i| ≤ 1000, -10^6 ≤ c_i ≤ 10^6). The sum of lengths of all strings t_i does not exceed 1000.
The last line contains one string S (1 ≤ |S| ≤ 4 ⋅ 10^5) consisting of lowercase Latin letters from a to n and question marks. The number of question marks in S is not greater than 14.
Output
Print one integer — the maximum value of S after replacing all question marks with pairwise distinct lowercase Latin letters from a to n.
Examples
Input
4
abc -10
a 1
b 1
c 3
?b?
Output
5
Input
2
a 1
a 1
?
Output
2
Input
3
a 1
b 3
ab 4
ab
Output
8
Input
1
a -1
?????????????
Output
0
Input
1
a -1
??????????????
Output
-1
Submitted Solution:
```
import sys
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def Ft(t, ti):
c = 0
for i in range(len(t) - len(ti) + 1):
if t[i:i+len(ti)] == ti:
c += 1
return c
def F(t, d):
v = 0
for elt in d:
v += elt[1] * Ft(t, elt[0])
return v
def solve(d, s, letters):
m = - sys.maxsize - 1
if '?' in s:
for l in letters:
if l not in s or l == 'o' and s.count('o') <= 14 - len(letters):
p = solve(d, s.replace('?', l, 1), letters)
if p > m:
m = p
return m
else:
return F(s, d)
def output():
k = inp()
d = []
missing_letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n']
letters = []
for i in range(k):
t, c = ''.join(insr()).split(' ')
for letter in t:
if letter in missing_letters:
missing_letters.remove(letter)
letters.append(letter)
d.append((t, int(c)))
s = ''.join(insr())
letters.append('o')
m = solve(d, s, letters)
print(m)
output()
```
No
| 177 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bill likes to play with dominoes. He took an n × m board divided into equal square cells, and covered it with dominoes. Each domino covers two adjacent cells of the board either horizontally or vertically, and each cell is covered exactly once with a half of one domino (that is, there are no uncovered cells, and no two dominoes cover the same cell twice).
After that Bill decided to play with the covered board and share some photos of it on social media. First, he removes exactly one domino from the board, freeing two of the cells. Next, he moves dominoes around. A domino can only be moved along the line parallel to its longer side. A move in the chosen direction is possible if the next cell in this direction is currently free. Bill doesn't want to lose track of what the original tiling looks like, so he makes sure that at any point each domino shares at least one cell with its original position.
After removing a domino and making several (possibly, zero) moves Bill takes a photo of the board and posts it. However, with the amount of filters Bill is using, domino borders are not visible, so only the two free cells of the board can be identified. When the photo is posted, Bill reverts the board to its original state and starts the process again.
Bill wants to post as many photos as possible, but he will not post any photo twice. How many distinct photos can he take? Recall that photos are different if the pairs of free cells in the photos are different.
Input
The first line contains two positive integers n and m (nm ≤ 2 ⋅ 10^5) — height and width of the board respectively.
The next n lines describe the tiling of the board, row by row from top to bottom. Each of these lines contains m characters, describing the cells in the corresponding row left to right. Each character is one of U, D, L, or R, meaning that the cell is covered with a top, bottom, left, or right half of a domino respectively.
It is guaranteed that the described tiling is valid, that is, each half-domino has a counterpart in the relevant location. In particular, since tiling is possible, the number of cells in the board is even.
Output
Print a single integer — the number of distinct photos Bill can take.
Examples
Input
2 4
UUUU
DDDD
Output
4
Input
2 3
ULR
DLR
Output
6
Input
6 6
ULRUUU
DUUDDD
UDDLRU
DLRLRD
ULRULR
DLRDLR
Output
133
Note
In the first sample case, no moves are possible after removing any domino, thus there are four distinct photos.
In the second sample case, four photos are possible after removing the leftmost domino by independently moving/not moving the remaining two dominoes. Two more different photos are obtained by removing one of the dominoes on the right.
Submitted Solution:
```
print('hahah')
```
No
| 178 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number n, can you find the two digit permutations that have this property?
Input
The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output
Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Examples
Input
198
Output
981
819
Input
500
Output
500
500
Tags: greedy
Correct Solution:
```
n = input()
digits = [0 for x in range(10)]
for x in n:
digits[int(x)] += 1
best = -1
b1 = ''
b2 = ''
types = [(1,9), (2,8), (3,7), (4,6), (5,5)]
best = -1
b1 = ''
b2 = ''
for a,b in types:
if digits[a] and digits[b]:
d1 = digits[:]
d2 = digits[:]
d1[a] -= 1
d2[b] -= 1
s1 = str(a)
s2 = str(b)
for i,x in enumerate(d1):
num = min(x,d2[9-i])
s1 += str(i)*num
s2 += str(9-i)*num
d1[i] -= num
d2[9-i] -= num
num = min(d1[0], d2[0])
s1 = '0'*num+s1
s2 = '0'*num+s2
d1[0] -= num
d2[0] -= num
if len(s1) > best:
best = len(s1)
for i,x in enumerate(d1):
s1 += str(i)*x
for i,x in enumerate(d2):
s2 += str(i)*x
b1 = s1
b2 = s2
if best == -1:
for x in range(10):
b1 += str(x)*digits[x]
b2 += str(x)*digits[x]
print(b1[::-1])
print(b2[::-1])
```
| 179 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number n, can you find the two digit permutations that have this property?
Input
The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output
Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Examples
Input
198
Output
981
819
Input
500
Output
500
500
Tags: greedy
Correct Solution:
```
import itertools
def countZeroes(s):
ret = 0
for i in s:
if i != '0':
break
ret += 1
return ret
def stupid(n):
ansMax = 0
bn1 = n
bn2 = n
for n1 in itertools.permutations(n):
for n2 in itertools.permutations(n):
val = str(int(''.join(n1)) + int(''.join(n2)))[::-1]
cnt = countZeroes(val)
if cnt > ansMax:
ansMax = cnt
bn1 = ''.join(n1)
bn2 = ''.join(n2)
return (bn1, bn2)
def solution(n):
ansMax = n.count('0')
bestN1 = n.replace('0', '') + ansMax * '0'
bestN2 = n.replace('0', '') + ansMax * '0'
for i in range(1, 10):
cnt1 = [n.count(str(j)) for j in range(10)]
cnt2 = [n.count(str(j)) for j in range(10)]
if cnt1[i] == 0 or cnt2[10 - i] == 0:
continue
cnt1[i] -= 1
cnt2[10 - i] -= 1
curN1 = str(i)
curN2 = str(10 - i)
ansCur = 1
for j in range(10):
addend = min(cnt1[j], cnt2[9 - j])
ansCur += addend
cnt1[j] -= addend
cnt2[9 - j] -= addend
curN1 += str(j) * addend
curN2 += str(9 - j) * addend
if cnt1[0] > 0 and cnt2[0] > 0:
addend = min(cnt1[0], cnt2[0])
ansCur += addend
cnt1[0] -= addend
cnt2[0] -= addend
curN1 = '0' * addend + curN1
curN2 = '0' * addend + curN2
if ansCur > ansMax:
ansMax = ansCur
f = lambda x: str(x[0]) * x[1]
bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1]
bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1]
return (bestN1, bestN2)
n = input()
print('\n'.join(solution(n)))
```
| 180 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number n, can you find the two digit permutations that have this property?
Input
The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output
Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Examples
Input
198
Output
981
819
Input
500
Output
500
500
Submitted Solution:
```
a = input()
lis = {}
for i in range(10):
lis[i] = 0
for i in range(len(a)):
lis[int(a[i])] = lis[int(a[i])] + 1
lis_1 = lis.copy()
lis_2 = lis.copy()
L_1 = []
L_2 = []
A = ""
B = ""
for i in range(1, 6):
if lis[i] < lis[10 - i]:
lis_1[i] = 0
lis_2[10 - i] = lis[10 - i] - lis[i]
for j in range(lis[i]):
L_1.append(i)
L_2.append(10 - i)
else:
lis_1[10 -i] = 0
lis_2[i] = lis[i] - lis[10 - i]
for j in range(lis[10 - i]):
L_1.append(10 - i)
L_2.append(i)
for i in range(lis[0]):
L_1.append(0)
L_2.append(0)
for i in range(10):
for j in range(lis_1[i]):
A = A + str(i)
for i in range(len(L_1)):
A = A + str(L_1[i])
for i in range(10):
for j in range(lis_2[i]):
B = B + str(i)
for i in range(len(L_2)):
B = B + str(L_2[i])
print(int(A))
print(int(B))
```
No
| 181 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number n, can you find the two digit permutations that have this property?
Input
The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output
Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Examples
Input
198
Output
981
819
Input
500
Output
500
500
Submitted Solution:
```
n = input()
digits = [0 for x in range(10)]
for x in n:
digits[int(x)] += 1
best = -1
b1 = ''
b2 = ''
types = [(1,9), (2,8), (3,7), (4,6), (5,5)]
best = -1
b1 = ''
b2 = ''
for a,b in types:
if digits[a] and digits[b]:
d1 = digits[:]
d2 = digits[:]
d1[a] -= 1
d2[b] -= 1
s1 = str(a)
s2 = str(b)
for i,x in enumerate(d1):
num = min(x,d2[9-i])
s1 += str(i)*num
s2 += str(9-i)*num
d1[i] -= num
d2[9-i] -= num
num = min(d1[0], d2[0])
s1 = '0'*num+s1
s2 = '0'*num+s2
d1[0] -= num
d2[0] -= num
if len(s1) > best:
best = len(s1)
for i,x in enumerate(d1):
s1 += str(i)*x
for i,x in enumerate(d2):
s2 += str(i)*x
b1 = s1
b2 = s2
print(b1[::-1])
print(b2[::-1])
```
No
| 182 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Andrey's favourite number is n. Andrey's friends gave him two identical numbers n as a New Year present. He hung them on a wall and watched them adoringly.
Then Andrey got bored from looking at the same number and he started to swap digits first in one, then in the other number, then again in the first number and so on (arbitrary number of changes could be made in each number). At some point it turned out that if we sum the resulting numbers, then the number of zeroes with which the sum will end would be maximum among the possible variants of digit permutations in those numbers.
Given number n, can you find the two digit permutations that have this property?
Input
The first line contains a positive integer n — the original number. The number of digits in this number does not exceed 105. The number is written without any leading zeroes.
Output
Print two permutations of digits of number n, such that the sum of these numbers ends with the maximum number of zeroes. The permutations can have leading zeroes (if they are present, they all should be printed). The permutations do not have to be different. If there are several answers, print any of them.
Examples
Input
198
Output
981
819
Input
500
Output
500
500
Submitted Solution:
```
n = input()
zeroes = n.count('0')
n = n.replace('0', '')
ansMax = 0
bestN1 = n
bestN2 = n
for i in range(1, 10):
cnt1 = [0] + [n.count(str(j)) for j in range(1, 10)]
cnt2 = [0] + [n.count(str(j)) for j in range(1, 10)]
if cnt1[i] == 0 or cnt2[10 - i] == 0:
continue
cnt1[i] -= 1
cnt2[10 - i] -= 1
curN1 = str(i)
curN2 = str(10 - i)
ansCur = 1
for j in range(10):
addend = min(cnt1[j], cnt2[9 - j])
ansCur += addend
cnt1[j] -= addend
cnt2[9 - j] -= addend
curN1 += str(j) * addend
curN2 += str(9 - j) * addend
if ansCur > ansMax:
ansMax = ansCur
f = lambda x: str(x[0]) * x[1]
bestN1 = ''.join(map(f, enumerate(cnt1))) + curN1[::-1]
bestN2 = ''.join(map(f, enumerate(cnt2))) + curN2[::-1]
print(bestN1 + '0' * zeroes)
print(bestN2 + '0' * zeroes)
```
No
| 183 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import io
import os
from bisect import bisect_right
from collections import Counter, defaultdict, deque
# https://raw.githubusercontent.com/cheran-senthil/PyRival/master/pyrival/data_structures/RangeQuery.py
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, start, stop):
"""func of data[start, stop)"""
depth = (stop - start).bit_length() - 1
return self.func(
self._data[depth][start], self._data[depth][stop - (1 << depth)]
)
def solve(N, A):
rmq = RangeQuery(A)
maxLeft = [0]
maxRight = [0]
for x in A:
maxLeft.append(max(maxLeft[-1], x))
for x in A[::-1]:
maxRight.append(max(maxRight[-1], x))
for x in range(1, N):
mx = maxLeft[x]
index = bisect_right(maxRight, mx, 0, N - x - 1)
for z in [index - 2, index - 1, index]:
y = N - x - z
if 1 <= y <= N and 1 <= z <= N and maxRight[z] == mx == rmq.query(x, x + y):
return "YES\n" + str(x) + " " + str(y) + " " + str(z)
return "NO"
def solveBrute(N, A):
rangeMin = RangeQuery(A)
rangeMax = RangeQuery(A, max)
for x in range(1, N):
for y in range(1, N):
z = N - x - y
if 1 <= y <= N and 1 <= z <= N:
if (
rangeMax.query(0, x)
== rangeMin.query(x, x + y)
== rangeMax.query(x + y, x + y + z)
):
return "YES"
return "NO"
DEBUG = False
if DEBUG:
import random
random.seed(0)
for _ in range(100000):
N = random.randint(1, 10)
A = [random.randint(1, 10) for i in range(N)]
print("tc", _, N, A)
ans1 = solve(N, A)
ans2 = solveBrute(N, A)
if (ans1 == "NO" or ans2 == "NO") and ans1 != ans2:
print("ans1", ans1)
print("ans2", ans2)
assert False
exit()
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
(N,) = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
ans = solve(N, A)
print(ans)
```
| 184 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
import heapq
T = int(input())
r = 1
while r<=T:
n = int(input())
arr = list(map(int,input().split()))
# arr = [1,2]*50000+[1,3,1,2]+[1,2]*49998
# n = 200000
third = [0]*n
third[-1] = arr[-1]
maxfre = 0
for i in range(n-2,-1,-1):
third[i] = max(third[i+1],arr[i])
firstdic = {}
temp = []
secondindexnum = 0
secondindexmin = 2147483647
flag = False
fuck = 0
for i in range(n-1):
if arr[i]<=third[i+1]:
heapq.heappush(temp,[-arr[i],-i])
if arr[i] not in firstdic: firstdic[arr[i]] = []
firstdic[arr[i]].append(i)
else:
secondindexnum += 1
secondindexmin = min(secondindexmin,i)
while temp and -temp[0][0]>third[i+1]:
ele = heapq.heappop(temp)
secondindexnum += 1
secondindexmin = min(secondindexmin,-ele[1])
if -ele[0] in firstdic: del firstdic[-ele[0]]
if len(temp)<2: continue
if temp[0][0]!=-third[i+1]: continue
maximum = heapq.heappop(temp)
if temp[0][0]!=-third[i+1]:
heapq.heappush(temp,maximum)
continue
heapq.heappush(temp,maximum)
if secondindexnum==0:
flag = True
x,y,z = len(temp)-1,1,n-len(temp)
break
needed = i - secondindexmin + 1 - secondindexnum
if len(temp)<needed+1: continue
# print("hahaha",needed)
if needed==0 and -temp[0][1]==secondindexmin-1:
flag = True
x,y,z = secondindexmin-1,i+2-secondindexmin,n-i-1
break
if needed>0 and len(firstdic[third[i+1]])>needed:
target = firstdic[third[i+1]]
if target[-needed]>secondindexmin:
flag = True
x,y,z = secondindexmin,i+1-secondindexmin,n-i-1
if flag: break
if flag:
print("YES")
print(x,y,z)
else:
print("NO")
r += 1
```
| 185 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import math
class RMQ:
def __init__(self, arr):
self.n = len(arr)
self.logn = int(math.log2(self.n)) + 1
self.arr = [0] + arr
self.Log = [0] * (self.n + 1)
self.Log[2] = 1
for i in range(3, self.n + 1):
self.Log[i] = self.Log[i // 2] + 1
self.min = [[0] * (self.logn + 1) for _ in range(self.n + 1)]
for i in range(1, self.n + 1):
self.min[i][0] = self.arr[i]
def pre(self):
for j in range(1, self.logn + 1):
for i in range(1, self.n + 1):
if i + (1 << j) - 1 > self.n: break
self.min[i][j] = min(self.min[i][j - 1], self.min[i + (1 << (j - 1))][j - 1])
def queryMax(self, l, r):
s = self.Log[r - l + 1]
return max(self.max[l][s], self.max[r - (1 << s) + 1][s])
def queryMin(self, l, r):
s = self.Log[r - l + 1]
return min(self.min[l][s], self.min[r - (1 << s) + 1][s])
from bisect import bisect, bisect_left
for _ in range(int(input())):
n = int(input())
A = list(map(int, input().split()))
rmq = RMQ(A)
rmq.pre()
dic = {}
cur = float("-inf")
left = [A[0]]
for i in range(1, n):
left.append(max(left[-1], A[i]))
right = [A[-1]]
for i in range(n - 2, -1, -1):
right.append(max(right[-1], A[i]))
for i in range(n - 2):
cur = left[i]
j, k = bisect(right, cur), bisect_left(right, cur)
if right[k] != cur: continue
j, k = n - j, n - 1 - k
if k - i <= 1: break
j = max(i + 2, j)
dic[i] = (j, k)
flag = 0
for i, (j, k) in dic.items():
while j <= k:
m = (j + k) // 2
tmp = rmq.queryMin(i + 2, m)
if tmp == left[i]:
flag = 1
break
elif tmp > left[i]:
j = m + 1
else:
k = m - 1
if flag:
print("YES")
print("{} {} {}".format(i + 1, m - i - 1, n - m))
break
else:
print("NO")
```
| 186 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
T = Tp.TypeVar('T')
class SegmentTree(Tp.Generic[T]):
__slots__ = ["size", "tree", "identity", "op", "update_op"]
def __init__(self, size: int, identity: T, op: Tp.Callable[[T, T], T],
update_op: Tp.Callable[[T, T], T]) -> None:
self.size = size
self.tree = [identity] * (size * 2)
self.identity = identity
self.op = op
self.update_op = update_op
def build(self, a: Tp.List[T]) -> None:
tree = self.tree
tree[self.size:self.size + len(a)] = a
for i in range(self.size - 1, 0, -1):
tree[i] = self.op(tree[i << 1], tree[(i << 1) + 1])
def find(self, left: int, right: int) -> T:
left += self.size
right += self.size
tree, result, op = self.tree, self.identity, self.op
while left < right:
if left & 1:
result = op(tree[left], result)
left += 1
if right & 1:
result = op(tree[right - 1], result)
left, right = left >> 1, right >> 1
return result
def update(self, i: int, value: T) -> None:
op, tree = self.op, self.tree
i = self.size + i
tree[i] = self.update_op(tree[i], value)
while i > 1:
i >>= 1
tree[i] = op(tree[i << 1], tree[(i << 1) + 1])
def main():
from collections import defaultdict
t = int(input())
ans = ['NO'] * t
for ti in range(t):
n = int(input())
a = list(map(int, input().split()))
segtree = SegmentTree[int](n, 10**9 + 1, min, min)
segtree.build(a)
right_max = [0] * (n + 1)
r_max_i = defaultdict(list)
for i in range(n - 1, -1, -1):
right_max[i] = max(right_max[i + 1], a[i])
r_max_i[right_max[i]].append(i)
left_max = 0
for i in range(n - 2):
left_max = max(left_max, a[i])
while r_max_i[left_max] and r_max_i[left_max][-1] <= i:
r_max_i[left_max].pop()
if not r_max_i[left_max]:
continue
ok, ng = i + 2, r_max_i[left_max][0] + 1
while abs(ok - ng) > 1:
mid = (ok + ng) >> 1
if segtree.find(i + 1, mid) >= left_max:
ok = mid
else:
ng = mid
if right_max[ok] == left_max and segtree.find(i + 1, ok) == left_max:
ans[ti] = f'YES\n{i+1} {ok - i - 1} {n - ok}'
break
sys.stdout.buffer.write(('\n'.join(ans) + '\n').encode('utf-8'))
if __name__ == '__main__':
main()
```
| 187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
"""
Author - Satwik Tiwari .
24th NOV , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, start, stop):
"""func of data[start, stop)"""
depth = (stop - start).bit_length() - 1
return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])
def solve(case):
n = int(inp())
a = lis()
# n = randint(1,100000)
# a = [randint(1,1000) for i in range(n)]
rmq = RangeQuery(a)
mxleft = [a[0]]*n
curr = a[0]
for i in range(1,n):
curr = max(curr,a[i])
mxleft[i] = curr
mxright = [a[n-1]]*n
curr = a[n-1]
for i in range(n-2,-1,-1):
curr = max(a[i],curr)
mxright[i] = curr
mx = {}
for i in range(n-1,-1,-1):
if(mxright[i] in mx):
mx[mxright[i]].append(i)
else:
mx[mxright[i]] = [i]
for i in mx:
mx[i] = mx[i][::-1]
for i in range(n-2):
if(mxleft[i] not in mx):
continue
ans = mxleft[i]
# print(i,mx[ans])
# temp = mx[ans]
lo = bl(mx[ans],i+2)
hi = len(mx[ans])-1
# print(lo,hi,ans,'===')
while(lo<=hi):
mid = (lo+hi)//2
# chck = RMQ(st,n,i+1,mx[ans][mid]-1)
chck = rmq.query(i+1,mx[ans][mid])
# print(i+1,mid,lo,hi,chck)
if(chck < ans):
hi = mid-1
elif(chck > ans):
lo = mid+1
else:
print('YES')
print(i+1,mx[ans][mid] - 1 - i,n-mx[ans][mid])
return
print('NO')
sys.stdout.flush()
# testcase(1)
testcase(int(inp()))
```
| 188 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n')
def out(var) : sys.stdout.write(str(var)+'\n')
#from decimal import Decimal
#from fractions import Fraction
#sys.setrecursionlimit(100000)
INF = float('inf')
mod = 998244353
class SegmentTree:
def __init__(self, data, default=INF, func=min):
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
while idx:
idx >>= 1
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
for t in range(int(data())):
n=int(data())
a=mdata()
S=SegmentTree(a)
m=[[a[-1],1]]
d=dd(int)
d[a[-1]]=n-1
for i in range(n-2,-1,-1):
if a[i]<=m[-1][0]:
m.append(m[-1])
if a[i]==m[-1][0]:
m[-1][1]+=1
d[m[-1][0]]=i
else:
m.append([a[i],1])
d[a[i]]=i
m=m[::-1]
m1=a[0]
flag=False
l=[]
if m[0][1]>2:
flag=True
l=[]
for i in range(n):
if len(l)==3:
break
if a[i]==m[0][0]:
l.append(i+1)
l[0],l[1],l[2]=l[1]-1,1,n-l[1]
else:
for i in range(n):
m1=max(m1,a[i])
if m1 in d and d[m1]>i:
m2=S.query(i+1,d[m1])
if m2==m1:
flag=True
l=[i+1,d[m1]-i-1,n-d[m1]]
elif m2>m1 and a[d[m1]]==m1 and m[d[m1]][1]>1:
l = [i + 1, d[m1] - i, n - d[m1]-1]
flag=True
if flag:
break
if flag:
out("YES")
outl(l)
else:
out("NO")
```
| 189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
import bisect
t=int(input())
for tests in range(t):
n=int(input())
A=list(map(int,input().split()))
LEN = len(A)
Sparse_table = [A]
for i in range(LEN.bit_length()-1):
j = 1<<i
B = []
for k in range(len(Sparse_table[-1])-j):
B.append(min(Sparse_table[-1][k], Sparse_table[-1][k+j]))
Sparse_table.append(B)
def query(l,r): # [l,r)におけるminを求める.
i=(r-l).bit_length()-1 # 何番目のSparse_tableを見るか.
return min(Sparse_table[i][l],Sparse_table[i][r-(1<<i)]) # (1<<i)個あれば[l, r)が埋まるので, それを使ってminを求める.
LMAX=[A[0]]
for i in range(1,n):
LMAX.append(max(LMAX[-1],A[i]))
RMAX=A[-1]
for i in range(n-1,-1,-1):
RMAX=max(RMAX,A[i])
x=bisect.bisect(LMAX,RMAX)
#print(RMAX,x)
if x==0:
continue
v=min(x,i-1)
if v<=0:
continue
if LMAX[v-1]==query(v,i)==RMAX:
print("YES")
print(v,i-v,n-i)
break
v-=1
if v<=0:
continue
if LMAX[v-1]==query(v,i)==RMAX:
print("YES")
print(v,i-v,n-i)
break
else:
print("NO")
```
| 190 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Tags: binary search, data structures, greedy, two pointers
Correct Solution:
```
from collections import Counter, OrderedDict
def nint():
return int(input())
def nintA():
return [int(x) for x in input().split()]
def f():
nint()
A = nintA()
n = len(A)
m = max(A)
l,r,rr = 0,0,0
try:
l = A.index(m)
r = A[l+1:].index(m) + l + 1
rr = A[r+1:].index(m) + r + 1
except:
pass
if rr:
print("YES")
return print(r,1,n-r-1)
r = max(l,r)
m = min(A[l:r+1])
MAX = [A[0]] + [0] * (n-2) + [A[-1]]
for i in range(1, l):
MAX[i] = max(MAX[i-1], A[i])
for i in reversed(range(r + 1, n-1)):
MAX[i] = max(MAX[i+1], A[i])
ll,rr = l-1, r+1
while rr < n and ll >= 0:
m = min(m, A[ll+1], A[rr-1])
# print(m, ll, rr, MAX)
if m == MAX[ll] and m == MAX[rr]:
print("YES")
return print(ll+1, rr-ll-1 ,n-rr)
elif ll == 0:
rr += 1
elif rr == n-1:
ll -= 1
elif min(m, MAX[ll-1], MAX[rr], A[ll]) > min(m, MAX[ll], MAX[rr+1], A[rr]):
ll -= 1
else:
rr += 1
print ("NO")
t = int(input())
for i in range(t):
f()
```
| 191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
import sys
input = sys.stdin.readline
def format(a, b=0, n=0):
if a == -1:
return "NO"
else:
return "YES\n{} {} {}".format(a, b-a, n-b)
def solve():
n = int(input())
ar = [int(t) for t in input().split()]
rmq = RangeQuery(ar)
fmax = max(ar)
idxs = [i for i in range(n) if ar[i] == fmax]
if len(idxs) >= 3:
mid = idxs[1]
return format(mid, mid+1, n)
front = []
cmax, event = 0, 0
for i in range(n):
x = ar[i]
if x > cmax:
front += [(cmax, event)]
cmax = x
event = i
elif x < cmax:
event = i
back = []
cmax, event = 0, n
for i in reversed(range(n)):
x = ar[i]
if x > cmax:
back += [(cmax, event)]
cmax = x
event = i
elif x < cmax:
event = i
fit = iter(front)
bit = iter(back)
f = next(fit, False)
b = next(bit, False)
while f and b:
if f[0] == b[0]:
if f[0] == rmq.query(f[1]+1, b[1]):
return format(f[1]+1, b[1], n)
else:
f = next(fit, False)
b = next(bit, False)
elif f[0] < b[0]:
f = next(fit, False)
else:
b = next(bit, False)
return format(-1)
def main():
T = int(input())
ans = []
for _ in range(T):
ans += [solve()]
print(*ans, sep='\n')
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, start, stop):
"""func of data[start, stop)"""
depth = (stop - start).bit_length() - 1
return self.func(self._data[depth][start], self._data[depth][stop - (1 << depth)])
def __getitem__(self, idx):
return self._data[0][idx]
main()
```
Yes
| 192 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
import heapq
def heapu(counted, heee, f, d, e):
for i in range(f, d, e):
while (len(heee) > 0 and (heee[0][0] * -1) > a[i]):
counted[heee[0][1]] = (i - heee[0][1])
heapq.heappop(heee)
heapq.heappush(heee, [a[i] * -1, i])
return counted
for t in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
he=[[-a[0],0]]
plus=0
f_counted=[]
b_counted=[]
for i in range(n):
b_counted.append(plus)
plus-=1
plus=n-1
for i in range(n):
f_counted.append(plus)
plus-=1
counted_f=heapu(f_counted,he,1,n-1,1)
hee=[[-a[n-1],n-1]]
counted_b=heapu(b_counted,hee,n-1,0,-1)
f_maxi=[]
maxi=0
for i in range(0,n):
maxi=max(maxi,a[i])
f_maxi.append(maxi)
b_maxi=[]
maxi=0
for i in range(n-1,-1,-1):
maxi=max(maxi,a[i])
b_maxi.append(maxi)
b_maxi=b_maxi[::-1]
x, y, z = -1, -1, -1
flag=1
for i in range(1,n-1):
x, y, z = -1, -1, -1
if(a[i]==b_maxi[i+counted_f[i]]):
z=n-i-f_counted[i]
elif(a[i]==b_maxi[i+counted_f[i]-1] and counted_f[i]>1):
z=n-i-f_counted[i]+1
if(a[i]==f_maxi[i+counted_b[i]]):
x=i+b_counted[i]+1
elif(a[i]==f_maxi[i+counted_b[i]+1] and counted_b[i]<-1):
x=i+b_counted[i]+1+1
y=n-x-z
if(x>-1 and z>-1):
flag=0
break
if(flag==0):
print("YES")
print(x,y,z)
else:
print("NO")
```
Yes
| 193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
from sys import stdin, stdout
from math import log, ceil
# 1
# 9
# 2 1 | 4 2 4 3 3 | 1 2
def array_partition(n, a_a):
lm = [a_a[0]]
rm = [a_a[-1]]
for i in range(1, n):
lm.append(max(lm[-1], a_a[i]))
rm.append(max(rm[-1], a_a[-(i+1)]))
r = n - 1
for l in range(n - 2):
left = lm[l]
while r > l + 1 and rm[n - 1 - r] <= left:
r -= 1
if r < n - 1:
r += 1
if left == rm[n - 1 - r]:
mm = query(0, 0, n - 1, l + 1, r - 1)
if left == mm:
return [l + 1, r - l - 1, n - r]
elif mm < left:
pass
elif r < n - 1:
r += 1
if left == rm[n - 1 - r] and query(0, 0, n - 1, l + 1, r - 1) == left:
return [l + 1, r - l - 1, n - r]
return []
def build(cur, l, r):
if l == r:
segTree[cur] = a_a[l]
return a_a[l]
mid = l + (r - l) // 2
segTree[cur] = min(build(2 * cur + 1, l, mid), build(2 * cur + 2, mid + 1, r))
return segTree[cur]
def query(cur, sl, sr, l, r):
if l <= sl and r >= sr:
return segTree[cur]
elif l > sr or r < sl:
return float('inf')
else:
mid = sl + (sr - sl) // 2
return min(query(cur * 2 + 1, sl, mid, l, r), query(cur * 2 + 2, mid + 1, sr, l, r))
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
a_a = list(map(int, stdin.readline().split()))
size = int(2 ** (ceil(log(n, 2)) + 1) - 1)
segTree = [float('inf') for i in range(size)]
build(0, 0, n - 1)
r = array_partition(n, a_a)
if r:
stdout.write('YES\n')
stdout.write(' '.join(map(str, r)) + '\n')
else:
stdout.write('NO\n')
```
Yes
| 194 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
import sys
input=sys.stdin.readline
import bisect
t=int(input())
for you in range(t):
n=int(input())
l=input().split()
li=[int(i) for i in l]
hashi=dict()
for i in range(n):
if(li[i] in hashi):
hashi[li[i]].append(i)
else:
hashi[li[i]]=[]
hashi[li[i]].append(i)
maxpref=[0 for i in range(n)]
maxsuff=[0 for i in range(n)]
maxa=0
for i in range(n):
maxa=max(maxa,li[i])
maxpref[i]=maxa
maxa=0
for i in range(n-1,-1,-1):
maxa=max(maxa,li[i])
maxsuff[i]=maxa
nextlow=[n for i in range(n)]
prevlow=[-1 for i in range(n)]
s=[]
for i in range(n):
while(s!=[] and li[s[-1]]>li[i]):
nextlow[s[-1]]=i
s.pop(-1)
s.append(i)
for i in range(n-1,-1,-1):
while(s!=[] and li[s[-1]]>li[i]):
prevlow[s[-1]]=i
s.pop(-1)
s.append(i)
maxs=dict()
maxe=dict()
for i in range(n):
maxs[maxpref[i]]=i
for i in range(n-1,-1,-1):
maxe[maxsuff[i]]=i
hashs=dict()
hashe=dict()
for i in range(n):
if(maxpref[i] not in hashs):
hashs[maxpref[i]]=[i]
else:
hashs[maxpref[i]].append(i)
for i in range(n):
if(maxsuff[i] not in hashe):
hashe[maxsuff[i]]=[i]
else:
hashe[maxsuff[i]].append(i)
poss=0
for i in range(n):
if(li[i] not in hashs or li[i] not in hashe):
continue
z=bisect.bisect_left(hashs[li[i]],i)
z-=1
if(z<0 or z>=len(hashs[li[i]]) or hashs[li[i]][z]<prevlow[i]):
continue
y=bisect.bisect_right(hashe[li[i]],i)
if(y>=len(hashe[li[i]]) or hashe[li[i]][y]>nextlow[i]):
continue
poss=1
ans=(hashs[li[i]][z],hashe[li[i]][y])
break
if(poss):
print("YES")
print(ans[0]+1,ans[1]-ans[0]-1,n-ans[1])
else:
print("NO")
```
Yes
| 195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
import sys
max_int = 2147483648 # 2^31
def set_val(i, v, x, lx, rx):
if rx - lx == 1:
seg_tree[x] = v
else:
mid = (lx + rx) // 2
if i < mid:
set_val(i, v, 2 * x + 1, lx, mid)
else:
set_val(i, v, 2 * x + 2, mid, rx)
seg_tree[x] = min(seg_tree[2 * x + 1], seg_tree[2 * x + 2])
def get_min(l, r, x, lx, rx):
if lx >= r or l >= rx:
return max_int
if lx >= l and rx <= r:
return seg_tree[x]
mid = (lx + rx) // 2
min1 = get_min(l, r, 2 * x + 1, lx, mid)
min2 = get_min(l, r, 2 * x + 2, mid, rx)
return min(min1, min2)
t = int(input())
for _t in range(t):
n = int(sys.stdin.readline())
a = list(map(int, sys.stdin.readline().split()))
size = 1
while size < n:
size *= 2
seg_tree = [max_int] * (2 * size - 1)
for i, num in enumerate(a, size - 1):
seg_tree[i] = num
for i in range(size - 2, -1, -1):
seg_tree[i] = min(seg_tree[2 * i + 1], seg_tree[2 * i + 2])
i = 0
j = n - 1
m1 = 0
m3 = 0
while j - i > 1:
m1 = max(m1, a[i])
m3 = max(m3, a[j])
while i < n - 1 and a[i + 1] < m1:
i += 1
while j > 0 and a[j - 1] < m1:
j -= 1
if m1 == m3:
if get_min(i + 1, j, 0, 0, size) == m1:
print('YES')
print(i + 1, j - i - 1, n - j)
break
i += 1
j -= 1
elif m1 < m3:
i += 1
else:
j -= 1
else:
print('NO')
```
No
| 196 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
from bisect import *
from collections import *
from math import gcd,ceil,sqrt,floor,inf
from heapq import *
from itertools import *
from operator import add,mul,sub,xor,truediv,floordiv
from functools import *
#------------------------------------------------------------------------
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().rstrip("\r\n")
#------------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
#------------------------------------------------------------------------
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
farr=[1]
ifa=[]
def fact(x,mod=0):
if mod:
while x>=len(farr):
farr.append(farr[-1]*len(farr)%mod)
else:
while x>=len(farr):
farr.append(farr[-1]*len(farr))
return farr[x]
def ifact(x,mod):
global ifa
ifa.append(pow(farr[-1],mod-2,mod))
for i in range(x,0,-1):
ifa.append(ifa[-1]*i%mod)
ifa=ifa[::-1]
def per(i,j,mod=0):
if i<j: return 0
if not mod:
return fact(i)//fact(i-j)
return farr[i]*ifa[i-j]%mod
def com(i,j,mod=0):
if i<j: return 0
if not mod:
return per(i,j)//fact(j)
return per(i,j,mod)*ifa[j]%mod
def catalan(n):
return com(2*n,n)//(n+1)
def linc(f,t,l,r):
while l<r:
mid=(l+r)//2
if t>f(mid):
l=mid+1
else:
r=mid
return l
def rinc(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t<f(mid):
r=mid-1
else:
l=mid
return l
def ldec(f,t,l,r):
while l<r:
mid=(l+r)//2
if t<f(mid):
l=mid+1
else:
r=mid
return l
def rdec(f,t,l,r):
while l<r:
mid=(l+r+1)//2
if t>f(mid):
r=mid-1
else:
l=mid
return l
def isprime(n):
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def binfun(x):
c=0
for w in arr:
c+=ceil(w/x)
return c
def lowbit(n):
return n&-n
def inverse(a,m):
a%=m
if a<=1: return a
return ((1-inverse(m,a)*m)//a)%m
class BIT:
def __init__(self,arr):
self.arr=arr
self.n=len(arr)-1
def update(self,x,v):
while x<=self.n:
self.arr[x]+=v
x+=x&-x
def query(self,x):
ans=0
while x:
ans+=self.arr[x]
x&=x-1
return ans
'''
class SMT:
def __init__(self,arr):
self.n=len(arr)-1
self.arr=[0]*(self.n<<2)
self.lazy=[0]*(self.n<<2)
def Build(l,r,rt):
if l==r:
self.arr[rt]=arr[l]
return
m=(l+r)>>1
Build(l,m,rt<<1)
Build(m+1,r,rt<<1|1)
self.pushup(rt)
Build(1,self.n,1)
def pushup(self,rt):
self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1]
def pushdown(self,rt,ln,rn):#lr,rn表区间数字数
if self.lazy[rt]:
self.lazy[rt<<1]+=self.lazy[rt]
self.lazy[rt<<1|1]=self.lazy[rt]
self.arr[rt<<1]+=self.lazy[rt]*ln
self.arr[rt<<1|1]+=self.lazy[rt]*rn
self.lazy[rt]=0
def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间
if r==None: r=self.n
if L<=l and r<=R:
self.arr[rt]+=c*(r-l+1)
self.lazy[rt]+=c
return
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
if L<=m: self.update(L,R,c,l,m,rt<<1)
if R>m: self.update(L,R,c,m+1,r,rt<<1|1)
self.pushup(rt)
def query(self,L,R,l=1,r=None,rt=1):
if r==None: r=self.n
#print(L,R,l,r,rt)
if L<=l and R>=r:
return self.arr[rt]
m=(l+r)>>1
self.pushdown(rt,m-l+1,r-m)
ans=0
if L<=m: ans+=self.query(L,R,l,m,rt<<1)
if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1)
return ans
'''
class DSU:#容量+路径压缩
def __init__(self,n):
self.c=[-1]*n
def same(self,x,y):
return self.find(x)==self.find(y)
def find(self,x):
if self.c[x]<0:
return x
self.c[x]=self.find(self.c[x])
return self.c[x]
def union(self,u,v):
u,v=self.find(u),self.find(v)
if u==v:
return False
if self.c[u]<self.c[v]:
u,v=v,u
self.c[u]+=self.c[v]
self.c[v]=u
return True
def size(self,x): return -self.c[self.find(x)]
class UFS:#秩+路径
def __init__(self,n):
self.parent=[i for i in range(n)]
self.ranks=[0]*n
def find(self,x):
if x!=self.parent[x]:
self.parent[x]=self.find(self.parent[x])
return self.parent[x]
def union(self,u,v):
pu,pv=self.find(u),self.find(v)
if pu==pv:
return False
if self.ranks[pu]>=self.ranks[pv]:
self.parent[pv]=pu
if self.ranks[pv]==self.ranks[pu]:
self.ranks[pu]+=1
else:
self.parent[pu]=pv
def Prime(n):
c=0
prime=[]
flag=[0]*(n+1)
for i in range(2,n+1):
if not flag[i]:
prime.append(i)
c+=1
for j in range(c):
if i*prime[j]>n: break
flag[i*prime[j]]=prime[j]
if i%prime[j]==0: break
return prime
def dij(s,graph):
d={}
d[s]=0
heap=[(0,s)]
seen=set()
while heap:
dis,u=heappop(heap)
if u in seen:
continue
for v in graph[u]:
if v not in d or d[v]>d[u]+graph[u][v]:
d[v]=d[u]+graph[u][v]
heappush(heap,(d[v],v))
return d
def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)]
class DLN:
def __init__(self,val):
self.val=val
self.pre=None
self.next=None
t=N()
for i in range(t):
n=N()
a=RLL()
ma=max(a)
res=[]
c=0
for i,x in enumerate(a):
if x==ma:
c+=1
res.append(i+1)
if c>=3:
x=res[1]-1
y=1
z=n-x-y
print('YES')
print(x,y,z)
else:
l=r=res[0]-1
pre=[0]*n
suf=[0]*n
pre[0]=a[0]
suf[n-1]=a[n-1]
#print(l,r)
for i in range(l):
pre[i]=max(pre[i-1],a[i])
for j in range(n-2,r,-1):
suf[j]=max(suf[j+1],a[j])
s=set(a)
s=sorted(s,reverse=True)
f=1
c=Counter()
c[a[l]]+=1
for j in range(1,len(s)):
while r<n-1 and a[r+1]>=s[j]:
c[a[r+1]]+=1
r+=1
while l>0 and a[l-1]>=s[j]:
l-=1
c[a[l]]+=1
#print(s[j],l,r,c)
tmp=c[s[j]]
x=l
y=r+1-x
if l==0:
if a[l]==s[j]:
x=1
y-=1
tmp-=1
else:
f=0
break
else:
if pre[l-1]>s[j]:
continue
elif pre[l-1]<s[j]:
if a[l]==s[j]:
x+=1
y-=1
tmp-=1
else:
continue
if r==n-1:
if a[r]==s[j]:
tmp-=1
y-=1
else:
f=0
break
else:
if suf[r+1]>s[j]:
continue
elif suf[r+1]<s[j]:
if a[r]==s[j]:
y-=1
tmp-=1
if tmp:
break
if f:
print('YES')
if not max(a[:x])==min(a[x:x+y])==max(a[x+y:]):
print(a)
print(x,y,n-x-y)
else:
print('NO')
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
'''
sys.setrecursionlimit(200000)
import threading
threading.stack_size(10**8)
t=threading.Thread(target=main)
t.start()
t.join()
'''
```
No
| 197 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
import heapq
from collections import defaultdict
testCaseCounter = int(input())
for lksjdfa in range(testCaseCounter):
n = int(input())
arr = [int(amit) for amit in input().split(" ")]
leftPointer = 0
rightPointer = n-1
leftMax = arr[leftPointer]
rightMax = arr[rightPointer]
middleHeap = arr[1:-1].copy()
#print (arr)
heapq.heapify(middleHeap)
#print (arr)
freqMiddle = defaultdict(int)# stores the freq of every element in middle section
maxMiddle = None
freqMiddle[leftMax] += 1
freqMiddle[rightMax] += 1
for item in middleHeap:
freqMiddle[item] += 1
if freqMiddle[item] >= 3 and (maxMiddle is None or item > maxMiddle):
maxMiddle = item
freqMiddle[leftMax] -= 1
freqMiddle[rightMax] -= 1
while maxMiddle is not None and leftPointer < rightPointer + 1 and len(middleHeap) > 0:
#print ((leftMax, middleHeap[0], rightMax))
#print ((leftPointer, rightPointer))
if leftMax == rightMax == middleHeap[0]:
# success
break
elif leftMax > maxMiddle or rightMax > maxMiddle:
# failure
break
elif leftMax < rightMax:
leftPointer += 1
leftMax = max(leftMax, arr[leftPointer])
freqMiddle[arr[leftPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
elif rightMax < leftMax:
rightPointer -= 1
rightMax = max(rightMax, arr[rightPointer])
freqMiddle[arr[rightPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
elif leftMax == rightMax:
if middleHeap[0] < leftMax:
# middle value is too small, let us eat the smallest value away
if arr[leftPointer + 1] <= arr[rightPointer - 1] and (arr[leftPointer + 1] < maxMiddle or arr[leftPointer + 1] == maxMiddle and freqMiddle[maxMiddle] > 2):
# eat the left
leftPointer += 1
leftMax = max(leftMax, arr[leftPointer])
freqMiddle[arr[leftPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
else:
rightPointer -= 1
rightMax = max(rightMax, arr[rightPointer])
freqMiddle[arr[rightPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
else:
# middle value is too big, let the smaller value stay
if arr[leftPointer + 1] >= arr[rightPointer - 1] and (arr[leftPointer + 1] < maxMiddle or arr[leftPointer + 1] == maxMiddle and freqMiddle[maxMiddle] > 2):
# eat the left
leftPointer += 1
leftMax = max(leftMax, arr[leftPointer])
freqMiddle[arr[leftPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
else:
rightPointer -= 1
rightMax = max(rightMax, arr[rightPointer])
freqMiddle[arr[rightPointer]] -= 1
while len(middleHeap) > 0 and freqMiddle[middleHeap[0]] == 0:
heapq.heappop(middleHeap)
if len(middleHeap) > 0 and leftMax == rightMax == middleHeap[0]:
x = leftPointer + 1
y = rightPointer - 1 - leftPointer
z = (n - x - y)
print ("YES")
print (str(x) + " " + str(y) + " " + str(z))
else:
print ("NO")
```
No
| 198 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
Let min(l, r) be the minimum value among a_l, a_{l + 1}, …, a_r and max(l, r) be the maximum value among a_l, a_{l + 1}, …, a_r.
Your task is to choose three positive (greater than 0) integers x, y and z such that:
* x + y + z = n;
* max(1, x) = min(x + 1, x + y) = max(x + y + 1, n).
In other words, you have to split the array a into three consecutive non-empty parts that cover the whole array and the maximum in the first part equals the minimum in the second part and equals the maximum in the third part (or determine it is impossible to find such a partition).
Among all such triples (partitions), you can choose any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (3 ≤ n ≤ 2 ⋅ 10^5) — the length of a.
The second line of the test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer: NO in the only line if there is no such partition of a that satisfies the conditions from the problem statement. Otherwise, print YES in the first line and three integers x, y and z (x + y + z = n) in the second line.
If there are several answers, you can print any.
Example
Input
6
11
1 2 3 3 3 4 4 3 4 2 1
8
2 9 1 7 3 9 4 1
9
2 1 4 2 4 3 3 1 2
7
4 2 1 1 4 1 4
5
1 1 1 1 1
7
4 3 4 3 3 3 4
Output
YES
6 1 4
NO
YES
2 5 2
YES
4 1 2
YES
1 1 3
YES
2 1 4
Submitted Solution:
```
a=int(input())
li=list(map(int,input().split()))
if a%2!=0:
print("YES")
print(1,2,a-3)
else:
print("NO")
```
No
| 199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.