text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens:
* Two numbers i and j are chosen equiprobable such that (1 β€ i < j β€ n).
* The numbers in the i and j positions are swapped.
Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem.
It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q notβ‘ 0~\pmod {10^9+7}.
Input
The first line contains two integers n and k (2 β€ n β€ 100, 1 β€ k β€ 10^9) β the length of the array a and the number of operations.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1) β the description of the array a.
Output
If the desired probability is 0, print 0, otherwise print the value P β
Q^{-1} \pmod {10^9+7}, where P and Q are defined above.
Examples
Input
3 2
0 1 0
Output
333333336
Input
5 1
1 1 1 0 0
Output
0
Input
6 4
1 0 0 1 1 0
Output
968493834
Note
In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3.
In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0.
Submitted Solution:
```
n,m=[int(x)for x in input().split()]
ns=[int(x)for x in input().split()]
print(1)
# k=n-sum(ns)
# c=k-sum(ns[:k])
# # print(k,c)
#
# def r(num):
# return num, k - num, k - num, n - k - (k - num)
# def p(num):
# a,b,c,d=r(num)
# o,z=a+c,b+d
# return a*d,o*(o-1)//2+z*(z-1)//2+a*b+c*d,b*c
#
# import numpy as np
#
# bs=np.zeros((k+1,k+1),'int')
# md=10**9+7
# st=np.zeros((1,k+1),'int')
# st[0,c]=1
# deno=n*(n-1)//2
#
# def get_inv(aa,pp):
# pp-=2
# l=len(bin(pp))-2
# ls=[aa]
# for i in range(l):
# ls.append(ls[-1]*ls[-1]%(pp+2))
# # print(ls)
# aa=1
# for i in range(l):
# if (pp>>i)&1:
# aa=aa*ls[i]%(pp+2)
# return aa%(pp+2)
# inv=get_inv(deno,md)
# # print('inv of {} : {}'.format(deno,inv))
#
#
# for i in range(k+1):
# x=p(i)
# for j in range(i-1,i+2):
# if 0<=j<=k:
# bs[i][j]=x[j-i+1]*inv%md
# ls=[bs]
# i=0
# m=bin(m)[2:][::-1]
# # print('m',m)
# for i in range(len(m)):
# ls.append(np.matmul(ls[-1],ls[-1])%md)
# # print(ls)
# for i in range(len(m)):
# c=m[i]
# if c=='1':
# st=np.matmul(st,ls[i])%md
# print(st[0,k])
#
#
#
#
# # print(bs)
# # print(np.matmul(bs,bs))
```
No
| 5,100 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens:
* Two numbers i and j are chosen equiprobable such that (1 β€ i < j β€ n).
* The numbers in the i and j positions are swapped.
Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem.
It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q notβ‘ 0~\pmod {10^9+7}.
Input
The first line contains two integers n and k (2 β€ n β€ 100, 1 β€ k β€ 10^9) β the length of the array a and the number of operations.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1) β the description of the array a.
Output
If the desired probability is 0, print 0, otherwise print the value P β
Q^{-1} \pmod {10^9+7}, where P and Q are defined above.
Examples
Input
3 2
0 1 0
Output
333333336
Input
5 1
1 1 1 0 0
Output
0
Input
6 4
1 0 0 1 1 0
Output
968493834
Note
In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3.
In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0.
Submitted Solution:
```
n,m=[int(x)for x in input().split()]
ns=[int(x)for x in input().split()]
k=n-sum(ns)
c=k-sum(ns[:k])
# print(k,c)
def r(num):
return num, k - num, k - num, n - k - (k - num)
def p(num):
a,b,c,d=r(num)
o,z=a+c,b+d
return a*d,o*(o-1)//2+z*(z-1)//2+a*b+c*d,b*c
bs=[[0]*(k+1) for i in range(k+1)]
md=10**9+7
st=[[0]*(k+1)]
st[0][c]=1
deno=n*(n-1)//2
def get_inv(aa,pp):
pp-=2
l=len(bin(pp))-2
ls=[aa]
for i in range(l):
ls.append(ls[-1]*ls[-1]%(pp+2))
# print(ls)
aa=1
for i in range(l):
if (pp>>i)&1:
aa=aa*ls[i]%(pp+2)
return aa%(pp+2)
inv=get_inv(deno,md)
# print('inv of {} : {}'.format(deno,inv))
def matmul(x,y):
ans=[[0]*(k+1) for i in range(len(x))]
for i in range(len(x)):
for j in range(k+1):
t=0
for kk in range(k+1):
t+=x[i][kk]*y[kk][j]%md
ans[i][j]=t%md
return ans
for i in range(k+1):
x=p(i)
for j in range(i-1,i+2):
if 0<=j<=k:
bs[i][j]=x[j-i+1]*inv%md
ls=[bs]
i=0
m=bin(m)[2:][::-1]
# print('m',m)
for i in range(len(m)):
ls.append(matmul(ls[-1],ls[-1]))
# print(ls)
for i in range(len(m)):
c=m[i]
if c=='1':
st=matmul(st,ls[i])
print(st[0][k])
# print(bs)
# print(np.matmul(bs,bs))
```
No
| 5,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A girl named Sonya is studying in the scientific lyceum of the Kingdom of Kremland. The teacher of computer science (Sonya's favorite subject!) invented a task for her.
Given an array a of length n, consisting only of the numbers 0 and 1, and the number k. Exactly k times the following happens:
* Two numbers i and j are chosen equiprobable such that (1 β€ i < j β€ n).
* The numbers in the i and j positions are swapped.
Sonya's task is to find the probability that after all the operations are completed, the a array will be sorted in non-decreasing order. She turned to you for help. Help Sonya solve this problem.
It can be shown that the desired probability is either 0 or it can be represented as P/Q, where P and Q are coprime integers and Q notβ‘ 0~\pmod {10^9+7}.
Input
The first line contains two integers n and k (2 β€ n β€ 100, 1 β€ k β€ 10^9) β the length of the array a and the number of operations.
The second line contains n integers a_1, a_2, β¦, a_n (0 β€ a_i β€ 1) β the description of the array a.
Output
If the desired probability is 0, print 0, otherwise print the value P β
Q^{-1} \pmod {10^9+7}, where P and Q are defined above.
Examples
Input
3 2
0 1 0
Output
333333336
Input
5 1
1 1 1 0 0
Output
0
Input
6 4
1 0 0 1 1 0
Output
968493834
Note
In the first example, all possible variants of the final array a, after applying exactly two operations: (0, 1, 0), (0, 0, 1), (1, 0, 0), (1, 0, 0), (0, 1, 0), (0, 0, 1), (0, 0, 1), (1, 0, 0), (0, 1, 0). Therefore, the answer is 3/9=1/3.
In the second example, the array will not be sorted in non-decreasing order after one operation, therefore the answer is 0.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Codeforces Round #553 (Div. 2)
Problem F. Sonya and Informatics
:author: Kitchen Tong
:mail: kctong529@gmail.com
Please feel free to contact me if you have any question
regarding the implementation below.
"""
__version__ = '1.5'
__date__ = '2019-04-21'
import sys
def binom_dp():
dp = [[-1 for j in range(110)] for i in range(110)]
def calculate(n, k):
if n < k:
return 0
if n == k or k == 0:
return 1
if dp[n][k] > 0:
return dp[n][k]
else:
dp[n][k] = calculate(n-1, k-1) + calculate(n-1, k)
return dp[n][k]
return calculate
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def multiply(A, B, mod):
if not hasattr(B[0], '__len__'):
C = [sum(aij * B[j] % mod for j, aij in enumerate(ai)) for ai in A]
else:
B = list(zip(*B))
C = [multiply(A, B[i], mod) for i in range(len(B[0]))]
return C
def memoize(func):
memo = {}
def wrapper(*args):
M, n, mod = args
if n not in memo:
memo[n] = func(M, n, mod)
return memo[n]
return wrapper
@memoize
def matrix_pow(M, n, mod):
# print(f'n is {n}')
if n == 2:
return multiply(M, M, mod)
if n == 1:
return M
sub_M = matrix_pow(M, n//2, mod)
if n % 2 == 0:
return multiply(sub_M, sub_M, mod)
return multiply(sub_M, matrix_pow(M, n - n//2, mod), mod)
def solve(n, k, a, binom, mod):
ones = sum(a)
zeros = n - ones
M = [[0 for col in range(zeros+1)] for row in range(zeros+1)]
for row in range(max(0, zeros-ones), zeros+1):
pre_zeros = row
pre_ones = zeros - pre_zeros
post_zeros = pre_ones
post_ones = ones - pre_ones
M[row][row] = (pre_ones * post_ones + pre_zeros * post_zeros
+ binom(zeros, 2) + binom(ones, 2))
if row > max(0, zeros-ones):
M[row-1][row] = pre_zeros * post_ones
if row < zeros:
M[row+1][row] = post_zeros * pre_ones
M = [matrix_pow(M, k, mod)[-1]]
b = [0] * (zeros + 1)
b[zeros - sum(a[:zeros])] = 1
C = multiply(M, b, mod)
return C[-1]
def main(argv=None):
mod = int(1e9) + 7
n, k = list(map(int, input().split()))
a = list(map(int, input().split()))
binom = binom_dp()
P = solve(n, k, a, binom, mod)
if P == 0:
print(0)
else:
Q = pow(binom(n, 2), k, mod)
print(P * modinv(Q, mod) % mod)
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
```
No
| 5,102 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
from collections import defaultdict as dfd
d = dfd(int)
arr = input().split()
arr.sort()
for i in arr:
d[i] += 1
if max(d.values())==3 or (arr[0][1]==arr[1][1]==arr[2][1] and int(arr[0][0])+1==int(arr[1][0]) and int(arr[1][0])+1==int(arr[2][0])):
print(0)
elif max(d.values())==2:
print(1)
else:
flag = True
for i in range(len(arr)):
for j in range(i+1, len(arr)):
if arr[i][1]==arr[j][1] and (abs(int(arr[i][0])-int(arr[j][0]))==1 or abs(int(arr[i][0])-int(arr[j][0]))==2):
print(1)
flag = False
break
if not flag:
break
if flag:
print(2)
```
| 5,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
a = sorted(list(map(lambda x: ord(x[0]) + 256 * ord(x[1]), input().split())))
res = 2
if a[1] - a[0] in [0, 1, 2] or a[2] - a[1] in [0, 1, 2]:
res = 1
if (a[0] == a[1] and a[1] == a[2]) or (a[0] + 1 == a[1] and a[1] + 1 == a[2]):
res = 0
print(res)
```
| 5,104 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
x,y,z = input().split()
v = list((x,y,z))
v.sort()
#print(v)
a = int(v[0][0])
b = int(v[1][0])
c = int(v[2][0])
l = v[0][1]
m = v[1][1]
n = v[2][1]
#print(a,b,c,l,m,n)
if x==y and y==z:
print(0)
elif x==y and y!=z or x==z and y!=z or y==z and x!=z:
print(1)
else:
if l==m and m==n:
if b==a+1 and c==b+1:
print(0)
elif b==a+1 and c!=b+1 or c==b+1 and b!=a+1:
print(1)
elif b==a+2 or c==b+2:
print(1)
else:
print(2)
elif l==m and m!=n:
if b==a+1 or b==a+2 or b==a:
print(1)
else:
print(2)
elif m==n and l!=n:
if c==b+1 or c==b or c==b+2:
print(1)
else:
print(2)
elif l==n and n!=m:
if c==a+1 or c==a or c==a+2:
print(1)
else:
print(2)
else:
print(2)
```
| 5,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
l = input().split()
suit = ['m', 'p', 's']
from collections import defaultdict
cnt = defaultdict(lambda : 0)
for i in range(3):
cnt[l[i]] += 1
mini = 10
for i in suit:
for j in range(1, 10):
# shuntsu
if j + 2 <= 9:
cn = 0
for k in range(3):
cn += int("{}{}".format(j+k, i) not in cnt)
mini = min(mini, cn)
# koutsu
mini = min(mini, 3 - cnt["{}{}".format(j, i)])
print(mini)
```
| 5,106 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
# your code goes here
a,b,c=input().split()
d={'m':[],'p':[],'s':[]}
d[a[1]].append(int(a[0]))
d[b[1]].append(int(b[0]))
d[c[1]].append(int(c[0]))
l=['m','p','s']
ans=2
for i in l:
if d[i]==[]:
continue
for j in range(1,10):
ans=min(ans,3-d[i].count(j))
if ans<0:
ans=0
if ans==0:
break
for j in range(1,8):
if j in d[i] and j+1 in d[i] and j+2 in d[i]:
ans=0
if ans==0:
break
if j in d[i] and j+1 in d[i] and j+2 not in d[i]:
ans=1
if j in d[i] and j+2 in d[i] and j+1 not in d[i]:
ans=1
if j not in d[i] and j+1 in d[i] and j+2 in d[i]:
ans=1
if ans==0:
break
print(ans)
```
| 5,107 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
s1,s2,s3 = input().split()
A = []
if (s1[1]==s2[1])and(s2[1]==s3[1]):
if (s1[0]==s2[0])and(s2[0]==s3[0]):
print(0)
exit()
A.append(int(s1[0]))
A.append(int(s2[0]))
A.append(int(s3[0]))
A.sort()
if (A[0]==A[1]-1) and(A[0]==A[2]-2):
print(0)
exit()
if (s1[1]==s2[1]):
if (s1[0]==s2[0]):
print(1)
exit()
if (int(s1[0])==(int(s2[0])+1))or(int(s1[0])==(int(s2[0])-1)):
print(1)
exit()
if (int(s1[0])==(int(s2[0])+2))or(int(s1[0])==(int(s2[0])-2)):
print(1)
exit()
if (s1[1] == s3[1]):
if (s1[0]==s3[0]):
print(1)
exit()
if (int(s1[0])==(int(s3[0])+1))or(int(s1[0])==(int(s3[0])-1)):
print(1)
exit()
if (int(s1[0])==(int(s3[0])+2))or(int(s1[0])==(int(s3[0])-2)):
print(1)
exit()
if (s2[1]==s3[1]):
if (s2[0]==s3[0]):
print(1)
exit()
if (int(s2[0])==(int(s3[0])+1))or(int(s2[0])==(int(s3[0])-1)):
print(1)
exit()
if (int(s2[0])==(int(s3[0])+2))or(int(s2[0])==(int(s3[0])-2)):
print(1)
exit()
print(2)
```
| 5,108 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
import collections
a=input().split()
a.sort()
if a[0]==a[1] and a[1]==a[2]:
print(0)
elif a[0][1]==a[1][1] and a[1][1]==a[2][1] and abs(int(a[1][0])-int(a[0][0]))==1 and abs(int(a[2][0])-int(a[1][0]))==1:
print("0")
elif a[0]==a[1] or a[1]==a[2] or a[2]==a[0]:
print("1")
elif a[0][1]==a[1][1] and (abs(int(a[1][0])-int(a[0][0]))==1 or abs(int(a[1][0])-int(a[0][0]))==2) :
print("1")
elif a[1][1]==a[2][1] and (abs(int(a[2][0])-int(a[1][0]))==1 or abs(int(a[2][0])-int(a[1][0]))==2):
print("1")
elif a[0][1]==a[2][1] and (abs(int(a[2][0])-int(a[0][0]))==1 or abs(int(a[2][0])-int(a[0][0]))==2):
print("1")
else:
print("2")
```
| 5,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Tags: brute force, implementation
Correct Solution:
```
arr=list(map(str,input().split()))
num1=int(arr[0][0])
num2=int(arr[1][0])
num3=int(arr[2][0])
str1=arr[0][1]
str2=arr[1][1]
str3=arr[2][1]
if str1==str2 and str2==str3:
if num1==num2 and num2==num3:
print(0)
else:
arr2=[num1,num2,num3]
arr2=sorted(arr2)
if arr2[0]==arr2[1]-1 and arr2[1]==arr2[2]-1:
print(0)
else:
if 0<=abs(num1-num2)<=2:
print(1)
elif 0<=abs(num1-num3)<=2:
print(1)
elif 0<=abs(num2-num3)<=2:
print(1)
else:
print(2)
elif str1==str2:
if abs(num1-num2)==0 or abs(num1-num2)==1 or abs(num1-num2)==2:
print(1)
else:
print(2)
elif str1==str3:
if abs(num1-num3)==0 or abs(num1-num3)==1 or abs(num1-num3)==2:
print(1)
else:
print(2)
elif str2==str3:
if abs(num2-num3)==0 or abs(num2-num3)==1 or abs(num2-num3)==2:
print(1)
else:
print(2)
else:
print(2)
```
| 5,110 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
m={"m":[0]*9, "s":[0]*9, "p":[0]*9}
for s in input().split():
m[s[1]][int(s[0])-1]+=1
ans = 2
for c in "smp":
l = m[c]
if(max(l)>=2):
ans = min(ans, 3-max(l))
else:
for i in range(7):
sm = sum(l[i:i+3])
ans = min(ans, 3-sm)
print(ans)
```
Yes
| 5,111 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
import bisect
import collections
import copy
import functools
import heapq
import itertools
import math
import random
import re
import sys
import time
import string
from typing import *
sys.setrecursionlimit(99999)
arr = list(input().split())
arr.sort()
ans = 3
cs = collections.Counter(arr)
def check(ap):
cp = collections.Counter(ap)
c = 0
for k, v in cs.items():
c += min(v, cp[k])
return 3 - c
for i in range(1, 10):
ans = min(ans, check([str(i) + 's', str(i) + 's', str(i) + 's']))
ans = min(ans, check([str(i) + 'p', str(i) + 'p', str(i) + 'p']))
ans = min(ans, check([str(i) + 'm', str(i) + 'm', str(i) + 'm']))
if i <= 7:
ans = min(ans,
check([str(i) + 's',
str(i + 1) + 's',
str(i + 2) + 's']))
ans = min(ans,
check([str(i) + 'p',
str(i + 1) + 'p',
str(i + 2) + 'p']))
ans = min(ans,
check([str(i) + 'm',
str(i + 1) + 'm',
str(i + 2) + 'm']))
print(ans)
```
Yes
| 5,112 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
#include<bits/stdc++.h>
#include<stdio.h> //per fare input output con scanf and printf
#include<stdlib.h> //per fare qsort e bsearch
#include<string.h> // per fare strcpy(sarrivo, spartenza) strcat(str, aggiungo) strcmp(a,b) che da 0 se sono uguali
#include<math.h>
#include<algorithm>
#include<iostream>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#using namespace std;
#define ld long double
#define ll long long int
#define vi vector <ll>
#define pi pair <ll, ll>
#define binary(v, el) binary_search((v).begin(), (v).end(), (el))
#define PB push_back
#define MP make_pair
#define F first
#define S second
x,y,z = list(map(str, input().strip().split()))
def cazzu(a,b,c):
if a==b==c:
return 1
else:
return 0
def shizu(a,b,c):
x = int(a[0])
y = int(b[0])
z = int(c[0])
l = [x,y,z]
l.sort()
if a[1]==b[1]==c[1] and l[1]-l[0] == 1 and l[2]-l[1]==1:
return 1
else:
return 0
if cazzu(x,y,z) or shizu(x,y,z):
print(0)
else:
flag = 0
for i in ['p','m','s']:
for j in ['1','2','3','4','5','6','7','8','9']:
w = j+i
if cazzu(x,y,w) or shizu(x,y,w) or cazzu(x,w,z) or shizu(x,w,z) or cazzu(w,y,z) or shizu(w,y,z):
flag = 1
if flag == 1:
print(1)
else:
print(2)
```
Yes
| 5,113 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
'''
Auther: ghoshashis545 Ashis Ghosh
College: jalpaiguri Govt Enggineering College
'''
from os import path
import sys
from heapq import heappush,heappop
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input().rstrip()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
# mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]
def bo(i):
return ord(i)-ord('a')
file=1
def solve():
# for _ in range(ii()):
s = list(map(str,input().split()))
m = {}
m['s'] = []
m['p'] = []
m['m'] = []
for i in s:
m[i[1]].append(int(i[0]))
if len(set(s))==1:
print(0)
elif(len(set(s))==2):
print(1)
elif(len(m['s'])==3):
p = [m['s'][0],m['s'][1],m['s'][2]]
p.sort()
if p[1]-p[0]==1 and p[2]-p[1]==1:
print(0)
elif(p[1]-p[0]==2 or p[2]-p[1]==2 or p[1]-p[0]==1 or p[2]-p[1]==1):
print(1)
else:
print(2)
elif(len(m['p'])==3):
p = [m['p'][0],m['p'][1],m['p'][2]]
p.sort()
if p[1]-p[0]==1 and p[2]-p[1]==1:
print(0)
elif(p[1]-p[0]==2 or p[2]-p[1]==2 or p[1]-p[0]==1 or p[2]-p[1]==1):
print(1)
else:
print(2)
elif(len(m['m'])==3):
p = [m['m'][0],m['m'][1],m['m'][2]]
p.sort()
if p[1]-p[0]==1 and p[2]-p[1]==1:
print(0)
elif(p[1]-p[0]==2 or p[2]-p[1]==2 or p[1]-p[0]==1 or p[2]-p[1]==1):
print(1)
else:
print(2)
elif(len(m['s'])==2 and (abs(m['s'][0]-m['s'][1]) == 1 or abs(m['s'][0]-m['s'][1])==2)):
print(1)
elif(len(m['p'])==2 and (abs(m['p'][0]-m['p'][1]) == 1 or abs(m['p'][0]-m['p'][1])==2)):
print(1)
elif(len(m['m'])== 2 and (abs(m['m'][0]-m['m'][1]) == 1 or abs(m['m'][0]-m['m'][1])==2)):
print(1)
else:
print(2)
if __name__ =="__main__":
if(file):
if path.exists('input.txt'):
sys.stdin=open('input.txt', 'r')
sys.stdout=open('output.txt','w')
else:
input=sys.stdin.readline
solve()
```
Yes
| 5,114 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
s=input().split()
l=[]
s.sort()
for i in s:
l.append(int(i[0]))
l.append(i[1])
if l[0]==l[2] and l[1]==l[3]:
if l[0]==l[4] and l[1]==l[5]:
print(0)
else:
print(1)
elif l[4]==l[2] and l[5]==l[3]:
print(1)
elif l[0]+1==l[2] and l[1]==l[3]:
if l[2]+1==l[4] and l[3]==l[5]:
print(0)
else:
print(1)
elif l[2]+1==l[4] and l[5]==l[3]:
print(1)
elif l[0]+2==l[4] and l[1]==l[5]:
print(1)
else:
print(2)
```
No
| 5,115 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
def process1(n):
Dicts = {1:'0 A',
2:'1 B',
3:'2 A',
0:'1 A'}
mod = n%4
return Dicts[mod]
def tile3(n):
list = n.split(" ")
list = sorted(list)
print(list)
list2 = []
for i in range(len(list)):
count = 0
for j in range(len(list)):
if list[i]==list[j]:
count+=1
list2.append(count)
if max(list2)>=3: # TrΖ°α»ng hợp cΓ³ 3 tile giα»ng nhau
return 0
elif max(list2)==2 and min(list2)>=1: # TrΖ°α»ng hợp cΓ³ 2 tile giα»ng nhau
return 1
elif list2.count(1)>=3: # TrΖ°α»ng hợp cαΊ£ 3 tile khΓ‘c nhau
for i in list:
if int(list[0][0])+2==int(list[1][0])+1==int(list[2][0]) and list[0][1]==list[1][1]==list[2][1]:
return 0
elif (list[0][1]!=list[1][1] and list[1][1]!=list[2][1] and list[2][1] != list[0][1]) or \
(int(list[1][0])-int(list[0][0])>2) and (int(list[2][0])-int(list[1][0])>2):
return 2
elif (list[0][1]==list[1][1] and list[1][1]!=list[2][1] and int(list[0][0])+1==int(list[1][0])) or \
(list[1][1]==list[2][1] and list[1][1]!=list[0][1] and int(list[1][0])+1==int(list[2][0])):
return 1
else: return 1
n = input()
s = tile3(n)
print(s)
```
No
| 5,116 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
arr = list(input().split())
x = arr[0]
y = arr[1]
z = arr[2]
if x==y==z:
print(0)
elif x[1] == y[1] == z[1]:
arr = []
arr.append(int(x[0]))
arr.append(int(y[0]))
arr.append(int(z[0]))
arr.sort()
#print(arr)
if arr[1]-arr[0]==arr[2]-arr[1]==1:
print(0)
elif arr[1]-arr[0]==1:
print(1)
elif arr[2]-arr[1]==1:
print(1)
elif arr[2]-arr[0]==1:
print(1)
else:
print(2)
elif x==y or y==z or z==x:
print(1)
elif x[1]==y[1] and abs(int(x[0])-int(y[0]))==1:
print(1)
elif y[1]==z[1] and abs(int(y[0])-int(z[0]))==1:
print(1)
elif z[1]==x[1] and abs(int(z[0])-int(x[0]))==1:
print(1)
else:
print(2)
```
No
| 5,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Tokitsukaze is playing a game derivated from Japanese mahjong. In this game, she has three tiles in her hand. Each tile she owns is a suited tile, which means it has a suit (manzu, pinzu or souzu) and a number (a digit ranged from 1 to 9). In this problem, we use one digit and one lowercase letter, which is the first character of the suit, to represent a suited tile. All possible suited tiles are represented as 1m, 2m, β¦, 9m, 1p, 2p, β¦, 9p, 1s, 2s, β¦, 9s.
In order to win the game, she must have at least one mentsu (described below) in her hand, so sometimes she should draw extra suited tiles. After drawing a tile, the number of her tiles increases by one. She can draw any tiles she wants, including those already in her hand.
Do you know the minimum number of extra suited tiles she needs to draw so that she can win?
Here are some useful definitions in this game:
* A mentsu, also known as meld, is formed by a koutsu or a shuntsu;
* A koutsu, also known as triplet, is made of three identical tiles, such as [1m, 1m, 1m], however, [1m, 1p, 1s] or [1m, 4m, 7m] is NOT a koutsu;
* A shuntsu, also known as sequence, is made of three sequential numbered tiles in the same suit, such as [1m, 2m, 3m] and [5s, 7s, 6s], however, [9m, 1m, 2m] or [1m, 2p, 3s] is NOT a shuntsu.
Some examples:
* [2m, 3p, 2s, 4m, 1s, 2s, 4s] β it contains no koutsu or shuntsu, so it includes no mentsu;
* [4s, 3m, 3p, 4s, 5p, 4s, 5p] β it contains a koutsu, [4s, 4s, 4s], but no shuntsu, so it includes a mentsu;
* [5p, 5s, 9m, 4p, 1s, 7p, 7m, 6p] β it contains no koutsu but a shuntsu, [5p, 4p, 6p] or [5p, 7p, 6p], so it includes a mentsu.
Note that the order of tiles is unnecessary and you can assume the number of each type of suited tiles she can draw is infinite.
Input
The only line contains three strings β the tiles in Tokitsukaze's hand. For each string, the first character is a digit ranged from 1 to 9 and the second character is m, p or s.
Output
Print a single integer β the minimum number of extra suited tiles she needs to draw.
Examples
Input
1s 2s 3s
Output
0
Input
9m 9m 9m
Output
0
Input
3p 9m 2p
Output
1
Note
In the first example, Tokitsukaze already has a shuntsu.
In the second example, Tokitsukaze already has a koutsu.
In the third example, Tokitsukaze can get a shuntsu by drawing one suited tile β 1p or 4p. The resulting tiles will be [3p, 9m, 2p, 1p] or [3p, 9m, 2p, 4p].
Submitted Solution:
```
a,b,c = map(str, input().split())
a = a[1]+a[0]
b = b[1]+b[0]
c = c[1]+c[0]
n = [a,b,c]
m = [0]*9
p = [0]*9
s = [0]*9
for i in range(3):
if(n[i][0]=="m"):
m[int(n[i][1])-1]+=1
if(n[i][0]=="p"):
p[int(n[i][1])-1]+=1
if(n[i][0]=="s"):
s[int(n[i][1])-1]+=1
ans = 2
#print(m,p,s)
for i in range(9):
if(3-m[i]<ans):
ans = 3-m[i]
if(0<i and i<8):
if(3-m[i-1]-m[i]-m[i+1]<ans):
ans = 3-m[i-1]-m[i]-m[i+1]
if(3-s[i]<ans):
ans = 3-s[i]
if(0<i and i<8):
if(3-s[i-1]-s[i]-s[i+1]<ans):
#print(23)
ans = 3-s[i-1]-s[i]-s[i+1]
#print(ans, 9)
if(3-p[i]<ans):
ans = 3-p[i]
#print(3-s[i-1]-s[i]-s[i+1])
if(0<i and i<8):
if(3-p[i-1]-p[i]-p[i+1]<ans):
ans = 3-p[i-1]-p[i]-p[i+1]
print(ans)
```
No
| 5,118 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
Input
The first line contains two positive integers n and k (1 β€ n β€ 1000 and 1 β€ k β€ n) β the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 β€ i β€ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
Output
Print the single number β the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
Examples
Input
5 5
0 1 0 1 0
Output
2
Input
2 1
1 1
Output
1
Submitted Solution:
```
f=open("input.txt","r")
i=0
for x in f.readlines():
if i==0:
l1=x.split()
i+=1
elif i==1: l2=x.split()
f.close()
for i in range(int(l1[0])):
k=int(l1[1])-1
if l2[k]=='1':
k+=1
break
s=0
while s==0:
s=int(l2[k])
k+=1
if k==int(l1[0]): k=0
f=open("output.txt","w+")
f.write(str(k))
f.close()
```
No
| 5,119 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
Input
The first line contains two positive integers n and k (1 β€ n β€ 1000 and 1 β€ k β€ n) β the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 β€ i β€ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
Output
Print the single number β the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
Examples
Input
5 5
0 1 0 1 0
Output
2
Input
2 1
1 1
Output
1
Submitted Solution:
```
import sys
sys.stdin = open('input.txt','r')
sys.stdout = open('output.txt','w')
n,m=map(int,input().split())
l=list(map(int,input().split()))
c=0
if n==m:
j=0
else:
j=m-1
while c==0:
if l[j]==1:
c=j+1
# print(c)
break
if j==n-1:
j=0
else:
j+=1
# j=j+1%(n)
print(c)
```
No
| 5,120 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
Input
The first line contains two positive integers n and k (1 β€ n β€ 1000 and 1 β€ k β€ n) β the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 β€ i β€ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
Output
Print the single number β the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
Examples
Input
5 5
0 1 0 1 0
Output
2
Input
2 1
1 1
Output
1
Submitted Solution:
```
with open("input.txt", "r") as file:
firstLine = list(map(int, file.readline().strip().split(" ")))
secondLine = list(map(int, file.readline().strip().split(" ")))
numTables = firstLine[0]
numPointed = firstLine[1]
line = numPointed % numTables
while(secondLine[line-1] == 0):
numPointed += 1
line = numPointed % numTables
# try:
output = open("output.txt", "w+")
output.write(str(line))
# except Exception as e:
# print(e)
# finally:
output.close
```
No
| 5,121 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A team quiz game called "What? Where? When?" is very popular in Berland. The game is centered on two teams competing. They are the team of six Experts versus the team of the Audience. A person from the audience asks a question and the experts are allowed a minute on brainstorming and finding the right answer to the question. All it takes to answer a typical question is general knowledge and common logic. The question sent be the audience are in envelops lain out in a circle on a round table. Each envelop is marked by the name of the asker's town. Each question is positioned in a separate sector. In the centre of the table is a spinning arrow. Thus, the table rather resembles a roulette table with no ball but with a spinning arrow instead. The host sets off the spinning arrow to choose a question for the experts: when the arrow stops spinning, the question it is pointing at is chosen. If the arrow points at the question that has already been asked, the host chooses the next unanswered question in the clockwise direction. Your task is to determine which will be the number of the next asked question if the arrow points at sector number k.
Input
The first line contains two positive integers n and k (1 β€ n β€ 1000 and 1 β€ k β€ n) β the numbers of sectors on the table and the number of the sector where the arrow is pointing. The second line contains n numbers: ai = 0 if the question from sector i has already been asked and ai = 1 if the question from sector i hasn't been asked yet (1 β€ i β€ n). The sectors are given in the clockwise order, the first sector follows after the n-th one.
Output
Print the single number β the number of the sector containing the question the experts will be asked. It is guaranteed that the answer exists, that is that not all the questions have already been asked.
Examples
Input
5 5
0 1 0 1 0
Output
2
Input
2 1
1 1
Output
1
Submitted Solution:
```
with open("input.txt", 'r') as f1:
n, k = map(int, f1.readline().split())
arr = list(map(int, f1.readline().split()))
if arr[k - 1] == 1:
with open("output.txt", 'w') as f2:
f2.write(str(k+1)+"\n")
else:
k-=1
while True:
k = (k+1)%n
if arr[k] == 1:
with open("output.txt", 'w') as f2:
f2.write(str(k+1)+"\n")
break
```
No
| 5,122 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Tags: brute force, combinatorics, number theory
Correct Solution:
```
import math
def good(x):
while x > 0:
if x % 10 != 4 and x % 10 != 7:
return False
x //=10
return True
n, k = map(int, input().split())
l = 1
r = n
if n >= 15:
l = n-14
if n <= 15 and math.factorial(n) < k:
print(-1)
else:
L = r - l + 1
a = []
for i in range(L):
a.append(i)
b = []
k -= 1
for i in range(L):
x = k//math.factorial(L-i-1)
y = a[x]
b.append(y+l)
a.remove(y)
k -= x * math.factorial(L-i-1)
c = []
if 4 < l:
c.append(4)
if 7 < l:
c.append(7)
ans = 0
while len(c) > 0:
ans += len(c)
cc = []
for x in c:
if x * 10 + 4 < l:
cc.append(x * 10 + 4)
if x * 10 + 7 < l:
cc.append(x * 10 + 7)
c = cc
for i in range(L):
if good(i+l) and good(b[i]):
ans += 1
print(ans)
```
| 5,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Tags: brute force, combinatorics, number theory
Correct Solution:
```
def lucky(x):
s=str(x)
return s.count('4')+s.count('7')==len(s)
def Gen_lucky(n):
if(len(n)==1):
if(n<"4"):
return 0
if(n<"7"):
return 1
return 2
s=str(n)
if(s[0]<'4'):
return 0
if(s[0]=='4'):
return Gen_lucky(s[1:])
if(s[0]<'7'):
return 2**(len(s)-1)
if(s[0]=='7'):
return 2**(len(s)-1)+Gen_lucky(s[1:])
else:
return 2**len(s)
def Form(X,k):
if(k==0):
return X
for i in range(len(X)):
if(k>=F[len(X)-i-1]):
h=k//F[len(X)-i-1]
r=k%F[len(X)-i-1]
G=list(X[i+1:])
G.remove(X[i+h])
G=[X[i]]+G
return Form(X[:i]+[X[i+h]]+G,r)
p=1
F=[1]
i=1
while(p<=10**15):
p*=i
F.append(p)
i+=1
n,k=map(int,input().split())
if(n<=14):
if(k>F[n]):
print(-1)
else:
L=Form(list(range(1,n+1)),k-1)
x=0
for i in range(n):
if(lucky(i+1) and lucky(L[i])):
x+=1
print(x)
else:
L=Form(list(range(n-14,n+1)),k-1)
ss=str(n-15)
x=0
for i in range(1,len(ss)):
x+=2**i
x+=Gen_lucky(ss)
for i in range(n-14,n+1):
if(lucky(L[i-n+14]) and lucky(i)):
x+=1
print(x)
```
| 5,124 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Submitted Solution:
```
def lucky(x):
s=str(x)
return s.count('4')+s.count('7')==len(s)
def Gen_lucky(n):
s=str(n)
if(len(s)==1):
if(s[0]>='7'):
return 2
if(s[0]>='4'):
return 1
return 0
x=0
for i in range(1,len(s)):
x+=2**i
if(s[0]<'4'):
return x
if(s[0]>'7'):
return x+2**len(s)
if(s[0]=='5' or s[0]=='6'):
return x+(2**(len(s)-1))
if(s[0]=='7'):
x+=2**(len(s)-1)
x+=Gen_lucky(s[1:])
return x
def Form(X,k):
if(k==0):
return X
for i in range(len(X)):
if(k>=F[len(X)-i-1]):
h=k//F[len(X)-i-1]
r=k%F[len(X)-i-1]
G=list(X[i+1:])
G.remove(X[i+h])
G=[X[i]]+G
return Form(X[:i]+[X[i+h]]+G,r)
p=1
F=[1]
i=1
while(p<=10**15):
p*=i
F.append(p)
i+=1
n,k=map(int,input().split())
if(n<=14):
if(k>F[n]):
print(-1)
else:
L=Form(list(range(1,n+1)),k-1)
x=0
for i in range(n):
if(lucky(i+1) and lucky(L[i])):
x+=1
print(x)
else:
L=Form(list(range(n-14,n+1)),k-1)
x=Gen_lucky(n-15)
for i in range(n-14,n+1):
if(lucky(L[i-n+14]) and lucky(i)):
x+=1
print(x)
```
No
| 5,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Submitted Solution:
```
def lucky(x):
s=str(x)
return s.count('4')+s.count('7')==len(s)
def Gen_lucky(n):
s=str(n)
if(len(s)==1):
if(s[0]=='4' or s[0]=='7'):
return 1
return 0
x=0
for i in range(1,len(s)):
x+=2**i
if(s[0]<'4'):
return x
if(s[0]>'7'):
return x+2**len(s)
if(s[0]=='5' or s[0]=='6'):
return x+(2**(len(s)-1))
if(s[0]=='7'):
x+=2**(len(s)-1)
x+=Getlucky(s[1:])
return x
def Form(X,k):
if(k==0):
return X
for i in range(len(X)):
if(k>=F[len(X)-i-1]):
h=k//F[len(X)-i-1]
r=k%F[len(X)-i-1]
G=list(X[i+1:])
G.remove(X[i+h])
G=[X[i]]+G
return Form(X[:i]+[X[i+h]]+G,r)
p=1
F=[1]
i=1
while(p<=10**10):
p*=i
F.append(p)
i+=1
n,k=map(int,input().split())
if(n<=14):
if(k>F[n]):
print(-1)
else:
L=Form(list(range(1,n+1)),k-1)
x=0
for i in range(n):
if(lucky(i+1) and lucky(L[i])):
x+=1
print(x)
else:
L=Form(list(range(n-13,n+1)),k-1)
x=Gen_lucky(n-14)
for i in range(n-13,n+1):
if(lucky(L[i-n+13]) and lucky(i)):
x+=1
print(x)
```
No
| 5,126 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Submitted Solution:
```
def lucky(x):
s=str(x)
return s.count('4')+s.count('7')==len(s)
def Gen_lucky(n):
s=str(n)
if(len(s)==1):
if(s[0]=='4' or s[0]=='7'):
return 1
return 0
x=0
for i in range(1,len(s)):
x+=2**i
if(s[0]<'4'):
return x
if(s[0]>'7'):
return x+2**len(s)
if(s[0]=='5' or s[0]=='6'):
return x+(2**(len(s)-1))
if(s[0]=='7'):
x+=2**(len(s)-1)
x+=Getlucky(s[1:])
return x
def Form(X,k):
if(k==0):
return X
for i in range(len(X)):
if(k>=F[len(X)-i-1]):
h=k//F[len(X)-i-1]
r=k%F[len(X)-i-1]
X[i],X[i+h]=X[i+h],X[i]
return [X[0]]+Form(X[1:],r)
p=1
F=[1]
i=1
while(p<=10**10):
p*=i
F.append(p)
i+=1
n,k=map(int,input().split())
if(n<=15):
L=Form(list(range(1,n+1)),k-1)
x=0
for i in range(n):
if(lucky(i+1) and lucky(L[i])):
x+=1
print(x)
else:
L=Form(list(range(n-13,n+1)),k-1)
x=Gen_lucky(n-14)
for i in range(n-13,n+1):
if(lucky(L[i-n+13]) and lucky(i)):
x+=1
print(x)
```
No
| 5,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers. Everybody knows that lucky numbers are positive integers whose decimal representation contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
One day Petya dreamt of a lexicographically k-th permutation of integers from 1 to n. Determine how many lucky numbers in the permutation are located on the positions whose indexes are also lucky numbers.
Input
The first line contains two integers n and k (1 β€ n, k β€ 109) β the number of elements in the permutation and the lexicographical number of the permutation.
Output
If the k-th permutation of numbers from 1 to n does not exist, print the single number "-1" (without the quotes). Otherwise, print the answer to the problem: the number of such indexes i, that i and ai are both lucky numbers.
Examples
Input
7 4
Output
1
Input
4 7
Output
1
Note
A permutation is an ordered set of n elements, where each integer from 1 to n occurs exactly once. The element of permutation in position with index i is denoted as ai (1 β€ i β€ n). Permutation a is lexicographically smaller that permutation b if there is such a i (1 β€ i β€ n), that ai < bi, and for any j (1 β€ j < i) aj = bj. Let's make a list of all possible permutations of n elements and sort it in the order of lexicographical increasing. Then the lexicographically k-th permutation is the k-th element of this list of permutations.
In the first sample the permutation looks like that:
1 2 3 4 6 7 5
The only suitable position is 4.
In the second sample the permutation looks like that:
2 1 3 4
The only suitable position is 4.
Submitted Solution:
```
print(1)
```
No
| 5,128 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
def main():
def getLowestPossibleMedian(lr,n):
lr.sort(key=lambda x:x[0]) # sort by l asc
return lr[n//2][0]
def checkPossibleMedian(lr,guess,n,s):
potentialUpper=[] # potential candidates for the upper half
lower=[]
lowerCnts=n//2
upperCnts=n-lowerCnts
for l,r in lr:
if r>=guess:
potentialUpper.append([l,r])
else:
lower.append([l,r])
if len(potentialUpper)<upperCnts:
return False
potentialUpper.sort(key=lambda x:x[0],reverse=True) # sort by l desc
# for the upper, take the ones with the highest l, leaving the rest for lower
for i in range(upperCnts,len(potentialUpper)):
lower.append(potentialUpper[i])
assert(len(lower))==lowerCnts
requiredSalary=0
for l,r in lower:
requiredSalary+=l
for i in range(upperCnts):
requiredSalary+=max(guess,potentialUpper[i][0])
return requiredSalary<=s
t=int(input())
allans=[]
for _ in range(t):
n,s=readIntArr()
lr=[]
for __ in range(n):
lr.append(readIntArr())
m=getLowestPossibleMedian(lr,n)
ans=m
b=s
while b>0:
while checkPossibleMedian(lr,ans+b,n,s):
ans+=b
b//=2
allans.append(ans)
multiLineArrayPrint(allans)
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(defaultVal,dimensionArr): # eg. makeArr(0,[n,m])
dv=defaultVal;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(x,y):
print('? {} {}'.format(x,y))
sys.stdout.flush()
return int(input())
def answerInteractive(ans):
print('! {}'.format(ans))
sys.stdout.flush()
inf=float('inf')
# MOD=10**9+7
MOD=998244353
for _abc in range(1):
main()
```
| 5,129 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
def solve(mid):
ans = 0
cnt = 0
tmp = []
for i in range(n):
if info[i][1] < mid:
ans += info[i][0]
elif mid < info[i][0]:
ans += info[i][0]
cnt += 1
else:
tmp.append(info[i][0])
tmp.sort(reverse = True)
nokori = (n+1) // 2 - cnt
for i in tmp:
if nokori > 0:
ans += mid
nokori -= 1
else:
ans += i
if ans <= s and nokori <= 0:
return True
else:
return False
q = int(input())
ans = [0]*q
for qi in range(q):
n, s = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n)]
ok = 0
ng = s + 1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if solve(mid):
ok = mid
else:
ng = mid
ans[qi] = ok
print('\n'.join(map(str, ans)))
```
| 5,130 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
import sys
import bisect
input=sys.stdin.readline
def checker(rem_,lower_):
sum_=0
a=[]
b=[]
for i in range(n):
if lower[i][1]>=rem_:
a.append(lower[i][0])
else:
b.append(lower[i][0])
a.sort(reverse=True)
if len(a) > n//2 and sum([max(j, rem_) for j in a[:n//2+1]]) + sum(a[n//2+1:]) + sum(b) <= s:
return(True)
return(False)
t=int(input())
for i in range(t):
lower=[]
higher=[]
n,s=map(int,input().split())
for i in range(n):
l,r=map(int,input().split())
lower.append([l,r])
higher.append(l)
higher.sort()
if sum(higher)==s:
print(higher[n//2])
else:
beg=1
end=1000000001
while end-beg>1:
mid=(beg+end)//2
#print(beg,end)
if checker(mid,lower):
beg=mid
else:
end=mid
print(beg)
```
| 5,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
N, S = map(int, input().split())
LR = [list(map(int, input().split())) for _ in range(N)]
Query.append((N, S, LR))
for N, S, LR in Query:
G = []
for L, _ in LR:
G.append(L)
G.sort()
l = G[N//2]
r = S+1
while r - l > 1:
m = (l+r)//2
A = []
B = []
C = []
for L, R in LR:
if L <= m <= R:
C.append(L)
elif R < m:
A.append(L)
else:
B.append(L)
C.sort()
if len(A) < N//2+1 <= len(A)+len(C):
if sum(A)+sum(B)+sum(C[:N//2-len(A)]) + m*(len(A)+len(C)-N//2) <= S:
l = m
else:
r = m
else:
r = m
print(l)
```
| 5,132 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
from sys import stdin
from operator import itemgetter, attrgetter
def check(salary, mid, s):
cnt = 0
for i in range(len(salary)):
if salary[i][0] > mid:
s -= salary[i][0]
cnt += 1
elif salary[i][0] <= mid and salary[i][1] >= mid:
if cnt < (len(salary) + 1) // 2:
s -= mid
cnt += 1
else:
s -= salary[i][0]
elif salary[i][1] < mid:
s -= salary[i][0]
if cnt >= (len(salary) + 1) // 2 and s >= 0:
return True
else:
return False
t = int(stdin.buffer.readline())
for _ in range(t):
salary = list()
n, s = map(int, stdin.buffer.readline().split())
ansL, ansR = 0x3f3f3f3f3f3f3f3f, -1
for i in range(n):
l, r = map(int, stdin.buffer.readline().split())
ansL = min(ansL, l)
ansR = max(ansR, r)
salary.append((l, r))
salary = sorted(salary, key=itemgetter(0), reverse=True)
l = ansL
r = ansR
ans = None
while l <= r:
mid = (l + r) // 2
if check(salary, mid, s):
ans = mid
l = mid + 1
else:
r = mid - 1
print(ans)
```
| 5,133 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
def solve(mid):
ans = 0
cnt = 0
tmp = []
for i in range(n):
l, r = info[i]
if r < mid:
ans += l
elif mid < l:
ans += l
cnt += 1
else:
tmp.append(l)
tmp.sort(reverse = True)
nokori = (n+1) // 2 - cnt
for i in tmp:
if nokori > 0:
ans += mid
nokori -= 1
else:
ans += i
if ans <= s and nokori <= 0:
return True
else:
return False
q = int(input())
for _ in range(q):
n, s = map(int, input().split())
info = [list(map(int, input().split())) for i in range(n)]
ok = 0
ng = s + 1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if solve(mid):
ok = mid
else:
ng = mid
print(ok)
```
| 5,134 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
MOD = 10 ** 9 + 7
def bisearch_max(mn, mx, func):
ok = mn
ng = mx
while ok+1 < ng:
mid = (ok+ng) // 2
if func(mid):
ok = mid
else:
ng = mid
return ok
def check(m):
midcnt = N//2 + 1
A1, A2, A3 = [], [], []
cnt = k = 0
for l, r in LR:
if r < m:
A1.append((l, r))
k += l
elif m <= l:
A2.append((l ,r))
cnt += 1
k += l
else:
A3.append((l, r))
k += l
if k > K:
return False
if cnt+len(A3) < midcnt:
return False
if cnt >= midcnt and k <= K:
return True
A3.sort(reverse=True)
for l, r in A3:
cnt += 1
k += m - l
if k > K:
return False
if cnt >= midcnt and k <= K:
return True
return False
for _ in range(INT()):
N, K = MAP()
LR = []
for i in range(N):
l, r = MAP()
LR.append((l, r))
res = bisearch_max(0, 10**9+1, check)
print(res)
```
| 5,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Tags: binary search, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
import heapq
sys.setrecursionlimit(100000)
def getN():
return int(input())
def getList():
return list(map(int, input().split()))
def solve():
ls, rs = [], []
n, money = getList()
sals = []
for _ in range(n):
a, b = getList()
sals.append((a, b))
# ls.sort()
# rs.sort()
ans_mx = 10**10
ans_mn = 0
while(ans_mx - ans_mn > 1):
# print(ans_mx, ans_mn)
tmp = 0
heap = []
mid = (ans_mn + ans_mx) // 2
for sal in sals:
if sal[1] < mid:
tmp += sal[0]
else:
heapq.heappush(heap, (-sal[0], -sal[1]))
# print(len(heap))
if len(heap) < (n + 1) // 2:
ans_mx = mid
continue
high = 0
tgt = n // 2
# print(heap)
while(heap):
sal_cur = heapq.heappop(heap)
if high <= tgt:
tmp += max(mid, -sal_cur[0])
high += 1
else:
tmp += -sal_cur[0]
if tmp <= money:
ans_mn = mid
else:
ans_mx = mid
# print(tmp)
# ================================
# print(ans_mx, ans_mn)
tmp = 0
heap = []
mid = ans_mx
# print("mid", mid)
for sal in sals:
if sal[1] < mid:
tmp += sal[0]
else:
heapq.heappush(heap, (-sal[0], -sal[1]))
if len(heap) < (n + 1) // 2:
print(ans_mn)
return
high = 0
tgt = n // 2
# print(heap)
while (heap):
sal_cur = heapq.heappop(heap)
# print(sal_cur)
if high <= tgt:
tmp += max(mid, -sal_cur[0])
high += 1
else:
tmp += -sal_cur[0]
# print(tmp)
if tmp <= money:
print(mid)
return
else:
print(ans_mn)
return
# print(tmp)
def main():
t = getN()
for times in range(t):
solve()
if __name__ == "__main__":
main()
"""
1
3 26
10 12
1 4
10 11
1
1 100
1 1
1
3 6
1 1000
2 1000
3 1000
1
9 100
2 4
3 5
8 100
25 100
2 39
1 2
23 40
1 20
2 10
"""
```
| 5,136 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
#!/usr/bin/env python3
import sys
INF = 10**9
sys.setrecursionlimit(10**8)
input = sys.stdin.buffer.readline
t = int(input())
for i in range(t):
n, s = [int(item) for item in input().split()]
lr = []
for j in range(n):
l, r = [int(item) for item in input().split()]
lr.append((l, r))
lft = 0; rgt = 10**9+1
while rgt - lft > 1:
mid = (lft + rgt) // 2
minimum_cost = 0
takable = []
for l, r in lr:
minimum_cost += l
if mid <= r:
takable.append(max(l - mid, 0) - l)
if len(takable) < (n // 2 + 1):
rgt = mid
continue
takable.sort()
cost = sum(takable[:n//2 + 1]) + minimum_cost + mid * (n // 2 + 1)
if cost <= s:
lft = mid
else:
rgt = mid
print(lft)
```
Yes
| 5,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
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)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
for _ in range(N()):
n, s = RL()
arr = [RLL() for _ in range(n)]
mid = n//2+1
def c(num):
now = 0
total = 0
tmp = []
for l, r in arr:
if r<num:
total+=l
elif l>num:
total+=l
now+=1
else:
tmp.append([l, r])
dif = mid-now
tmp.sort(key=lambda a: a[0], reverse=1)
for i in range(len(tmp)):
if i+1<=dif:
total+=num
now+=1
else:
total+=tmp[i][0]
return now>=mid and total<=s
l, r = 0, s
while l<r:
m = (l+r+1)//2
if c(m):
l = m
else:
r = m-1
print(l)
if __name__ == "__main__":
main()
```
Yes
| 5,138 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
a=int(input())
ans=[]
import sys
input=sys.stdin.readline
def checker(ans,mid,n,s):
g1=n//2
c1=0
c2=0
c3=0
cost=0
t1=[]
for i in range(len(ans)):
if(ans[i][0]<=mid<=ans[i][1]):
t1.append([ans[i][0],ans[i][1]])
elif(ans[i][1]<mid):
c3+=1
cost+=ans[i][0]
else:
c1+=1
cost+=ans[i][0]
if(c1>g1 or c3>g1):
if(c3>g1):
return 0;
else:
return 2;
else:
left=g1-c3
leftr=g1-c1
for i in range(left):
cost+=t1[i][0]
cost+=(leftr+1)*mid
if(cost<=s):
return 1;
else:
return 0;
import math
for i in range(a):
n,s=map(int,input().split())
ans=[]
mini=math.inf
maxa=0
for i in range(n):
x,y=map(int,input().split())
ans.append([x,y])
mini=min(x,y,mini)
maxa=max(x,y,maxa)
ans.sort()
maxa+=5
value=0
while(mini<maxa):
mid=(mini+maxa)//2
t=checker(ans,mid,n,s)
if(t==0):
maxa=mid
else:
if(t==1):
value=max(value,mid)
mini=mid+1
print(value)
```
Yes
| 5,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
import bisect
import os, sys, atexit
from io import BytesIO, StringIO
input = BytesIO(os.read(0, os.fstat(0).st_size)).readline
_OUTPUT_BUFFER = StringIO()
sys.stdout = _OUTPUT_BUFFER
@atexit.register
def write():
sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
def solve():
t = int(input())
for _ in range(t):
n,s = map(int,input().split())
ranges = []
for _ in range(n):
l,r = map(int,input().split())
ranges.append([r,l])
ranges.sort()
sumli =[0]
li,ri=[],[]
for r,l in ranges:
sumli.append(sumli[-1]+l)
li.append(l)
ri.append(r)
left,right = 0,ri[n//2]
# print(ri,li)
while left!=right:
mid = (left+right+1)//2
total = 0
# print ("binaries",left,mid,right)
riIndex = bisect.bisect_left(ri,mid)
if (n-riIndex>n//2):
total += sumli[riIndex]
# print (total)
sortedLi = sorted(li[riIndex:])
# print ("sorted li ",sortedLi)
liIndex = bisect.bisect_left(sortedLi,mid)
total+=sum(sortedLi[liIndex:])
# print (total)
countN2 = max((n+1)//2-(len(sortedLi)-liIndex),0)
total += countN2*mid+sum(sortedLi[:liIndex-countN2])
# print (total)
if total>s:
right = mid-1
else:
if countN2==0:
left = sortedLi[-(n//2+1)]
else:
left = mid
else:
right = mid-1
print ((left+right)//2)
try:
solve()
except Exception as e:
print (e)
# solve()
```
Yes
| 5,140 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
t = int(input())
#n number of employee
#s amt of money
#take in the lowest one for the first n//2(sorted)
#then take in the highest possible from the top.
for i in range(t):
n,s = map(int,input().split())
salaryrange = [[] for c in range(n)]
for b in range(n):
l,r = map(int,input().split())
salaryrange[b] = [l,r]
salaryrange.sort(key=lambda x: x[1])
totalpaid = 0
if len(salaryrange) >1:
for c in range(n//2):
totalpaid += salaryrange[c][0]
for d in range(n//2,n):
totalpaid += salaryrange[n//2][1]
if totalpaid > s:
print(int(salaryrange[n//2][1] -((totalpaid - s )/(n - n//2))))
else:
print(salaryrange[n//2][1])
else:
print(s)
```
No
| 5,141 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
import operator
def divide_into_lsts(salaries_ranges, median):
below = []
middle = []
above = 0
count_above = 0
for k, v in salaries_ranges.items():
if k[0] < median and k[1] < median:
#duplicates or more
for i in range(v):
below.append(k)
elif k[0] > median and k[1] > median:
above += k[0]
count_above += 1
else:
#duplicates or more
for i in range(v):
middle.append(k)
return below, middle, above, count_above
def calculate_min_salary_sum(below, middle, above, median, e):
min_salary_sum = 0
if len(middle) != 0:
middle.sort(key = operator.itemgetter(0))
if len(below) <= e:
n = e - len(below)
for i in range(n):
if len(middle) == 0:
break
else:
below.append(middle[0])
middle.pop(0)
for i in range(len(below)):
min_salary_sum += below[i][0]
if len(middle) > 0:
min_salary_sum += median * len(middle)
min_salary_sum += above
return min_salary_sum
t = int(input())
salaries_ranges_lst = []
p_lst = []
sum_max_lst = []
# loading data
for i in range(t):
p, sum_max = map(int, input().split())
p_lst.append(p)
sum_max_lst.append(sum_max)
salaries_ranges = {}
for j in range(p):
salary_min, salary_max = map(int, input().split())
if (salary_min, salary_max) in salaries_ranges:
salaries_ranges[(salary_min, salary_max)] += 1
else:
salaries_ranges[(salary_min, salary_max)] = 1
salaries_ranges_lst.append(salaries_ranges)
for i in range(t):
# define new variables using created collections
p = p_lst[i]
sum_max = sum_max_lst[i]
salaries_ranges = salaries_ranges_lst[i]
#define new variables
median_idx = p // 2
real_sum_max = 0
median_lst = []
for k in salaries_ranges.keys():
real_sum_max += k[1]
median_lst.append(k[1])
median_lst = sorted(median_lst)
if real_sum_max <= sum_max:
print(median_lst[median_idx])
elif p == 1 and real_sum_max > sum_max:
print(sum_max)
else:
median = median_lst[median_idx]
too_low = 0
too_high = median
min_salary_sum = real_sum_max
while too_low != too_high:
below, middle, above, count_above = divide_into_lsts(salaries_ranges, median)
e = median_idx
min_salary_sum = calculate_min_salary_sum(below, middle, above, median, e)
if min_salary_sum > sum_max:
# print("a")
too_high = median
median = int(too_low + (too_high - too_low) // 2)
elif min_salary_sum <= sum_max:
too_low = median
median = int(too_low + (too_high - too_low) // 2)
if too_high - too_low <= 1:
too_high = too_low
median = too_low
print(median)
```
No
| 5,142 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
def fun1(m,l,s):
cl=0
cr=0
l1=[]
n=len(l)
l2=[]
for i in range(n):
if l[i][1]<m:
s-=l[i][0]
cl+=1
elif l[i][0]>m:
s-=l[i][0]
cr+=1
else:
l1.append(l[i][1])
if cl>n//2 or cr>n//2:
return(0)
elif (s<(sum(l1[:(n//2-cl)])+m*(1+n//2-cr))):
return(0)
else:
return(1)
def search(low,high,l,su):
while(low<high):
mid=(low+high)//2
if fun1(mid,l,su):
low=mid+1
else:
high=mid
if fun1(low,l,su):
return(low)
return(low-1)
for _ in range(int(input())):
n,su=[int(j) for j in input().split()]
l=[]
l2=[]
for i in range(n):
inp=[int(j) for j in input().split()]
l.append(inp)
l2.append(inp[0])
l.sort()
low=sorted(l2)[n//2]
print(search(low,1+10**9,l,su))
```
No
| 5,143 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are the head of a large enterprise. n people work at you, and n is odd (i. e. n is not divisible by 2).
You have to distribute salaries to your employees. Initially, you have s dollars for it, and the i-th employee should get a salary from l_i to r_i dollars. You have to distribute salaries in such a way that the median salary is maximum possible.
To find the median of a sequence of odd length, you have to sort it and take the element in the middle position after sorting. For example:
* the median of the sequence [5, 1, 10, 17, 6] is 6,
* the median of the sequence [1, 2, 1] is 1.
It is guaranteed that you have enough money to pay the minimum salary, i.e l_1 + l_2 + ... + l_n β€ s.
Note that you don't have to spend all your s dollars on salaries.
You have to answer t test cases.
Input
The first line contains one integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The first line of each query contains two integers n and s (1 β€ n < 2 β
10^5, 1 β€ s β€ 2 β
10^{14}) β the number of employees and the amount of money you have. The value n is not divisible by 2.
The following n lines of each query contain the information about employees. The i-th line contains two integers l_i and r_i (1 β€ l_i β€ r_i β€ 10^9).
It is guaranteed that the sum of all n over all queries does not exceed 2 β
10^5.
It is also guaranteed that you have enough money to pay the minimum salary to each employee, i. e. β_{i=1}^{n} l_i β€ s.
Output
For each test case print one integer β the maximum median salary that you can obtain.
Example
Input
3
3 26
10 12
1 4
10 11
1 1337
1 1000000000
5 26
4 4
2 4
6 8
5 6
2 7
Output
11
1337
6
Note
In the first test case, you can distribute salaries as follows: sal_1 = 12, sal_2 = 2, sal_3 = 11 (sal_i is the salary of the i-th employee). Then the median salary is 11.
In the second test case, you have to pay 1337 dollars to the only employee.
In the third test case, you can distribute salaries as follows: sal_1 = 4, sal_2 = 3, sal_3 = 6, sal_4 = 6, sal_5 = 7. Then the median salary is 6.
Submitted Solution:
```
t = int(input())
#n number of employee
#s amt of money
#take in the lowest one for the first n//2(sorted)
#then take in the highest possible from the top.
for i in range(t):
n,s = map(int,input().split())
salaryrange = [[] for c in range(n)]
for b in range(n):
l,r = map(int,input().split())
salaryrange[b] = [l,r]
salaryrange.sort(key=lambda x: x[1])
totalpaid = 0
if len(salaryrange) >1:
for c in range(n//2):#0->n//2-1
totalpaid += salaryrange[c][0]
ans = salaryrange[n // 2][1]
totalpaid += ans
counter = 1
for d in range(n//2+1,n):#n//2+1->n-1
if salaryrange[d][0]>=salaryrange[n//2][1]:
totalpaid += salaryrange[d][0]
else:
totalpaid += ans
counter += 1
if totalpaid > s:
print(int(ans-((totalpaid-s)/(counter))))
else:
print(ans)
else:
print(s)
```
No
| 5,144 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
n=int(input())
s=list(input())
b=[]
a=[]
for i in range(n):
a.append(s[i])
b.append(s[i])
c=[]
for i in range(n-1):
if(a[i]=="W"):
continue
else:
a[i]="W"
c.append(i+1)
if(a[i+1]=="W"):
a[i+1]="B"
else:
a[i+1]="W"
if(a.count("W")==n):
print(len(c))
print(*c)
else:
d=[]
for i in range(n-1):
if(b[i]=="B"):
continue
else:
b[i]="B"
d.append(i+1)
if(b[i+1]=="W"):
b[i+1]="B"
else:
b[i+1]="W"
if(b.count("B")==n):
print(len(d))
print(*d)
else:
print(-1)
```
| 5,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
# HEY STALKER
from collections import Counter
n = int(input())
l = list(input())
x = Counter(l)
if x['B'] % 2 and x['W'] % 2:
print(-1)
elif x['B'] == n or x['W'] == n:
print(0)
else:
k = []
b = ''
w = ''
if not x['B'] % 2:
b = 'B'
w = 'W'
else:
b = 'W'
w = 'B'
t = 0
while t < n-1:
if l[t] == b:
if l[t+1] == b:
k.append(t+1)
l[t] = w
l[t+1] = w
elif l[t+1] == w:
k.append(t+1)
l[t] = w
l[t+1] = b
t += 1
print(len(k))
print(*k)
```
| 5,146 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
n=int(input())
s=list(input())
x='B'
def check(l):
prev=l[0]
for i in range(len(l)):
if l[i]!=prev:
return False
return True
count=0
ans=[i for i in s]
l=[]
for i in range(n-1):
if s[i]!=x:
s[i]=x
if s[i+1]=='B':
s[i+1]='W'
else:
s[i+1]='B'
l.append(i+1)
count+=1
if count<=3*n and check(s):
print(count)
print(*l)
else:
x='W'
count=0
l=[]
s=[i for i in ans]
for i in range(n-1):
if s[i]!=x:
s[i]=x
if s[i+1]=='B':
s[i+1]='W'
else:
s[i+1]='B'
l.append(i+1)
count+=1
if count<=3*n and check(s):
print(count)
print(*l)
else:
print(-1)
```
| 5,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
'''input
3 2
192
'''
# A coding delight
from sys import stdin
def counter(c):
if c == 'B':
return 'W'
return 'B'
# main starts
n = int(stdin.readline().strip())
string = list(stdin.readline().strip())
temp = string[:]
# changing to B
ans = []
for i in range(n - 1):
if string[i] == 'B':
pass
else:
string[i] = 'B'
string[i + 1] = counter(string[i + 1])
ans.append(i + 1)
if string[-1] == 'B':
print(len(ans))
print(*ans)
exit()
ans = []
string = temp[:]
for i in range(n - 1):
if string[i] == 'W':
pass
else:
string[i] = 'W'
string[i + 1] = counter(string[i + 1])
ans.append(i + 1)
if string[-1] == 'W':
print(len(ans))
print(*ans)
exit()
print(-1)
```
| 5,148 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
n=int(input())
s=input()
t1=s.count('B')
t2=s.count('W')
a=[x for x in s]
if t1%2==1 and t2%2==1:
print("-1")
else:
c=0
a1=[]
b="#"
if t2%2==0:
b="W"
else:
b="B"
for i in range(n-1):
if(a[i]==b):
c+=1
if(a[i+1]=='W'):
a[i+1]='B'
else:
a[i+1]='W'
a1.append(i+1)
print(c)
print(*a1)
```
| 5,149 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
n=int(input())
r=list(input())
for t in range(len(r)):
if r[t]=='B':
r[t]=1
else:
r[t]=-1
g=0
m=0
l=[]
jk=[]
o=list(r)
for i in range(0,n-1):
if r[i]==-1:
r[i]=-r[i]
r[i+1]=-r[i+1]
l+=[i+1]
if r[n-1]!=1:
g=1
for q in range(0,n-1):
if o[q]==1:
o[q]=-o[q]
o[q+1]=-o[q+1]
jk+=[q+1]
if o[n-1]!=-1:
m=1
if m==1 and g==1:
print(-1)
if m!=1 and g==1:
print(len(jk))
for ty in jk:
print(ty,end=' ')
if m==1 and g!=1:
print(len(l))
for tyh in l:
print(tyh,end=' ')
if m!=1 and g!=1:
if len(l)<len(jk):
print(len(l))
for tye in l:
print(tye,end=' ')
else:
print(len(jk))
for tyw in jk:
print(tyw,end=' ')
```
| 5,150 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
n=int(input())
s=list(input())
w=s.count('W')
b=n-w
f = lambda c: 'B' if c=='W' else 'W'
if not b&1:
l = []
for i in range(n-1):
if s[i]=='B':
s[i],s[i+1]=f(s[i]),f(s[i+1])
l.append(i+1)
le=len(l)
print(le)
if le:
print(*l)
elif not w&1:
l = []
for i in range(n-1):
if s[i]=='W':
s[i],s[i+1]=f(s[i]),f(s[i+1])
l.append(i+1)
le=len(l)
print(le)
if le:
print(*l)
else:
print(-1)
```
| 5,151 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Tags: greedy, math
Correct Solution:
```
t = int(input())
s = input()
white = []
white_count = 0
temp = list(s)
for j in range(len(s)-1):
if(temp[j]=='B'):
white_count+=1
temp[j+1]='W' if temp[j+1]=='B' else 'B'
white.append(j+1)
if(temp[-1]=='W'):
print(white_count)
if(len(white)!=0):
print(*white)
else:
black = []
black_count = 0
temp = list(s)
for j in range(len(s)-1):
if(temp[j]=='W'):
black_count+=1
temp[j+1]='B' if temp[j+1]=='W' else 'W'
black.append(j+1)
if(temp[-1]=='B'):
print(black_count)
if(len(black)!=0):
print(*black)
else:
print(-1)
```
| 5,152 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
'''input
3
BWB
'''
n = int(input())
string = input()
temp = []
for ele in string:
if ele == 'B':
temp.append(0)
else:
temp.append(1)
string = temp[::]
ans = []
temp = string[::]
for i in range(n - 1):
if temp[i] == 0:
temp[i] ^= 1
temp[i + 1] ^= 1
ans.append(i + 1)
# print(string, temp)
if temp[n - 1] == 0:
ans = []
temp = string[::]
for i in range(n - 1):
if temp[i] == 1:
temp[i] ^= 1
temp[i + 1] ^= 1
ans.append(i + 1)
if temp[n - 1] == 1:
print(-1)
else:
print(len(ans))
print(*ans)
else:
print(len(ans))
print(*ans)
```
Yes
| 5,153 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
#import sys
#input = sys.stdin.readline
def main():
n = int( input())
S = list( input())
b = 0
w = 0
T = [0]*n
for i in range(n):
if S[i] == 'B':
b += 1
else:
w += 1
T[i] = 1
if b%2 == 1 and w%2 == 1:
print(-1)
return
count = 0
ans = []
if b%2 == 1:
for i in range(n-1):
if T[i] == 0:
continue
T[i] = 0
T[i+1] = 1-T[i+1]
count += 1
ans.append(i+1)
else:
for i in range(n-1):
if T[i] == 1:
continue
T[i] = 1
T[i+1] = 1-T[i+1]
count += 1
ans.append(i+1)
print(count)
if count == 0:
return
print(" ".join( map(str, ans)))
if __name__ == '__main__':
main()
```
Yes
| 5,154 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
t = int(input())
s = list(input())
l1 = []
l2 = []
B = 0
W = 0
j = 0
p = []
q = []
for i in s:
l1.append(i)
l2.append(i)
if l1[j] == "W":
W += 1
else:
B += 1
j += 1
if W==0 or B==0:
print(0)
else:
for k in range(t-1):
if l1[k] != 'B':
l1[k] = 'B'
p.append(k + 1)
if l1[k+1] == 'B':
l1[k+1] = 'W'
elif l1[k+1] == 'W':
l1[k+1] = 'B'
if l2[k] != 'W':
l2[k] = 'W'
q.append(k + 1)
if l2[k+1] == 'W':
l2[k+1] = 'B'
elif l2[k+1] == 'B':
l2[k+1] = 'W'
if l1[-1] == 'B':
print(len(p))
while p:
print(p[-1])
p.pop()
elif l2[-1] == 'W':
print(len(q))
while q:
print(q[-1])
q.pop()
else:
print(-1)
```
Yes
| 5,155 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
n=int(input())
s=input()
a=list(s)
if (a.count("B")%2)*(a.count("W")%2):print(-1);exit()
b=[]
if a.count("B")%2:m="W"
else:m="B"
for i in range(n-1):
if a[i]==m:
b.append(i+1)
if a[i]=="W":a[i]="B"
else:a[i]="W"
if a[i+1]=="W":a[i+1]="B"
else:a[i+1]="W"
print(len(b))
if len(b):print(*b)
```
Yes
| 5,156 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
n = int(input())
b = [1 if i == "B" else 0 for i in input()]
sb = sum(b)
if sb % 2 == 1 and n % 2 == 0:
print(-1)
elif sb == 0 or sb == n:
print(0)
else:
if sb > n//2:
flip = 1
else:
flip = 0
ans = []
for a in range(len(b)-1):
if b[a] == flip:
print(b)
ans.append(a+1)
b[a] = 1 - b[a]
b[a+1] = 1 - b[a+1]
print(len(ans))
print(" ".join(map(str, ans)))
```
No
| 5,157 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
n = int(input())
s = str(input())
s = s.replace('W', '0')
s = s.replace('B', '1')
def funs(s):
ind = []
for i in range(0, len(s)):
k = int(s[i]) % 2
ind.append(k)
return ind
def conv(ind):
st = ''
for i in range(0, len(ind)):
if ind[i] == 1:
st = st + 'B'
elif ind[i] == 0:
st = st + 'W'
return st
s = str(s)
if s.count('0') > s.count('1'):
mak = 0
mal = 1
else:
mak = 1
mal = 0
s = funs(s)
if s.count(mak) == len(s):
print('0')
elif s.count(mak) % 2 == 1:
print('-1')
else:
ink = []
for i in range(0, len(s) - 1):
if s[i] == mak:
ink.append(i)
s[i + 1] = s[i + 1] + 1
s[i] = s[i] + 1
ink.sort(reverse=True)
stk=''
for y in ink:
y=y+1
stk=stk+str(y)+' '
if len(ink) <= 3*n:
print(len(ink))
print(stk)
else:
print('-1')
```
No
| 5,158 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
# ========= /\ /| |====/|
# | / \ | | / |
# | /____\ | | / |
# | / \ | | / |
# ========= / \ ===== |/====|
# code
def main():
n = int(input())
s = input()
s = list(s)
# print(s)
if len(set(s)) == 1:
print(0)
return
a = []
for i in range(n - 1):
if s[i] == 'W' and s[i + 1] == 'B':
s[i] = 'B'
s[i + 1] = 'W'
a.append(i + 1)
elif s[i] == 'W' and s[i + 1] == 'W':
a.append(i + 1)
s[i] = 'B'
s[i + 1] = 'B'
if len(set(s)) > 1:
print(-1)
else:
print(len(a))
print(*a)
return
if __name__ == "__main__":
main()
```
No
| 5,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n blocks arranged in a row and numbered from left to right, starting from one. Each block is either black or white.
You may perform the following operation zero or more times: choose two adjacent blocks and invert their colors (white block becomes black, and vice versa).
You want to find a sequence of operations, such that they make all the blocks having the same color. You don't have to minimize the number of operations, but it should not exceed 3 β
n. If it is impossible to find such a sequence of operations, you need to report it.
Input
The first line contains one integer n (2 β€ n β€ 200) β the number of blocks.
The second line contains one string s consisting of n characters, each character is either "W" or "B". If the i-th character is "W", then the i-th block is white. If the i-th character is "B", then the i-th block is black.
Output
If it is impossible to make all the blocks having the same color, print -1.
Otherwise, print an integer k (0 β€ k β€ 3 β
n) β the number of operations. Then print k integers p_1, p_2, ..., p_k (1 β€ p_j β€ n - 1), where p_j is the position of the left block in the pair of blocks that should be affected by the j-th operation.
If there are multiple answers, print any of them.
Examples
Input
8
BWWWWWWB
Output
3
6 2 4
Input
4
BWBB
Output
-1
Input
5
WWWWW
Output
0
Input
3
BWB
Output
2
2 1
Note
In the first example, it is possible to make all blocks black in 3 operations. Start with changing blocks 6 and 7, so the sequence is "BWWWWBBB". Then change blocks 2 and 3, so the sequence is "BBBWWBB". And finally, change blocks 4 and 5, so all blocks are black.
It is impossible to make all colors equal in the second example.
All blocks are already white in the third example.
In the fourth example it is possible to make all blocks white in two operations: first operation is to change blocks 2 and 3 (so the sequence is "BBW"), and then change blocks 1 and 2 (so all blocks are white).
Submitted Solution:
```
import sys,math,bisect
from random import randint
inf = float('inf')
mod = (10**9)+7
"========================================"
def lcm(a,b):
return int((a/math.gcd(a,b))*b)
def gcd(a,b):
return int(math.gcd(a,b))
def tobinary(n):
return bin(n)[2:]
def binarySearch(a,x):
i = bisect.bisect_left(a,x)
if i!=len(a) and a[i]==x:
return i
else:
return -1
def lowerBound(a, x):
i = bisect.bisect_left(a, x)
if i:
return (i-1)
else:
return -1
def upperBound(a,x):
i = bisect.bisect_right(a,x)
if i!= len(a)+1 and a[i-1]==x:
return (i-1)
else:
return -1
def primesInRange(n):
ans = []
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
for p in range(2, n+1):
if prime[p]:
ans.append(p)
return ans
def primeFactors(n):
factors = []
while n % 2 == 0:
factors.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
factors.append(i)
n = n // i
if n > 2:
factors.append(n)
return factors
def isPrime(n,k=5):
if (n <2):
return True
for i in range(0,k):
a = randint(1,n-1)
if(pow(a,n-1,n)!=1):
return False
return True
"========================================="
"""
n = int(input())
n,k = map(int,input().split())
arr = list(map(int,input().split()))
"""
from collections import deque,defaultdict,Counter
import heapq,string
n=int(input())
s=input()
freq = {}
for i in s:
if i in freq:
freq[i]+=1
else:
freq[i]=1
if 'B' not in s or 'W' not in s:
print(0)
elif freq['B']%2!=0 and freq['W']%2!=0:
print(-1)
else:
even = []
if freq['B']%2==0:
for i in range(n):
if s[i]=='B':
even.append(i+1)
else:
for i in range(n):
if s[i]=='W':
even.append(i+1)
ans = []
cnt = 0
for i in range(len(even)-1):
if even[i]+1==even[i+1]:
x,y=even[i],even[i+1]
cnt+=1
ans.append(even[i])
even[i]=-1
even[i+1]=-1
newEven = [ ]
for i in even:
if i!=-1:
newEven.append(i)
for i in range(1,len(newEven)):
cnt+=(newEven[i]-newEven[i-1])
for i in range(len(newEven)-1):
for j in range(newEven[i],newEven[i+1]):
ans.append(j)
print(cnt)
print(*ans)
```
No
| 5,160 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
ok = False
c = 2
while not ok and c*c*c <= n:
if n % c != 0:
c += 1
continue
# a * b = n / c
# a > b > c
b = c+1
while not ok and b*b <= (n // c):
if (n // c) % b != 0:
b += 1
continue
a = n // (c * b)
if a > b:
print('YES')
print(a, b, c)
ok = True
b += 1
c += 1
if not ok:
print('NO')
```
| 5,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
from functools import reduce
def fac(n):
return sorted(set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
t=int(input())
for i in range(t):
n=int(input())
x=fac(n)
x=x[1:-1]
flag=1
if len(x)<3:
flag=0
else:
a,b=x[0],0
for j in range(1,len(x)):
if n%(a*x[j])==0:
b=x[j]
break
if b:
te=a*b
if n%te==0:
c=n//te
if a!=b and a!=c and b!=c and a>=2 and b>=2 and c>=2:
pass
else:
flag=0
else:
flag=0
else:
flag=0
if flag:
pass
print("YES")
print(a,b,c)
else:
print("NO")
```
| 5,162 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
import math
if __name__ == "__main__":
t = int(input())
for _ in range(t):
n, a, b = int(input()), 0, 0
i = 1
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0 and i != n // i:
n, a = n // i, i
break
for j in range(i, int(math.sqrt(n)) + 1):
if n % j == 0:
if a != j and a != n // j and j != n // j:
n, b = n // j, j
break
if a != 0 and b != 0:
print("YES")
print(a, b, n)
else:
print("NO")
```
| 5,163 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
import math
for i in range(int(input())):
n=int(input())
l=[]
count=0
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
l.append(i)
n=n//i
break
for i in range(2,int(math.sqrt(n))+1):
if n%i==0 and len(l)==1 and l[0]!=i:
l.append(i)
n=n//i
count=1
break
flag=0
if count==1:
if n!=l[0] and n!=l[1]:
l.append(n)
else:
flag=1
if len(l)==3 and flag==0:
print("YES")
print(*l)
else:
print("NO")
```
| 5,164 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
# cook your dish here
import math
for t in range(int(input())):
n=int(input())
flag=False
for i in range(2,int(math.sqrt(n))+1):
if n%i==0:
x=i
yy=n//i
for j in range(i+1,int(math.sqrt(yy))+1):
if yy%j==0:
y=j
z=yy//j
if z>=2 and z!=y and z!=x:
flag=True
l=[x,y,z]
print("YES")
print(*l)
break
if flag:
break
if flag==False:
print("NO")
```
| 5,165 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 25 10:20:51 2020
@author: Anthony
"""
def abc(num):
threshold=num**0.5
myDivisors=[]
potentialDiv=2
current=num
while(potentialDiv<=threshold and current!=1):
if current//potentialDiv == current/potentialDiv:
myDivisors.append(potentialDiv)
current/=potentialDiv
potentialDiv+=1
if len(myDivisors)>=2 and (current not in myDivisors):
myDivisors.append(int(current))
return myDivisors
if len(myDivisors)>=3 and current==1:
return myDivisors
else:
return False
repeat=int(input())
for i in range(0,repeat):
temp=abc(int(input()))
if temp:
for i in range(0,len(temp)):
for j in range(i+1,len(temp)):
if (temp[i]*temp[j] not in temp) and len(temp)>3:
temp[i]*=temp[j]
temp[j]=1
safiye=[]
for x in temp:
if x!=1:
safiye.append(x)
if len(safiye)==3:
print("YES")
for x in safiye:
print(x,end=" ")
else:
print("NO")
else:
print("NO")
```
| 5,166 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
for i in range(int(input())):
n = int(input())
f = []
for j in range(2, int(n**(1/2))):
while n % j == 0:
f.append(j)
n = int(n/j)
if n > 1:
f.append(n)
if len(f) >= 3:
if len(f) == 3:
if f[0] != f[1] and f[1] != f[2] and f[2] != f[0]:
print('YES')
print(f[0],f[1],f[2])
else:
print('NO')
else:
f0 = f[0]
f1 = 1
f2 = 1
if f[1] == f[0]:
f1 = f[1] * f[2]
for j in range(3, len(f)):
f2 *= f[j]
else:
f1 = f[1]
for j in range(2, len(f)):
f2 *= f[j]
if f0 != f1 and f1 != f2 and f2 != f0:
print('YES')
print(f0, int(f1), int(f2))
else:
print('NO')
else:
print('NO')
```
| 5,167 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Tags: greedy, math, number theory
Correct Solution:
```
"""T=int(input())
for _ in range(0,T):
n=int(input())
a,b=map(int,input().split())
s=input()
s=[int(x) for x in input().split()]
for i in range(0,len(s)):
a,b=map(int,input().split())"""
import math
T=int(input())
for _ in range(0,T):
N=int(input())
n=N
L=[]
while (n % 2 == 0):
L.append(2)
n = n // 2
for i in range(3,int(math.sqrt(n))+1,2):
while (n % i== 0):
L.append(i)
n = n // i
if (n > 2):
L.append(n)
if(len(L)<3):
print('NO')
else:
t1=L[0]
t2=L[1]
t3=1
if(L[1]==L[0]):
t2=L[1]*L[2]
for j in range(3,len(L)):
t3*=L[j]
else:
for j in range(2,len(L)):
t3*=L[j]
if(t1!=t2 and t2!=t3 and t1!=t3 and t1>1 and t2>1 and t3>1):
print('YES')
print(t1,t2,t3)
else:
print('NO')
```
| 5,168 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
import math
for p in range(int(input())):
num=int(input())
b=[]
a=num
for i in range(2,int(math.sqrt(num))+1):
if(len(b)<2):
if(a%i==0):
b.append(int(i))
a/=i
else:
break
if((a not in b) and (len(b)==2)):
print('YES')
print(str(b[0])+' '+str(b[1])+' '+str(int(a)))
else:
print('NO')
```
Yes
| 5,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
import sys
import math
input=sys.stdin.readline
# A function to print all prime factors of
# a given number n
def primeFactors(n):
# Print the number of two's that divide n
while n % 2 == 0:
n = n / 2
return(2,n)
# n must be odd at this point
# so a skip of 2 ( i = i + 2) can be used
for i in range(3,int(math.sqrt(n))+1,2):
# while i divides n , print i ad divide n
while n % i== 0:
n = n / i
return(i,n)
# Condition if n is a prime
# number greater than 2
return(-1,-1)
t=int(input())
for _ in range(t):
n=int(input())
a,n=primeFactors(n)
b=-1
c=-1
flag=0
if(a==-1):
print("NO")
else:
i=2
while(i<=math.sqrt(n)):
if(n%i==0):
if(n//i>=2):
if(i!=a and(n//i!=a and i!=n//i)):
b=i
c=n//i
flag=1
i+=1
if(flag==1):
print("YES")
print(a,int(b),int(c))
else:
print("NO")
```
Yes
| 5,170 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
def isPrime(n):
if n == 2 or n == 3: return True
if n % 2 == 0 or n < 2: return False
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return False
return True
t = int(input())
for _ in range(t):
f = 0
n = int(input())
if isPrime(n):
print("NO")
continue
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
if not isPrime(n // i):
m = n // i
for j in range(2, int(m ** 0.5) + 1):
if m % j == 0 and i != j != (m // j) != i:
print("YES")
print(i, j, m // j)
f = 1
break
if f:
break
if not f:
print("NO")
```
Yes
| 5,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
# βββββββββββββββββββββββββββββββ
import math
for i in range(int(input())):
n = int(input())
l = []
p =math.sqrt(n)
p = int(p)
i=2
while len(l)<2 and i<p:
if n%i==0:
l.append(i)
n=n//i
i+=1
if len(l)==2 and n not in l:
print("YES")
print(*l,n)
else:
print("NO")
```
Yes
| 5,172 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
import math
from collections import defaultdict
def primeFactors(n):
d=defaultdict(int)
while n % 2 == 0:
d[2]+=1
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
d[i]+=1
n = n / i
if n > 2:
d[n]+=1
return d
t=int(input())
for i in range(t):
n=int(input())
d= primeFactors(n)
# print(d)
if len( d.keys() )>=3:
print("YES")
s=[]
ww=1
for j in list(d.keys())[:2]:
s.append( int(j**d[j]) )
ww*=j**(d[j]-1)
for j in list(d.keys())[2:]:
ww*= int(j**d[j])
s.append(ww)
print(*s)
elif len(list(d.keys()))==1:
w,w1 = int(list(d.keys())[0]), int(d[list(d.keys())[0]])
if w1>=6:
print("YES")
ans = "{} {} {}".format(w,w**2,w**(w1-3))
print(ans)
else:
print("NO")
elif len(list(d.keys()))==2:
keys= list(map(int,list(d.keys())))
value = list(map(int,list(d.values())))
value1 = sorted(list(d.values()))
if sum(value)>=4:
ans = "{} {} {}".format( keys[0], keys[1], keys[0]**(d[value1[0]]-1) * keys[1]**(d[value1[1]]-1) )
print(ans)
else:
print("NO")
```
No
| 5,173 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
import math
for i in range(int(input())):
x = int(input())
a,b=[2,3] if x%2 ==0 else [3,5]
while b <= int(math.sqrt(x)):
if x%(a*b) == 0:
c = int(x/(a*b))
if c != a and c != b:
print("YES")
print(f"{a} {b} {c}");break
else:
print("NO");break
b+=1;
else:
print("NO")
```
No
| 5,174 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
factors = []
for factor in range (2, 1000000000):
if n < factor:
break
if n % factor == 0:
factors.append(factor)
n = n // factor
if len(factors) == 2:
break
if len(factors) == 2:
factors.append(n)
print('YES')
print(' '.join(map(str, factors)))
else:
print('NO')
```
No
| 5,175 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given one integer number n. Find three distinct integers a, b, c such that 2 β€ a, b, c and a β
b β
c = n or say that it is impossible to do it.
If there are several answers, you can print any.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 100) β the number of test cases.
The next n lines describe test cases. The i-th test case is given on a new line as one integer n (2 β€ n β€ 10^9).
Output
For each test case, print the answer on it. Print "NO" if it is impossible to represent n as a β
b β
c for some distinct integers a, b, c such that 2 β€ a, b, c.
Otherwise, print "YES" and any possible such representation.
Example
Input
5
64
32
97
2
12345
Output
YES
2 4 8
NO
NO
NO
YES
3 5 823
Submitted Solution:
```
# _1294c
##########
def productOfThreeNumbers(n, answer=(1, )):
lengthOfAnswer = len(answer)
if lengthOfAnswer == 3:
if n > answer[-1]:
return f'YES\n{answer[1]} {answer[2]} {int(n)}'
return 'NO'
for i in range(answer[-1]+1, int(n**(1/(4-lengthOfAnswer)))):
if not n%i:
return productOfThreeNumbers(n/i, answer+(i, ))
return 'NO'
nTestCases = int(input())
testCases = [int(input()) for x in range(nTestCases)]
[print(productOfThreeNumbers(testCase)) for testCase in testCases]
```
No
| 5,176 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
from sys import stdin, gettrace
if not gettrace():
def input():
return next(stdin)[:-1]
def main():
def solve():
n = int(input())
bb = [int(a) for a in input().split()]
avail = [False] + [True] * 2 * n
for b in bb:
avail[b] = False
res = []
for b in bb:
if b == n*2:
print(-1)
return
res.append(b)
c = b+1
while not avail[c]:
c+=1
if c == 2*n+1:
print(-1)
return
res.append(c)
avail[c] = False
print(' '.join(map(str, res)))
q = int(input())
for _ in range(q):
solve()
if __name__ == "__main__":
main()
```
| 5,177 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()));d={}
for i in range(n):
d[a[i]]=1
ans=[];f=0
for i in range(n):
if a[i]<2*n:
for j in range(a[i],(2*n)+2):
if not d.get(j) and j<=2*n:
ans.append(a[i])
ans.append(j)
d[j]=1
break
if j>2*n:
print(-1)
f=1
break
else:
print(-1)
f=1
break
if f==1:
break
if f==0:
for i in ans:
print(i,end=' ')
print()
```
| 5,178 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
t=int(input())
for i in range(0,t):
n=int(input())
b=[]
c=[]
a=list(map(int,input().split()))
k1=1
k2=n*2
if(k1 in a and k2 not in a):
for j in range(1,2*n+1):
if(j not in a):
b.append(j)
for j in range(0,n):
k=a[j]+1
f=1
while(k not in b):
k=k+1
if(k>2*n):
f=0
break
if(f==0):
print(-1)
break
c.append(a[j])
c.append(k)
b.pop(b.index(k))
if(f==0):
continue
for j in range(0,2*n):
print(c[j],end=" ")
print("")
else:
print(-1)
```
| 5,179 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
from functools import reduce
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():return tuple(map(int,input().split()))
def arr():return [int(i) for i in input().split()]
def sarr():return [int(i) for i in input()]
def inn():return int(input())
mo=1000000007
#----------------------------CODE------------------------------#
for _ in range(int(input())):
n=inn()
a=arr()
d=defaultdict(int)
ans=[]
for i in a:
d[i]+=1
for i in range(n):
res=a[i]
for j in range(a[i]+1,2*n+1):
if(j not in d):
ans+=[(res,j)]
d[j]+=1
break
flag=0
for i in range(1,2*n+1):
if(i not in d):
flag=1
break
if(flag==1):
print(-1)
else:
for i in range(n):
print(ans[i][0],ans[i][1],end=" ")
print()
```
| 5,180 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
from collections import defaultdict as dfd
for _ in range(int(input())):
N = int(input())
A = list(map(int,input().split()))
C = dfd(int)
for i in range(1,(2*N)+1):
C[i] = 0
for i in range(len(A)):
C[A[i]] = 1
B = []
# print(C)
for i in range(len(A)):
B.append(A[i])
z = 0
temp = A[i]+1
while(z!=1):
if(C[temp]==0):
C[temp]=1
B.append(temp)
z = 1
else:
temp+=1
# print("Hello")
res = 0
for i in range(len(B)):
if(B[i]>(2*N)):
print(-1)
res = 1
break
if(res==0):
print(*B)
```
| 5,181 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
b = list(map(int, input().split()))
if max(b) >= n*2 or 1 not in b:
print(-1)
else:
a = [0]*(2*n)
ok = True
for i in range(n):
a[i*2] = b[i]
while 0 in a:
moved = False
for i in range(1, 1+2*n):
ind = a.index(0)
if i not in a and i > a[ind-1]:
a[ind] = i
moved = True
break
if not moved:
ok = False
break
if not ok:
print(-1)
else:
print(*a)
```
| 5,182 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
for T in range(int(input())):
n = int(input())
x = list(map(int, input().split(" ")))
b = [0]
for i in x:
b.append(i)
vis = [False for cnt_used in range(2*n + 1)]
a = [0 for cnt_a in range(2*n + 1)]
set_elem_b = True
for i in range(1, n+1):
num = int(b[i])
if not vis[num]:
vis[num] = True
else:
set_elem_b = False
break
if not set_elem_b:
print(-1)
continue
find = False
for i in range(1, n+1):
find = False
for j in range(1, 2*n+1):
if not vis[j] and j > b[i]:
vis[j] = True
a[i*2-1] = b[i]
a[i*2] = j
find = True
break
if not find:
break
if not find:
print(-1)
continue
for i in range(1, 2*n+1):
print(a[i], end = ' ')
print()
```
| 5,183 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
b=list(map(int,input().split()))
d={}
for i in range(1,2*n+1):
d[i]=1
for i in b:
d[i]=0
a=[]
for i in b:
a.append(i)
z=i
for j in range(z+1,2*n+1):
if d[j]:
z=j
d[j]=0
break
if z!=i:
a.append(z)
else:
break
if len(a)==2*n:
print(' '.join(map(str,a)))
else:
print(-1)
```
| 5,184 |
Provide tags and a correct Python 2 solution for this coding contest problem.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Tags: greedy
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
for t in range(ni()):
n=ni()
l=li()
d=Counter(l)
arr=[]
for i in range(1,2*n+1):
if not d[i]:
arr.append(i)
f=0
ans=[]
for i in range(n):
f1=0
for j in arr:
if j>l[i]:
f1=1
break
if not f1:
f=1
break
ans.append(l[i])
ans.append(j)
arr.remove(j)
if f:
pn(-1)
else:
pa(ans)
```
| 5,185 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from bisect import bisect
def solution(arr, n):
all_set = [i for i in range(1, (2 * n) + 1)]
for i, x in enumerate(arr):
all_set.remove(arr[i])
res = []
for i in range(n):
idx = bisect(all_set, arr[i])
if idx == len(all_set):
print(-1)
return
res.append(arr[i])
res.append(all_set[idx])
all_set.pop(idx)
for x in res:
print(x, end=' ')
print()
def main():
t = int(input())
for _ in range(t):
n = int(input())
arr = [int(x) for x in input().split()]
solution(arr, n)
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)
def input():
return sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
Yes
| 5,186 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
y = [*map(int, input().split())]
x = {*range(1, 2*n+1)}.difference(y)
res = []
for i in y:
a = [j for j in x if i < j]
if a:
b = min(a)
x.remove(b)
res.extend([i, b])
else:
print(-1)
break
if not x:
print(*res)
```
Yes
| 5,187 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
I=input
for _ in[0]*int(I()):
n=2*int(I());a=[0]*n;b=a[::2]=*map(int,I().split()),;c={*range(n+1)}-{*b};i=1
try:
for x in b:y=a[i]=min(c-{*range(x)});c-={y};i+=2
except:a=-1,
print(*a)
```
Yes
| 5,188 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
b = list(map(int, input().split()))
for i in range(n):
b[i] -= 1
# print("b: ", b)
used = [False for _ in range(2*n)]
for i in range(n):
used[b[i]] = True
ans = [0 for i in range(2*n)]
for i in range(n):
ans[2*i] = b[i]
result = True
for i in range(n):
found_cand = False
for cand in range(ans[2*i]+1, 2*n):
if not used[cand]:
used[cand] = True
ans[2*i+1] = cand
found_cand = True
break
if not found_cand:
result = False
if not result:
print(-1)
else:
print(" ".join([str(item+1) for item in ans]))
# print("ans: ", ans)
# print("used: ", used)
# print()
```
Yes
| 5,189 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
mod=10**9+7
def ni():
return int(raw_input())
def li():
return map(int,raw_input().split())
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr('\n'.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
for t in range(ni()):
n=ni()
l=li()
d=Counter(l)
arr=[]
for i in range(1,2*n+1):
if not d[i]:
arr.append(i)
pos=0
d1=Counter()
f=0
for i in sorted(d):
if arr[pos]<i:
f=1
break
d1[i]=arr[pos]
pos+=1
if f:
print -1
continue
for i in range(n):
print l[i],d1[l[i]],
print
```
No
| 5,190 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
'''
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
'''
class NotFoundError(Exception):
def __str__(self):
return "Lexicograohic sequence nnot found"
def returnNumber(bFinal, a, index):
for i in range(len(a)):
# print(a[i], bFinal[index])
if a[i] > bFinal[index] and a[i] not in bFinal:
return a[i]
raise NotFoundError()
testCases = int(input())
for t in range(testCases):
n = int(input())
b = list(map(int, input().rstrip().split()))
a = [i for i in range(1, 2*n + 1)]
bFinal = [None]*2*n
for i in range(len(b)):
bFinal[2*i] = b[i]
for i in b:
if i in a:
a.pop(a.index(i))
# print(b)
# print(a)
# print(bFinal)
for i in range(n):
try:
bFinal[2*i + 1] = returnNumber(bFinal, a, 2*i)
# print("bFinal[2*i + 1]= ", bFinal[2*i + 1])
except NotFoundError as e:
# print(e)
bFinal = -1
break
# print(bFinal)
if type(bFinal) is list:
print(bFinal)
else:
print(-1)
```
No
| 5,191 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
input=stdin.readline
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
dict=defaultdict(int)
arr=[]
for i in range(n):
arr.append([a[i],i])
dict[a[i]]=1
arr.sort()
#print(arr)
tmp=[]
for i in range(1,2*n+1):
if dict[i]==0:
tmp.append(i)
#print(tmp)
fl=0
farr={}
for i in range(len(tmp)):
if arr[i][0]>tmp[i]:
fl=1
break
else:
farr[arr[i][0]]=tmp[i]
if fl==1:
print(-1)
else:
for x in a:
print(x,farr[x],end=" ")
print()
```
No
| 5,192 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
import heapq as pq
def solve():
n = int(input())
A = list(map(int,input().split()))
d = dict()
arr = [0 for _ in range(2*n)]
for i in range(n):
d[A[i]] = i
arr[2*i] = A[i]
A[i] = (A[i],i)
remaining = []
pq.heapify(remaining)
for i in range(1,(2*n)+1):
if d.get(i,-1)==-1:
pq.heappush(remaining,i)
# print("sds")
# print(A,arr,remaining)
A.sort(key = lambda x: x[0]+x[1])
for i in range(n):
curr1 = pq.heappop(remaining)
if A[i][0]>curr1:
print(-1)
return
arr[(2*d.get(A[i][0]))+1] = curr1
for i in range(2*n):
if i==(2*n)-1:
print(arr[i])
else:
print(arr[i],end=" ")
return
if __name__ == '__main__':
t = int(input())
for _ in range(t):
solve()
```
No
| 5,193 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence b_1, b_2, β¦, b_n. Find the lexicographically minimal permutation a_1, a_2, β¦, a_{2n} such that b_i = min(a_{2i-1}, a_{2i}), or determine that it is impossible.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 β€ t β€ 100).
The first line of each test case consists of one integer n β the number of elements in the sequence b (1 β€ n β€ 100).
The second line of each test case consists of n different integers b_1, β¦, b_n β elements of the sequence b (1 β€ b_i β€ 2n).
It is guaranteed that the sum of n by all test cases doesn't exceed 100.
Output
For each test case, if there is no appropriate permutation, print one number -1.
Otherwise, print 2n integers a_1, β¦, a_{2n} β required lexicographically minimal permutation of numbers from 1 to 2n.
Example
Input
5
1
1
2
4 1
3
4 1 3
4
2 3 4 5
5
1 5 7 2 8
Output
1 2
-1
4 5 1 2 3 6
-1
1 3 5 6 7 9 2 4 8 10
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
ar1 = list(map(int, input().split()))
ar2 = []
kek = set()
for i in range(n):
kek.add(ar1[i])
ar2.append([ar1[i], 0, i])
ar2.sort()
j = 0
flag = 0
for i in range(1, 2 * n + 1):
if i not in kek:
if i < ar2[j][0]:
flag = 1
break
ar2[j][1] = i
j += 1
if flag == 1:
print(-1)
else:
ar2.sort(key=lambda x:x[2])
ans = []
for a, b, c in ar2:
ans.append(a)
ans.append(b)
print(*ans)
```
No
| 5,194 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infinitely deep barrel;
3. take one cup of the hot water ...
4. and so on ...
Note that you always start with the cup of hot water.
The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
Input
The first line contains a single integer T (1 β€ T β€ 3 β
10^4) β the number of testcases.
Each of the next T lines contains three integers h, c and t (1 β€ c < h β€ 10^6; c β€ t β€ h) β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
Output
For each testcase print a single positive integer β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.
Example
Input
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
Note
In the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.
In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.
In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.
Tags: binary search, math
Correct Solution:
```
import math
from sys import stdin,stdout
import sys
import fractions
mod=1000000007
F=fractions.Fraction
t=int(stdin.readline())
while t>0:
h,c,tt=list(map(int,stdin.readline().split()))
mini=sys.maxsize
ans=0
if(2*tt>h+c):
low=1
high=1000000
mid=low+(high-low)//2
x=0
while(low<=high):
mid=low+(high-low)//2
if(mid<(h-tt)/((2*tt)-(h+c))):
x=mid
low=mid+1
else:
high=mid-1
if(mini>abs(tt-F(h*(x+1)+c*x,(2*x+1)))):
mini=abs(tt-F(h*(x+1)+c*x,(2*x+1)))
ans=2*x+1
low=1
high=1000000
mid=low+(high-low)//2
x=0
while(low<=high):
mid=low+(high-low)//2
if(mid>=(h-tt)/((2*tt)-(h+c))):
x=mid
high=mid-1
else:
low=mid+1
if(mini>abs(tt-F(h*(x+1)+c*x,(2*x+1)))):
mini=abs(tt-F(h*(x+1)+c*x,(2*x+1)))
ans=2*x+1
else:
ans=2
stdout.write(f"{ans}\n")
t-=1
```
| 5,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infinitely deep barrel;
3. take one cup of the hot water ...
4. and so on ...
Note that you always start with the cup of hot water.
The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
Input
The first line contains a single integer T (1 β€ T β€ 3 β
10^4) β the number of testcases.
Each of the next T lines contains three integers h, c and t (1 β€ c < h β€ 10^6; c β€ t β€ h) β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
Output
For each testcase print a single positive integer β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.
Example
Input
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
Note
In the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.
In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.
In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.
Tags: binary search, math
Correct Solution:
```
T=int(input())
for _ in range(T):
h,c,t=map(int,input().split())
d=10**9
if t<=(h+c)/2:
print(2)
continue
k=(h-t)//(2*t-h-c)
a=abs((k*(h+c)+h)-(2*k+1)*t)*(2*k+3)
b=abs(((k+1)*(h+c)+h)-(2*k+3)*t)*(2*k+1)
print([2*k+1,2*k+3][a>b])
```
| 5,196 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infinitely deep barrel;
3. take one cup of the hot water ...
4. and so on ...
Note that you always start with the cup of hot water.
The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
Input
The first line contains a single integer T (1 β€ T β€ 3 β
10^4) β the number of testcases.
Each of the next T lines contains three integers h, c and t (1 β€ c < h β€ 10^6; c β€ t β€ h) β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
Output
For each testcase print a single positive integer β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.
Example
Input
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
Note
In the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.
In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.
In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.
Tags: binary search, math
Correct Solution:
```
from collections import deque
import sys
def input(): return sys.stdin.readline().rstrip()
for _ in range(int(input())):
h, c, t = list(map(int, input().split()))
if (2 * t == c + h):
print(2)
continue
base = abs(h - c) // abs(2*t - c - h)
ans = 0
d = 2e18
for i in range(base - 100, base + 100):
if i < 1: continue
if i % 2 == 1 and abs((2 * t - c - h) * i + c - h) * ans < d * i:
d = abs((2 * t - c - h) * i + c - h)
ans = i
if (ans * abs(2 * t - c - h) <= abs(2 * t * ans - (c + h) * (ans - 1) - 2 * h)): ans = 2
print(ans)
```
| 5,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infinitely deep barrel;
3. take one cup of the hot water ...
4. and so on ...
Note that you always start with the cup of hot water.
The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
Input
The first line contains a single integer T (1 β€ T β€ 3 β
10^4) β the number of testcases.
Each of the next T lines contains three integers h, c and t (1 β€ c < h β€ 10^6; c β€ t β€ h) β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
Output
For each testcase print a single positive integer β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.
Example
Input
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
Note
In the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.
In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.
In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.
Tags: binary search, math
Correct Solution:
```
T = int(input())
s = []
for i in range(T):
s.append(input())
for i in range(T):
h, c, t = map(int,s[i].split())
if t == h:
n = 1
elif t <= (h+c)/2:
n = 2
else:
k = (c-t)/(h+c-2*t)
n = int(2*k-1)
if n%2 == 0:
n = n+1
k = (n+1)/2
tb = (k*h + (k-1)*c) / n
n1 = n-2
k = (n1+1)/2
tb1 = (k*h + (k-1)*c) / n1
n2 = n+2
k = (n2+1)/2
tb2 = (k*h + (k-1)*c) / n2
if abs(t-tb1)<abs(t-tb) and abs(t-tb1)<abs(t-tb2):
n = n1
if abs(t-tb2)<abs(t-tb) and abs(t-tb2)<abs(t-tb1):
n = n2
print(n)
```
| 5,198 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are two infinite sources of water:
* hot water of temperature h;
* cold water of temperature c (c < h).
You perform the following procedure of alternating moves:
1. take one cup of the hot water and pour it into an infinitely deep barrel;
2. take one cup of the cold water and pour it into an infinitely deep barrel;
3. take one cup of the hot water ...
4. and so on ...
Note that you always start with the cup of hot water.
The barrel is initially empty. You have to pour at least one cup into the barrel. The water temperature in the barrel is an average of the temperatures of the poured cups.
You want to achieve a temperature as close as possible to t. So if the temperature in the barrel is t_b, then the absolute difference of t_b and t (|t_b - t|) should be as small as possible.
How many cups should you pour into the barrel, so that the temperature in it is as close as possible to t? If there are multiple answers with the minimum absolute difference, then print the smallest of them.
Input
The first line contains a single integer T (1 β€ T β€ 3 β
10^4) β the number of testcases.
Each of the next T lines contains three integers h, c and t (1 β€ c < h β€ 10^6; c β€ t β€ h) β the temperature of the hot water, the temperature of the cold water and the desired temperature in the barrel.
Output
For each testcase print a single positive integer β the minimum number of cups required to be poured into the barrel to achieve the closest temperature to t.
Example
Input
3
30 10 20
41 15 30
18 13 18
Output
2
7
1
Note
In the first testcase the temperature after 2 poured cups: 1 hot and 1 cold is exactly 20. So that is the closest we can achieve.
In the second testcase the temperature after 7 poured cups: 4 hot and 3 cold is about 29.857. Pouring more water won't get us closer to t than that.
In the third testcase the temperature after 1 poured cup: 1 hot is 18. That's exactly equal to t.
Tags: binary search, math
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline
nTests=int(input())
for _ in range(nTests):
h,c,t=[int(zz) for zz in input().split()]
#Observe that for every nHot==nCold (nCups//2==0), finalt=(h+c)/2.
#if t<=(h+c)/2, ans=2
#else, find temp(nHot) just larger than t and find temp(nHot+1) or temp(nHot) is closer
if t<=(h+c)/2:
print(2)
elif t==h:
print(1)
else:
nHot=(t-c)//(2*t-h-c)
x=nHot
den1=2*x-1;den2=2*x+1
num1=abs(x*h+(x-1)*c-t*den1);num2=abs((x+1)*h+x*c-t*den2)
if num1*den2<=num2*den1:
print(2*x-1)
else:
print(2*x+1)
```
| 5,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.