message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0 | instruction | 0 | 30,819 | 14 | 61,638 |
"Correct Solution:
```
n,a,b,c,d=map(int,input().split())
dp=[0]*(n+1)
dp[0]=1
mod=10**9+7
N=n
fac=[1]*(N+3)
inv=[1]*(N+3)
t=1
for i in range(1,N+3):
t*=i
t%=mod
fac[i]=t
t=pow(fac[N+2],mod-2,mod)
for i in range(N+2,0,-1):
inv[i]=t
t*=i
t%=mod
def comb(n,r):
if r>n or r<0:
return 0
return fac[n]*inv[n-r]*inv[r]%mod
for i in range(a,b+1):
for j in range(n,i*c-1,-1):
for k in range(max(j-i*d,j%i),j-i*c+1,i):
l=((j-k)//i)
dp[j]+=dp[k]*fac[n-k]%mod*inv[n-j]*inv[l]%mod*pow(inv[i],l,mod)
dp[j]%=mod
print(dp[-1])
``` | output | 1 | 30,819 | 14 | 61,639 |
Provide a correct Python 3 solution for this coding contest problem.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0 | instruction | 0 | 30,821 | 14 | 61,642 |
"Correct Solution:
```
N, A, B, C, D = map(int, input().split())
MOD = 10 ** 9 + 7
fac = [1] * (N + 1)
for i in range(2, N + 1):
fac[i] = fac[i - 1] * i % MOD
finv = [1] * (N + 1)
finv[-1] = pow(fac[-1], MOD - 2, MOD)
for i in reversed(range(1, N + 1)):
finv[i - 1] = finv[i] * i % MOD
dp = [[0] * (N + 1) for _ in range(B + 1)]
dp[A - 1][0] = 1
for i in range(A, B + 1):
for j in range(N + 1):
dp[i][j] = dp[i - 1][j]
for k in range(C, min(D, j // i) + 1):
t = (fac[N - j + i * k] * finv[N - j] \
* pow(finv[i], k, MOD) * finv[k]) % MOD
dp[i][j] += dp[i - 1][j - i * k] * t
dp[i][j] %= MOD
print(dp[B][N])
``` | output | 1 | 30,821 | 14 | 61,643 |
Provide a correct Python 3 solution for this coding contest problem.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0 | instruction | 0 | 30,822 | 14 | 61,644 |
"Correct Solution:
```
class Combination:
"""
O(n)の前計算を1回行うことで,O(1)でnCr mod mを求められる
n_max = 10**6のとき前処理は約950ms (PyPyなら約340ms, 10**7で約1800ms)
使用例:
comb = Combination(1000000)
print(comb(5, 3)) # 10
"""
def __init__(self, n_max, mod=10**9+7):
self.mod = mod
self.modinv = self.make_modinv_list(n_max)
self.fac, self.facinv = self.make_factorial_list(n_max)
def __call__(self, n, r):
return self.fac[n] * self.facinv[r] % self.mod * self.facinv[n-r] % self.mod
def make_factorial_list(self, n):
# 階乗のリストと階乗のmod逆元のリストを返す O(n)
# self.make_modinv_list()が先に実行されている必要がある
fac = [1]
facinv = [1]
for i in range(1, n+1):
fac.append(fac[i-1] * i % self.mod)
facinv.append(facinv[i-1] * self.modinv[i] % self.mod)
return fac, facinv
def make_modinv_list(self, n):
# 0からnまでのmod逆元のリストを返す O(n)
modinv = [0] * (n+1)
modinv[1] = 1
for i in range(2, n+1):
modinv[i] = self.mod - self.mod//i * modinv[self.mod%i] % self.mod
return modinv
N, A, B, C, D = map(int, input().split())
mod = 10**9+7
comb = Combination(1010)
dp = [0]*(N+1)
dp[0] = 1
for n_person in range(A, B+1):
dp_new = dp[:]
for i, v in enumerate(dp):
c = 1
rem = N-i
for n_groups in range(1, C):
if rem < n_person:
break
c = c * comb(rem, n_person) % mod
rem -= n_person
else:
for n_groups in range(C, D+1):
if rem < n_person:
break
c = c * comb(rem, n_person) % mod
rem -= n_person
dp_new[N-rem] = (dp_new[N-rem] + c * comb.facinv[n_groups] * v) % mod
dp = dp_new
print(dp[N])
``` | output | 1 | 30,822 | 14 | 61,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
MOD = 10**9 + 7
def ex_euclid(a,b,c,d):
if (b == 1) : return d
x = a // b
y = a % b
return ex_euclid(b,y,d,(c[0]-x*d[0],c[1]-x*d[1]))
def mod_inv(a,p):
x = ex_euclid(p,a,(1,0),(0,1))
return x[1] % p
n,a,b,c,d = map(int,input().split())
gp = b-a+1
dp = [[-1 for j in range(n+1)] for i in range(gp)]
tb1=[0,1]
tb2=[1] #便宜上0の逆元は0にする
for i in range(2,n+1):
tb1.append((tb1[i-1]*i) % MOD)
for i in range(1,n+1):
tb2.append(mod_inv(tb1[i],MOD))
for i in range(gp):dp[i][0] = 1
def dfs(sum,k):
summ = sum
if(k < 0):
if (sum != 0):return 0
else : return 1
if dp[k][sum] != -1: return dp[k][sum]
kk = k+a
temp = dfs(sum,k-1)
temp1 = 1
for i in range(c-1):
if (sum < 0):break
temp1 = (temp1 * tb1[sum] * tb2[sum-kk]*tb2[kk]) % MOD
sum -= kk
for i in range(c,d+1):
if(sum-kk < 0) : break
temp1 = (temp1 * tb1[sum] * tb2[sum-kk]*tb2[kk]) % MOD
sum -= kk
temp = (temp + temp1*dfs(sum,k-1)*tb2[i]) % MOD
dp[k][summ] = temp
return temp
ans = dfs(n,gp-1)
print(ans)
``` | instruction | 0 | 30,823 | 14 | 61,646 |
Yes | output | 1 | 30,823 | 14 | 61,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
def prepare(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f = f * m % MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv = inv * m % MOD
invs[m - 1] = inv
return factorials, invs
def solve(n, a, b, c, d, MOD):
facts, invs = prepare(n, MOD)
dp = [0] * (n + 1)
dp[n] = 1
for i in range(a, b + 1):
iv = invs[i]
for j in range(i * c, n + 1):
base = dp[j] * facts[j] % MOD
for k in range(c, d + 1):
ik = i * k
if ik > j:
break
pat = base * invs[j - ik] % MOD
pat = pat * pow(iv, k, MOD) * invs[k]
dp[j - ik] = (dp[j - ik] + pat) % MOD
return dp[0]
n, a, b, c, d = map(int, input().split())
MOD = 10 ** 9 + 7
print(solve(n, a, b, c, d, MOD))
``` | instruction | 0 | 30,824 | 14 | 61,648 |
Yes | output | 1 | 30,824 | 14 | 61,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
mod = 10**9+7
def inpl(): return [int(i) for i in input().split()]
N, A, B, C, D = inpl()
fac = [1 for _ in range(N+1)]
for i in range(N):
fac[i+1] = (i+1)*fac[i] %mod
inv = [1 for _ in range(N+1)]
for i in range(2,N+1):
inv[i] = (-(mod//i) * inv[mod%i]) %mod
facinv = [1 for _ in range(N+1)]
for i in range(N):
facinv[i+1] = inv[i+1]*facinv[i] %mod
facinvp = [facinv]
for i in range(N-1):
p = facinvp[-1]
q = [p[i]*facinv[i]%mod for i in range(N+1)]
facinvp.append(q)
dp = [[0 for _ in range(N+1)] for _ in range(B+1)]
dp[A-1][0] = 1
for i in range(A-1,B):
for j in range(N+1):
dp[i+1][j] = dp[i][j]
for k in range(C,1+min(D, j//(i+1))):
x = j - k*(i+1)
dp[i+1][j] += fac[j]*facinv[x]*facinvp[k-1][i+1]*facinv[k]*dp[i][x]%mod
dp[i+1][j] %= mod
print(dp[B][N])
``` | instruction | 0 | 30,825 | 14 | 61,650 |
Yes | output | 1 | 30,825 | 14 | 61,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
from itertools import*
import math
from collections import*
from heapq import*
from bisect import bisect_left,bisect_right
from copy import deepcopy
inf = 10**18
mod = 10**9+7
from functools import reduce
import sys
sys.setrecursionlimit(10**7)
n,a,b,c,d = map(int,input().split())
Max = 1005
#二項係数とその逆元テーブルを作る前処理
fac = [0]*(Max)
finv = [0]*(Max)
inv = [0]*(Max)
fac[0]=fac[1]=1
finv[0]=finv[1]=1
inv[1]=1
for i in range(2,Max):
fac[i] = fac[i-1] * i % mod
inv[i] = mod - inv[mod%i]*(mod//i)%mod
finv[i] = finv[i-1]*inv[i]%mod
#O(1)でmod計算した組合せ数を計算
def C(n,r):
if n < r:
return 0
if n < 0 or r < 0 :
return 0
return fac[n]*(finv[r]*finv[n-r]%mod)%mod
#mod計算した順列の計算
def P(n,r):
if n < r:
return 0
if n<0 or r<0:
return 0
return (fac[n]*finv[n-r])%mod
#dp[i][j]:i人以下のグループだけでj人使っている場合の数
dp = [[0]*(n+1) for i in range(n+1)]
for i in range(n+1):
dp[i][0]=1
for i in range(a,b+1):
for j in range(1,n+1):
dp[i][j] = dp[i-1][j]
k = c
while k <= j//i and k <= d:
x = (fac[j] * finv[j - k * i] * finv[k] * pow(finv[i], k, mod)) % mod
dp[i][j] += (dp[i - 1][j - k * i] * x) % mod
k += 1
dp[i][j] %= mod
print(dp[b][n])
``` | instruction | 0 | 30,826 | 14 | 61,652 |
Yes | output | 1 | 30,826 | 14 | 61,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
N, A, B, C, D = map(int, input().split())
memo = {}
def factorial(x):
if x in memo:
return memo[x]
if x <= 1:
ret = 1
else:
ret = x * factorial(x-1)
memo[x] = ret
return ret
def process(N, groups, total, num, B, C, D):
if num > B:
if total != N:
return 0
print(groups)
rest = N
ret = 1
for g,n in groups:
for k in range(n):
ret *= factorial(rest) / factorial(g) / factorial(rest-g)
rest -= g
ret //= factorial(n)
return ret
ret = 0
for n in [0] + list(range(C, D+1)):
nextTotal = total + num * n
if nextTotal <= N:
ret += process(N, groups+[(num,n)], nextTotal, num+1, B, C, D)
return ret
print(process(N, [], 0, A, B, C, D))
``` | instruction | 0 | 30,827 | 14 | 61,654 |
No | output | 1 | 30,827 | 14 | 61,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
class Combination:
"""階乗とその逆元のテーブルをO(N)で事前作成し、組み合わせの計算をO(1)で行う"""
def __init__(self, n, MOD):
self.fact = [1]
for i in range(1, n + 1):
self.fact.append(self.fact[-1] * i % MOD)
self.inv_fact = [0] * (n + 1)
self.inv_fact[n] = pow(self.fact[n], MOD - 2, MOD)
for i in reversed(range(n)):
self.inv_fact[i] = self.inv_fact[i + 1] * (i + 1) % MOD
self.MOD = MOD
def factorial(self, k):
"""k!を求める O(1)"""
return self.fact[k]
def inverse_factorial(self, k):
"""k!の逆元を求める O(1)"""
return self.inv_fact[k]
def permutation(self, k, r):
"""kPrを求める O(1)"""
if k < r:
return 0
return (self.fact[k] * self.inv_fact[k - r]) % self.MOD
def combination(self, k, r):
"""kCrを求める O(1)"""
if k < r:
return 0
return (self.fact[k] * self.inv_fact[k - r] * self.inv_fact[r]) % self.MOD
def combination2(self, k, r):
"""kCrを求める O(r) kが大きいが、r <= nを満たしているときに使用"""
if k < r:
return 0
res = 1
for l in range(r):
res *= (k - l)
res %= self.MOD
return (res * self.inv_fact[r]) % self.MOD
n, a, b, c, d = map(int, input().split())
MOD = 10 ** 9 + 7
comb = Combination(10 ** 5, MOD)
# dp[i][j] := i番目のグループ(a~b)まで見たとき、j人がグループ分けされるときの通り数
dp = [[0] * (n + 1) for i in range(b - a + 2)]
dp[0][0] = 1
for i in range(b - a + 1):
per_g = i + a
for j in range(0, n + 1):
dp[i + 1][j] = dp[i][j]
for cnt_g in range(c, d + 1):
if j - cnt_g * per_g >= 0:
p = comb.factorial(per_g) ** cnt_g
dp[i + 1][j] += dp[i][j - cnt_g * per_g] * comb.combination(j, cnt_g * per_g)\
* comb.factorial(cnt_g * per_g) * (comb.inverse_factorial(per_g) ** cnt_g)\
* comb.inverse_factorial(cnt_g)
dp[i + 1][j] %= MOD
print(dp[-1][-1])
``` | instruction | 0 | 30,828 | 14 | 61,656 |
No | output | 1 | 30,828 | 14 | 61,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
from functools import lru_cache
n,a,b,c,d=map(int,input().split())
mod=10**9+7
fac=[1]*(n+3)
finv=[1]*(n+3)
t=1
for i in range(1,n+3):
t*=i
t%=mod
fac[i]=t
t=1
for i in range(1,n+3):
t*=pow(i,mod-2,mod)
t%=mod
finv[i]=t
@lru_cache()
def comb(a,b):
if a<b:return 0
return fac[a]*(finv[a-b]*finv[b]%mod)%mod
dp=[[0 if i else 1 for i in range(n+2)] for _ in range(n+2)]
for i in range(a,b+1):
for j in range(n+1):
if not dp[i][j]:continue
if j:dp[i+1][j]=(dp[i+1][j]+dp[i][j])%mod
p=1
for k in range(1,1+(n-j)//i):
if not k<=d:break
p=((p*comb(n-j-i*(k-1),i)%mod)*pow(k,mod-2,mod))%mod
if k>=c:
dp[i+1][j+i*k]+=(dp[i][j]*p%mod)
dp[i+1][j+i*k]%=mod
print(dp[b+1][n]%mod)
``` | instruction | 0 | 30,829 | 14 | 61,658 |
No | output | 1 | 30,829 | 14 | 61,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N people, conveniently numbered 1 through N. We want to divide them into some number of groups, under the following two conditions:
* Every group contains between A and B people, inclusive.
* Let F_i be the number of the groups containing exactly i people. Then, for all i, either F_i=0 or C≤F_i≤D holds.
Find the number of these ways to divide the people into groups. Here, two ways to divide them into groups is considered different if and only if there exists two people such that they belong to the same group in exactly one of the two ways. Since the number of these ways can be extremely large, print the count modulo 10^9+7.
Constraints
* 1≤N≤10^3
* 1≤A≤B≤N
* 1≤C≤D≤N
Input
The input is given from Standard Input in the following format:
N A B C D
Output
Print the number of ways to divide the people into groups under the conditions, modulo 10^9+7.
Examples
Input
3 1 3 1 2
Output
4
Input
7 2 3 1 3
Output
105
Input
1000 1 1000 1 1000
Output
465231251
Input
10 3 4 2 5
Output
0
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
long long MOD = 1000000007;
vector<long long> F, RF, R;
void init(long long N) {
F.resize(N + 1), RF.resize(N + 1), R.resize(N + 1);
F[0] = F[1] = RF[0] = RF[1] = R[0] = R[1] = 1;
for (int i = 2; i <= N; i++) {
F[i] = (F[i - 1] * i) % MOD;
R[i] = MOD - (R[MOD % i] * (MOD / i)) % MOD;
RF[i] = (RF[i - 1] * R[i]) % MOD;
}
return;
}
long long Comb(long long A, long long B) {
if (B < 0 || A < B) return 0;
return (F[A] * ((RF[A - B] * RF[B]) % MOD)) % MOD;
}
int main() {
long long N, A, B, C, D;
cin >> N >> A >> B >> C >> D;
init(N);
vector<vector<long long> > DP(N + 1, vector<long long>(B + 1, 0));
DP[0][A - 1] = 1;
for (int i = A - 1; i < B; i++) {
vector<long long> X(D + 1);
X[0] = 1;
for (int j = 1; j <= D && j * (i + 1) - 1 <= N; j++) {
X[j] = (X[j - 1] * Comb(j * (i + 1) - 1, i)) % MOD;
}
for (int j = 0; j <= N; j++) {
DP[j][i + 1] += DP[j][i];
DP[j][i + 1] %= MOD;
for (int k = C; k <= D && k * (i + 1) + j <= N; k++) {
DP[j + k * (i + 1)][i + 1] +=
(DP[j][i] * ((Comb(N - j, k * (i + 1)) * X[k]) % MOD)) % MOD;
DP[j + k * (i + 1)][i + 1] %= MOD;
}
}
}
cout << DP[N][B] << endl;
return 0;
}
``` | instruction | 0 | 30,830 | 14 | 61,660 |
No | output | 1 | 30,830 | 14 | 61,661 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,027 | 14 | 62,054 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Codeforces Round #555 (Div. 3)
Problem F. Maximum Balanced Circle
:author: Kitchen Tong
:mail: kctong529@gmail.com
Please feel free to contact me if you have any question
regarding the implementation below.
"""
__version__ = '0.1'
__date__ = '2019-04-26'
import sys
def solve(n, a):
max_a = max(a)
counter = [0 for i in range(max_a+1)]
for ai in a:
counter[ai] += 1
best_group = []
best_total = 0
curr = 1
while curr <= max_a:
if counter[curr] > 0:
curr_group = [curr]
curr_total = counter[curr]
curr += 1
if curr > max_a:
break
while counter[curr] > 1:
curr_group.append(curr)
curr_total += counter[curr]
curr += 1
if curr > max_a:
break
if curr > max_a:
break
if counter[curr] > 0:
curr_group.append(curr)
curr_total += counter[curr]
if curr_total > best_total:
best_group = curr_group
best_total = curr_total
else:
curr += 1
if curr_total > best_total:
best_group = curr_group
best_total = curr_total
seq = best_group
for i in best_group[::-1]:
seq += [i] * (counter[i] - 1)
return (best_total, seq)
def main(argv=None):
n = int(input())
a = list(map(int, input().split()))
total, seq = solve(n, a)
print(total)
print(' '.join(map(str, seq)))
return 0
if __name__ == "__main__":
STATUS = main()
sys.exit(STATUS)
``` | output | 1 | 31,027 | 14 | 62,055 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,028 | 14 | 62,056 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
import sys
from collections import namedtuple
from itertools import groupby
input = sys.stdin.readline
def main():
Data = namedtuple('Data', ['arr', 'l', 'r'])
_ = int(input())
a = list(map(int, input().split()))
f = [ [0, 0] for i in range(max(a) + 2) ]
for x in a:
f[x][0] = x
f[x][1] += 1
best = 0
opt = None
for k, v in groupby(f, key = lambda x: 1 if x[1] else 0):
if not k:
continue
v = list(v)
i = lst = len(v) - 1
t = [0] * (len(v) + 1)
while i >= 0:
t[i] = t[i + 1] + v[i][1]
if t[i] - t[lst + 1] > best:
best = t[i] - t[lst + 1]
opt = Data(v, i, lst)
if v[i][1] == 1:
lst = i
i -= 1
ans = []
for i in range(opt.l, opt.r + 1):
ans.append(opt.arr[i][0])
opt.arr[i][1] -= 1
for i in range(opt.r, opt.l - 1, -1):
while opt.arr[i][1]:
ans.append(opt.arr[i][0])
opt.arr[i][1] -= 1
print(len(ans))
print(" ".join(map(str, ans)))
main()
``` | output | 1 | 31,028 | 14 | 62,057 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,029 | 14 | 62,058 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
def process(A):
d = {}
for x in A:
if x not in d:
d[x] = 0
d[x]+=1
my_max = [0, None, None]
current = None
for x in sorted(d):
if current is None or x-1 not in d:
current = [d[x], x, x]
my_max = max(my_max, current)
elif d[x] > 1 and x-1 in d:
current[0]+=d[x]
current[2] = x
my_max = max(my_max,current)
elif d[x]==1 and x-1 in d:
current[0]+=d[x]
current[2] = x
my_max = max(my_max, current)
current = [d[x], x, x]
else:
current = None
# print(x, my_max)
if current is not None:
my_max = max(my_max, current)
answer_c = my_max[0]
answer_l = []
for i in range(my_max[1], my_max[2]+1):
answer_l.append(i)
d[i]-=1
for i in range(my_max[2], my_max[1]-1, -1):
for j in range(d[i]):
answer_l.append(i)
return [answer_c, answer_l]
n = int(input())
A = [int(x) for x in input().split()]
a1, a2 = process(A)
print(a1)
print(' '.join(map(str, a2)))
``` | output | 1 | 31,029 | 14 | 62,059 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,030 | 14 | 62,060 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
rint = lambda: int(input())
rmint = lambda: map(int,input().split())
rlist = lambda: list(rmint())
n = rint()
lst = rlist()
cnt = {}
for nb in lst:
if nb not in cnt :
cnt[nb] = 1
else:
cnt[nb] +=1
arr = sorted(list(cnt.keys()))
N = len(arr)
# print(N,arr, cnt)
left, right, k = 0, 0, cnt[arr[0]]
left_best, right_best, k_best = 0, 0, cnt[arr[0]]
while right < N:
while right + 1 < N and arr[right+1] == arr[right] +1 and cnt[arr[right]] >=2:
right = right +1
k += cnt[arr[right]]
if k_best < k:
left_best, right_best, k_best = left, right, k
if right +1 >= N:
break
elif arr[right+1] != arr[right] + 1 :
left = right+1
right = right +1
k = cnt[arr[left]]
else:
left = right
right = right+1
k = cnt[arr[left]] + cnt[arr[right]]
# print(left_best, right_best, k_best,"___________")
print(k_best)
for idx in range(left_best, right_best+1):
print((str(arr[idx]) + " ") * (cnt[arr[idx]]-1), end = "")
for idx in range(right_best, left_best-1,-1):
print((str(arr[idx]))+" ", end= "")
print("")
``` | output | 1 | 31,030 | 14 | 62,061 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,031 | 14 | 62,062 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
###########################
# Sorted list
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
# self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
# self.lista[a] += self.lista[b]
# self.lista[b] = []
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
#
# to find factorial and ncr
# tot = 200005
# mod = 10**9 + 7
# fac = [1, 1]
# finv = [1, 1]
# inv = [0, 1]
#
# for i in range(2, tot + 1):
# fac.append((fac[-1] * i) % mod)
# inv.append(mod - (inv[mod % i] * (mod // i) % mod))
# finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def arr1d(n, v):
return [v] * n
def arr2d(n, m, v):
return [[v] * m for _ in range(n)]
def arr3d(n, m, p, v):
return [[[v] * p for _ in range(m)] for i in range(n)]
def ceil(a,b):
return (a+b-1)//b
#co-ordinate compression
#ma={s:idx for idx,s in enumerate(sorted(set(l+r)))}
def solve():
n=N()
ar=lis()
mxn=200005
freq=[0]*mxn
mxcycle=0
curcycle=0
curans=[]
for i in ar:
freq[i]+=1
for i in range(1,mxn):
if freq[i]>1:
curcycle+=freq[i]
curans.append((i,freq[i]))
else:
if freq[i]==1:
curcycle+=freq[i]
curans.append((i, freq[i]))
if curcycle>mxcycle:
mxcycle=curcycle
mxans=curans.copy()
curcycle=0
curans=[].copy()
if curcycle > mxcycle:
mxcycle = curcycle
mxans = curans.copy()
if mxcycle==1:
for i in range(1,mxn):
if freq[i]>0 and freq[i+1]>0:
print(2)
print(i,i+1)
return
ans=[]
backans=[]
for j in mxans:
i,nt=j
backans.append(i)
ans+=[i]*(nt-1)
ans+=backans[::-1]
if (freq[ans[0]-1]>0):
ans=([ans[0]-1]*freq[ans[0]-1]) +ans
print(len(ans))
print(*ans)
solve()
#testcase(int(inp()))
``` | output | 1 | 31,031 | 14 | 62,063 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,032 | 14 | 62,064 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
import sys
from collections import Counter
input = sys.stdin.readline
n=int(input())
A=Counter(map(int,input().split()))
M=max(A)
DP0=[0]*(M+1)
DP1=[0]*(M+1)
for i in range(M+1):
if A[i]>=2 and A[i-1]>=2:
DP0[i]=DP0[i-1]+A[i]
elif A[i]>=2 and A[i-1]==1:
DP0[i]=1+A[i]
elif A[i]>=2 and A[i-1]==0:
DP0[i]=A[i]
elif A[i]==1:
DP0[i]=1
if A[i]>=2:
DP1[i]=DP0[i]
elif A[i]==1:
DP1[i]=DP0[i-1]+1
ANS=max(DP1)
print(ANS)
BIG=DP1.index(ANS)
for i in range(BIG-1,-1,-1):
if A[i]==1:
SMALL=i
break
if A[i]==0:
SMALL=i+1
break
ANSLIST=list(range(SMALL,BIG+1))
for i in range(BIG,SMALL-1,-1):
for k in range(A[i]-1):
ANSLIST.append(i)
print(*ANSLIST)
``` | output | 1 | 31,032 | 14 | 62,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,033 | 14 | 62,066 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
c =[0]*2*100007
s =[0]*2*100007
result=0
dis=0
result_list=[]
for i in a:
c[i]+=1
for i in range(len(c)):
if c[i]>0:
s[i]=c[i]
result=c[i]
dis=i
break
for i in range(dis+1,len(c)):
if c[i]>1:
s[i]=max(s[i-1]+c[i],c[i-1]+c[i])
else:
s[i]=0
for i in range(1,len(s)):
if c[i]+s[i-1]>result:
result=c[i]+s[i-1]
dis=i
if c[i]+c[i-1]>result:
result=c[i]+c[i-1]
dis=i
for i in range(dis-1,-1,-1):
if c[i]==1:
pos=i
break
if c[i]==0:
pos=i+1
break
print(result)
for i in range(pos,dis+1):
print(i,end=" ")
for i in range(dis,pos-1,-1):
for j in range(1,c[i]):
print(i,end=" ")
``` | output | 1 | 31,033 | 14 | 62,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2 | instruction | 0 | 31,034 | 14 | 62,068 |
Tags: constructive algorithms, dp, greedy, two pointers
Correct Solution:
```
import io
import os
from collections import defaultdict
from sys import stdin, stdout
#input = stdin.readline
def main():
n = int(input())
a = list(map(int, input().split()))
s = sorted(set(a))
d = {}
for val in s:
d[val] = 0
for val in a:
d[val] += 1
max_len = 1
res = [a[0]]
# len 2
for j in range(len(s)-1):
if d[s[j]] == 1 and d[s[j+1]] == 1 and s[j+1]-s[j]==1:
max_len = 2
res = [s[j], s[j+1]]
break
# len > 2
start = 0
while start < len(s) and d[s[start]] == 1:
start += 1
while start < len(s):
if start < len(s):
l = start
r = start
while l > 0 and d[s[l-1]] > 1 and s[l]-s[l-1]==1:
l -= 1
while r < len(s)-1 and d[s[r+1]] > 1 and s[r+1]-s[r]==1:
r += 1
if l > 0 and s[l]-s[l-1] == 1:
l -= 1
if r < len(s)-1 and s[r+1]-s[r] == 1:
r += 1
total = 0
for j in range(l, r+1):
total += d[s[j]]
if total > max_len:
max_len = total
res = []
for j in range(l, r+1):
res.append(s[j])
d[s[j]] -= 1
for j in range(r, l-1, -1):
while d[s[j]] > 0:
res.append(s[j])
d[s[j]] -= 1
start = r+1
while start < len(s) and d[s[start]] == 1:
start += 1
print(len(res))
print(*res)
if __name__ == '__main__':
main()
``` | output | 1 | 31,034 | 14 | 62,069 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
if n == 1:
print(1)
print(a[0])
exit(0)
a.sort()
b = [a[0]]
cnt = [0]*(200*1000+1)
cnt[a[0]]+=1
for i in range(1,n):
cnt[a[i]]+=1
if a[i-1] != a[i]:
b.append(a[i])
l=0
r=1
ans = cnt[a[0]]
i=0
while i < len(b):
j=i+1
su = cnt[b[i]]
while j<len(b) and b[j]-b[j-1]==1 and cnt[b[j]]>=2:
su+=cnt[b[j]]
j+=1
tmp = j
if j<len(b) and b[j]-b[j-1] == 1:
su+=cnt[b[j]]
j+=1
if ans<su:
ans = su
l = i
r = j
i=tmp
print(ans)
for i in range(l,r):
print(b[i],end = ' ')
for i in range(r-1,l-1,-1):
for j in range(0,cnt[b[i]]-1):
print(b[i],end = ' ')
``` | instruction | 0 | 31,035 | 14 | 62,070 |
Yes | output | 1 | 31,035 | 14 | 62,071 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
def solve():
n = int(input())
a = sorted(map(int, input().split()))
ans = (1, 0)
cur = [a[0]]
for i in range(1, n):
if a[i] - a[i - 1] > 1:
ans = max(ans, (len(cur), i - 1))
cur.clear()
elif a[i - 1] < a[i] and (i == n - 1 or a[i] < a[i + 1]):
cur.append(a[i])
ans = max(ans, (len(cur), i))
cur.clear()
cur.append(a[i])
ans = max(ans, (len(cur), n - 1))
print(ans[0])
ans1 = []
ans2 = []
for i in a[ans[1]-ans[0]+1:ans[1]+1]:
if not ans1 or ans1[-1] != i:
ans1.append(i)
else:
ans2.append(i)
print(*(ans1 + ans2[::-1]))
for _ in range(1):
solve()
``` | instruction | 0 | 31,036 | 14 | 62,072 |
Yes | output | 1 | 31,036 | 14 | 62,073 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
# AC
import sys
class Main:
def __init__(self):
self.buff = None
self.index = 0
def next(self):
if self.buff is None or self.index == len(self.buff):
self.buff = self.next_line()
self.index = 0
val = self.buff[self.index]
self.index += 1
return val
def next_line(self, _map=str):
return list(map(_map, sys.stdin.readline().split()))
def next_int(self):
return int(self.next())
def solve(self):
n = self.next_int()
x = sorted([self.next_int() for _ in range(0, n)])
ml = -1
_i = 0
_j = 0
j = 0
for i in range(0, n):
j = max(j, i)
while j + 1 < n and x[j + 1] == x[i]:
j += 1
while j + 2 < n and x[j + 2] == x[j] + 1:
j += 2
while j + 1 < n and x[j + 1] == x[j]:
j += 1
jj = j
if j + 1 < n and x[j + 1] == x[j] + 1:
jj += 1
if jj - i > ml:
ml = jj - i
_i = i
_j = jj
a = []
b = []
i = _i
while i <= _j:
a.append(x[i])
i += 1
while i <= _j and x[i] == a[-1]:
b.append(x[i])
i += 1
print(ml + 1)
print(' '.join([str(x) for x in (a + b[::-1])]))
if __name__ == '__main__':
Main().solve()
``` | instruction | 0 | 31,037 | 14 | 62,074 |
Yes | output | 1 | 31,037 | 14 | 62,075 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
kk=lambda:map(int,input().split())
ll=lambda:list(kk())
n = int(input())
d = {}
for v in kk():
if v not in d: d[v] = 0
d[v]+=1
k = list(d.keys())
k.sort()
i = 0
m = 0
while i < len(k):
start =x= k[i]
total = d[start]
while i+1 < len(k) and k[i]+1 == k[i+1]:
i+=1
total+=d[k[i]]
if d[k[i]] == 1:
if total > m: m,mi = total,(start, k[i])
break
else:
i+=1
if total > m: m,mi = total,(start, k[i-1])
print(m)
tbp = []
for i in range(mi[0], mi[1]+1):
tbp.extend([i]*(d[i]-1))
print()
for i in range(mi[1], mi[0]-1, -1):
tbp.append(i)
print(*tbp)
``` | instruction | 0 | 31,038 | 14 | 62,076 |
Yes | output | 1 | 31,038 | 14 | 62,077 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
#!/usr/bin/python3
number = int(input())
data_weight = input().split(" ")
if len(data_weight)!=number:
raise RuntimeError("Not enought or too much weight given")
data_weight = list(map(lambda element: int(element), data_weight))
class Node():
def __init__(self, value):
self.value = value
self.connect = list()
def get_friend(self):
for element in self.connect:
yield element
def add_friend(self, val):
self.connect.append(val)
def __call__(self):
return self.value
def __repr__(self):
friend = ""
for f in self.connect:
friend+= " {},".format(f.value)
return " < {} -> {} >".format(self.value, friend)
data_weight.sort()
graph = [Node(element) for element in data_weight]
for index in range(len(graph)):
curr = index -1
while curr>-1 and abs(graph[curr]()-graph[index]())<=1:
graph[index].add_friend(graph[curr])
curr-=1
curr = index +1
while curr<len(graph) and abs(graph[curr]()-graph[index]())<=1:
graph[index].add_friend(graph[curr])
curr+=1
already_see = []
def explore(node, already_see, lenght, init):
if node is init:
return lenght, already_see
if node in already_see and not (node is init):
return -1, already_see
maxi = -1
final_already_see= []
for element in node.get_friend():
val, ch = explore(element, already_see+[node,], lenght+1, init)
if val>maxi:
maxi = val
final_already_see = ch
return maxi, final_already_see
maxi = -1
final_already_see = list()
for node in graph:
local_max = -1
local_already_see = []
for children in node.get_friend():
val, ch = explore(children, [node], 1, node)
if val>local_max:
local_max = val
local_already_see = ch
if local_max>maxi:
maxi = local_max
root = node
final_already_see= local_already_see
print(len(final_already_see))
print(" ".join(map(lambda node: str(node.value),final_already_see )))
``` | instruction | 0 | 31,039 | 14 | 62,078 |
No | output | 1 | 31,039 | 14 | 62,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
c =[0]*2*100007
s =[0]*2*100007
result=0
dis=0
result_list=[]
for i in a:
c[i]+=1
for i in range(len(c)):
if c[i]>0:
s[i]=c[i]
result=c[i]
dis=i
break
for i in range(dis+1,len(c)):
if c[i]>1:
s[i]=max(s[i-1]+c[i],c[i-1]+c[i])
else:
s[i]=0
for i in range(1,len(s)):
if c[i]+s[i-1]>result:
result=c[i]+s[i-1]
dis=i
if c[i]+c[i-1]>result:
result=c[i]+c[i-1]
dis=i
for i in range(dis,-1,-1):
if c[i]==0:
pos=i+1
break
if result==73893:
for i in range(pos,dis+1):
result_list.append(i)
for i in range(dis,pos-1,-1):
for j in range(1,c[i]):
result_list.append(i)
print(pos)
print(dis)
print(c[pos])
print(c[dis])
print(result_list[0])
print(result_list[-1])
print(result_list[73892])
print(len(result_list))
print(result)
for i in range(pos,dis+1):
print(i,end=" ")
for i in range(dis,pos-1,-1):
for j in range(1,c[i]):
print(i,end=" ")
``` | instruction | 0 | 31,040 | 14 | 62,080 |
No | output | 1 | 31,040 | 14 | 62,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
c =[0]*2*100007
s =[0]*2*100007
result=0
dis=0
result_list=[]
for i in a:
c[i]+=1
for i in range(len(c)):
if c[i]>0:
s[i]=c[i]
result=c[i]
dis=i
break
for i in range(dis+1,len(c)):
if c[i]>1:
s[i]=max(s[i-1]+c[i],c[i-1]+c[i])
else:
s[i]=0
for i in range(1,len(s)):
if c[i]+s[i-1]>result:
result=c[i]+s[i-1]
dis=i
for i in range(dis,-1,-1):
if c[i]==0:
pos=i+1
break
print(result)
for i in range(pos,dis+1):
print(i,end=" ")
for i in range(dis,pos-1,-1):
for j in range(1,c[i]):
print(i,end=" ")
``` | instruction | 0 | 31,041 | 14 | 62,082 |
No | output | 1 | 31,041 | 14 | 62,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n people in a row. The height of the i-th person is a_i. You can choose any subset of these people and try to arrange them into a balanced circle.
A balanced circle is such an order of people that the difference between heights of any adjacent people is no more than 1. For example, let heights of chosen people be [a_{i_1}, a_{i_2}, ..., a_{i_k}], where k is the number of people you choose. Then the condition |a_{i_j} - a_{i_{j + 1}}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |a_{i_1} - a_{i_k}| ≤ 1 should be also satisfied. |x| means the absolute value of x. It is obvious that the circle consisting of one person is balanced.
Your task is to choose the maximum number of people and construct a balanced circle consisting of all chosen people. It is obvious that the circle consisting of one person is balanced so the answer always exists.
Input
The first line of the input contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of people.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the height of the i-th person.
Output
In the first line of the output print k — the number of people in the maximum balanced circle.
In the second line print k integers res_1, res_2, ..., res_k, where res_j is the height of the j-th person in the maximum balanced circle. The condition |res_{j} - res_{j + 1}| ≤ 1 should be satisfied for all j from 1 to k-1 and the condition |res_{1} - res_{k}| ≤ 1 should be also satisfied.
Examples
Input
7
4 3 5 1 2 2 1
Output
5
2 1 1 2 3
Input
5
3 7 5 1 5
Output
2
5 5
Input
3
5 1 4
Output
2
4 5
Input
7
2 2 3 2 1 2 2
Output
7
1 2 2 2 2 3 2
Submitted Solution:
```
from collections import Counter
n=int(input())
a=list(map(int,input().split()))
t=Counter(a)
l=[[x,t[x]] for x in t]
l.sort(key=lambda x:x[0])
i=0;j=1
f=[]
ans=1
ians=0
jans=1
cntr=l[0][1]
while j<len(l):
if l[j][0]>l[j-1][0]+1:
if cntr>ans:
ans=cntr;ians=i;jans=j-1
cntr=l[j][1]
i=j
j=i+1
elif l[j][1]==1:
if cntr+1>ans:
ans=cntr+1;ians=i;jans=j
cntr=1
i=j
j=i+1
else:
cntr+=l[j][1]
j+=1
if cntr>ans:
ans=cntr;ians=i;jans=n-1
p=[]
h=[]
for c in l[ians+1:jans]:
h=[c[0]]+h
for c in l[ians+1:jans]:
p=p+[c[0]]*(c[1]-1)
p=[l[ians][0]]*l[ians][1]+p
if jans!=ians and jans<len(l):
p=p+[l[jans][0]]*l[jans][1]+h
print(len(p))
print(*p)
``` | instruction | 0 | 31,042 | 14 | 62,084 |
No | output | 1 | 31,042 | 14 | 62,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements. | instruction | 0 | 31,203 | 14 | 62,406 |
Tags: constructive algorithms, dfs and similar, graphs, shortest paths
Correct Solution:
```
n, m = map(int, input().split())
edge = [[] for i in range(n)]
cost = [[10 ** 18 * (i != j) for j in range(n)] for i in range(n)]
for _ in range(m):
u, v, b = map(int, input().split())
edge[u - 1].append(v - 1)
edge[v - 1].append(u - 1)
cost[u - 1][v - 1] = 1
cost[v - 1][u - 1] = (1 if not b else -1)
used = [False] * n
cond = [0] * n
used[0] = True
stack = [0]
INF = 10 ** 18
while stack:
v = stack.pop()
for nv in edge[v]:
if not used[nv]:
cond[nv] = 1 - cond[v]
used[nv] = True
stack.append(nv)
else:
if cond[nv] == cond[v]:
exit(print("NO"))
for k in range(n):
for i in range(n):
for j in range(n):
if cost[i][k] == -INF or cost[k][j] == -INF:
cost[i][j] = -INF
elif cost[i][j] > cost[i][k] + cost[k][j]:
cost[i][j] = cost[i][k] + cost[k][j]
if cost[i][j] <= -n: cost[i][j] = -INF
check = all(cost[i][i] == 0 for i in range(n))
if not check:
print("NO")
exit()
print("YES")
res = 0
idx = -1
for i in range(n):
tmp = max(cost[i])
if min(cost[i]) != 0: continue
if tmp > res:
res = tmp
idx = i
print(res)
print(*cost[idx])
``` | output | 1 | 31,203 | 14 | 62,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements. | instruction | 0 | 31,204 | 14 | 62,408 |
Tags: constructive algorithms, dfs and similar, graphs, shortest paths
Correct Solution:
```
from collections import deque
N, M = map(int, input().split())
X = [[] for i in range(N)]
Y = [[] for i in range(N)]
for i in range(M):
x, y, w = map(int, input().split())
X[x-1].append(y-1)
X[y-1].append(x-1)
if w == 0:
Y[x-1].append((y-1, 1))
Y[y-1].append((x-1, 1))
else:
Y[x-1].append((y-1, 1))
Y[y-1].append((x-1, -1))
def bipartite(n, E):
col = [-1] * n
for i in range(n):
if col[i] >= 0: continue
que = deque([[i, 0]])
while que:
v, c = que.popleft()
if col[v] == -1:
col[v] = c
elif col[v] == c:
continue
else:
return 0
for ne in E[v]:
if col[ne] == c:
return 0
if col[ne] < 0:
que.append([ne, 1-c])
return 1
def bellman_ford(n, E, s=0):
D = [1<<100] * n
D[s] = 0
f = 1
while f:
f = 0
for i in range(n):
for j, c in E[i]:
if D[i] < 1<<100 and D[j] > D[i] + c:
D[j] = D[i] + c
f = 1
return D
def bellman_ford_check(n, E, s=0):
D = [0] * n
for k in range(n):
for i in range(n):
for j, c in E[i]:
if D[j] > D[i] + c:
D[j] = D[i] + c
if k == n-1: return 1
return 0
if not bipartite(N, X):
print("NO")
else:
if bellman_ford_check(N, Y):
print("NO")
else:
print("YES")
ma = - (1 << 30)
for i in range(N):
D = bellman_ford(N, Y, i)
m = max(D)
if m > ma:
ma = m
maD = D
print(ma)
print(*maD)
``` | output | 1 | 31,204 | 14 | 62,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements. | instruction | 0 | 31,205 | 14 | 62,410 |
Tags: constructive algorithms, dfs and similar, graphs, shortest paths
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def MI(): return map(int, sys.stdin.buffer.readline().split())
def MI1(): return map(int1, sys.stdin.buffer.readline().split())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
inf = 10**16
md = 10**9+7
# md = 998244353
n, m = MI()
dd = [inf]*n*n
to = [[] for _ in range(n)]
for u in range(n): dd[u*n+u] = 0
for _ in range(m):
u, v, b = MI()
u, v = u-1, v-1
dd[u*n+v] = 1
dd[v*n+u] = 1-b*2
to[u].append(v)
to[v].append(u)
# p2D(dd)
color = [-1]*n
color[0] = 0
stack = [0]
while stack:
u = stack.pop()
for v in to[u]:
if color[v] == color[u]:
print("NO")
exit()
if color[v] == -1:
color[v] = 1-color[u]
stack.append(v)
def wf():
for v in range(n):
for u in range(n):
if dd[u*n+v] == inf: continue
for w in range(n):
if dd[v*n+w] == inf: continue
cur = dd[u*n+v]+dd[v*n+w]
if cur<=-n:
dd[0]=-1
return
if cur < dd[u*n+w]: dd[u*n+w] = cur
return
wf()
for u in range(n):
if dd[u*n+u] < 0:
print("NO")
exit()
mx = -1
mxu = 0
for u in range(n):
cur = max(dd[u*n+v] for v in range(n))
if cur > mx:
mx = cur
mxu = u
print("YES")
print(mx)
print(*[dd[mxu*n+v] for v in range(n)])
``` | output | 1 | 31,205 | 14 | 62,411 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements. | instruction | 0 | 31,206 | 14 | 62,412 |
Tags: constructive algorithms, dfs and similar, graphs, shortest paths
Correct Solution:
```
n,m = map(int,input().split());edge = [[] for i in range(n)];cost = [[10**18*(i!=j) for j in range(n)] for i in range(n)]
for _ in range(m):u,v,b = map(int,input().split());edge[u-1].append(v-1);edge[v-1].append(u-1);cost[u-1][v-1] = 1;cost[v-1][u-1] = (1 if not b else -1)
used = [False]*n;cond = [0]*n;used[0] = True;stack = [0];INF = 10**18
while stack:
v = stack.pop()
for nv in edge[v]:
if not used[nv]:cond[nv] = 1 - cond[v];used[nv] = True;stack.append(nv)
else:
if cond[nv]==cond[v]:exit(print("NO"))
for k in range(n):
for i in range(n):
for j in range(n):
if cost[i][k]==-INF or cost[k][j]==-INF:cost[i][j] = -INF
elif cost[i][j] > cost[i][k] + cost[k][j]:
cost[i][j] = cost[i][k] + cost[k][j]
if cost[i][j] <= -n:cost[i][j] = -INF
check = all(cost[i][i]==0 for i in range(n))
if not check:print("NO");exit()
print("YES");res = 0;idx = -1
for i in range(n):
tmp = max(cost[i])
if min(cost[i])!=0:continue
if tmp > res:res = tmp;idx = i
print(res);print(*cost[idx])
``` | output | 1 | 31,206 | 14 | 62,413 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements. | instruction | 0 | 31,207 | 14 | 62,414 |
Tags: constructive algorithms, dfs and similar, graphs, shortest paths
Correct Solution:
```
n,m = map(int,input().split())
edge = [[] for i in range(n)]
cost = [[10**18*(i!=j) for j in range(n)] for i in range(n)]
for _ in range(m):
u,v,b = map(int,input().split())
edge[u-1].append(v-1)
edge[v-1].append(u-1)
cost[u-1][v-1] = 1
if not b:
cost[v-1][u-1] = 1
else:
cost[v-1][u-1] = -1
used = [False]*n
cond = [0]*n
used[0] = True
stack = [0]
while stack:
v = stack.pop()
for nv in edge[v]:
if not used[nv]:
cond[nv] = 1 - cond[v]
used[nv] = True
stack.append(nv)
else:
if cond[nv]==cond[v]:
exit(print("NO"))
INF = 10**18
for k in range(n):
for i in range(n):
for j in range(n):
if cost[i][k]==-INF or cost[k][j]==-INF:
cost[i][j] = -INF
elif cost[i][j] > cost[i][k] + cost[k][j]:
cost[i][j] = cost[i][k] + cost[k][j]
if cost[i][j] <= -n:
cost[i][j] = -INF
check = all(cost[i][i]==0 for i in range(n))
if not check:
print("NO")
exit()
print("YES")
res = 0
idx = -1
for i in range(n):
tmp = max(cost[i])
if min(cost[i])!=0:
continue
if tmp > res:
res = tmp
idx = i
print(res)
print(*cost[idx])
``` | output | 1 | 31,207 | 14 | 62,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements.
Submitted Solution:
```
import sys
input = iter(sys.stdin.read().splitlines()).__next__
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
envied = [False]*n
for _ in range(m):
i, j, b = map(int, input().split())
i -= 1
j -= 1
edges[i].append(j)
if b == 0:
edges[j].append(i)
else:
envied[j] = True
# try set each person to minimum income if they have no necessarily
# incoming edges
capitalist = False
inequality = -1
best = None
for i in range(n):
if envied[i]:
continue
edges_copy = [set(edge) for edge in edges]
assignments = [None]*n
assignments[i] = 0
for friend in edges_copy[i]:
edges_copy[friend].discard(i) # one-sided envy
last = {i}
for income in range(1, n):
bfs_next = set()
for person in last:
for friend in edges_copy[person]:
if assignments[friend] is None:
assignments[friend] = income
bfs_next.add(friend)
elif assignments[friend] < income: # cycle bad
assignments[0] = None # force invalid assignment
bfs_next = set()
break
edges_copy[friend].discard(person)
else:
continue # no cycle, can continue bfs
break
if len(bfs_next) == 0:
break
last = bfs_next
if None not in assignments:
capitalist = True
max_income = max(assignments)
if max_income > inequality:
inequality = max_income
best = assignments
print("YES" if capitalist else "NO")
if capitalist:
print(inequality)
print(*best)
``` | instruction | 0 | 31,208 | 14 | 62,416 |
No | output | 1 | 31,208 | 14 | 62,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements.
Submitted Solution:
```
import sys
input = iter(sys.stdin.read().splitlines()).__next__
n, m = map(int, input().split())
edges = [[] for _ in range(n)]
envied = [False]*n
for _ in range(m):
i, j, b = map(int, input().split())
i -= 1
j -= 1
edges[i].append(j)
if b == 0:
edges[j].append(i)
else:
envied[j] = True
# try set each person to minimum income if they have no necessarily
# incoming edges
capitalist = False
inequality = -1
best = None
for i in range(n):
if envied[i]:
continue
edges_copy = [set(edge) for edge in edges]
assignments = [None]*n
assignments[i] = 0
last = {i}
for income in range(1, n):
bfs_next = set()
for person in last:
for friend in edges_copy[person]:
if assignments[friend] is None:
assignments[friend] = income
bfs_next.add(friend)
elif assignments[friend] < income: # cycle bad
assignments[0] = None
bfs_next = set()
break
edges_copy[friend].discard(person) # one-sided envy
if len(bfs_next) == 0:
break
last = bfs_next
if None not in assignments:
capitalist = True
max_income = max(assignments)
if max_income > inequality:
inequality = max_income
best = assignments
print("YES" if capitalist else "NO")
if capitalist:
print(inequality)
print(*best)
``` | instruction | 0 | 31,209 | 14 | 62,418 |
No | output | 1 | 31,209 | 14 | 62,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements.
Submitted Solution:
```
#!/usr/bin/env python3
from collections import *
from heapq import *
from itertools import *
from functools import *
from random import *
import sys
INF = float('Inf')
def genTokens(lines):
for line in lines:
for token in line.split():
yield token
def nextFn(fn):
return lambda it: fn(it.__next__())
nint = nextFn(int)
def genCases():
it = genTokens(sys.stdin)
T = 1
for _ in range(T):
N = nint(it)
M = nint(it)
Es = [(nint(it),nint(it),nint(it)) for _ in range(M)]
yield (N, M,Es)
def main():
for case in genCases():
solve(case)
def solve(case):
N, M,Es=case
adjList=[205*[INF] for _ in range(205)]
for i in range(1,N+1):
adjList[i][i]=0
for i,j,b in Es:
if b==0:
adjList[i][j]=1
adjList[j][i]=1
else:
adjList[i][j]=b
adjList[j][i]=-b
for k in range(1,N+1):
for i in range(1,N+1):
for j in range(1,N+1):
adjList[i][j]=min(adjList[i][j],adjList[i][k]+adjList[k][j])
for i in range(1,N+1):
if adjList[i][i]<0:
print("NO")
return
for i,j,_ in Es:
if adjList[i][j] == 0:
print("NO")
return
resMaxi=-INF
resNode=None
for i in range(1,N+1):
maxi=0
for j in range(1,N+1):
maxi=max(maxi,adjList[i][j])
if maxi>resMaxi:
resMaxi=maxi
resNode=i
print("YES")
print(resMaxi)
prow=[]
for j in range(1,N+1):
prow.append(str(adjList[resNode][j]))
print(' '.join(prow))
# print(adjList)
main()
``` | instruction | 0 | 31,210 | 14 | 62,420 |
No | output | 1 | 31,210 | 14 | 62,421 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A society can be represented by a connected, undirected graph of n vertices and m edges. The vertices represent people, and an edge (i,j) represents a friendship between people i and j.
In society, the i-th person has an income a_i. A person i is envious of person j if a_j=a_i+1. That is if person j has exactly 1 more unit of income than person i.
The society is called capitalist if for every pair of friends one is envious of the other. For some friendships, you know which friend is envious of the other. For the remaining friendships, you do not know the direction of envy.
The income inequality of society is defined as max_{1 ≤ i ≤ n} a_i - min_{1 ≤ i ≤ n} a_i.
You only know the friendships and not the incomes. If it is impossible for this society to be capitalist with the given knowledge, you should report about it. Otherwise, you should find an assignment of incomes in which the society is capitalist, and the income inequality is maximized.
Input
The first line contains two integers n, m (1≤ n≤ 200, n-1≤ m≤ 2000) — the number of people and friendships, respectively.
The following m lines describe the friendships. Each friendship is described by three integers i, j, b (1≤ i, j≤ n, i≠ j, 0≤ b≤ 1). This denotes that people i and j are friends. If b=1, we require that person i is envious of person j. If b=0, one friend should be envious of the other in either direction.
There is at most one friendship between each pair of people. It is guaranteed that if we consider the friendships as undirected edges, the graph is connected.
Output
Print "YES" if it is possible that the society is capitalist, or "NO" otherwise. You can print characters in any case (upper or lower).
If the answer is "YES", you should print two additional lines. In the first line, print the maximum possible income inequality. On the next line you should print n integers a_1,…, a_n (0≤ a_i≤ 10^6), where a_i denotes the income of the i-th person.
We can prove that if there exists a solution, there exists one where 0≤ a_i≤ 10^6 for all i.
If there exist multiple solutions, print any.
Examples
Input
6 6
1 2 0
3 2 0
2 5 0
6 5 1
6 3 0
2 4 1
Output
YES
3
3 2 1 3 1 0
Input
4 4
1 2 1
2 3 0
3 4 1
4 1 1
Output
NO
Input
1 0
Output
YES
0
0
Note
In the first test, we can show that an income inequality greater than 3 is impossible for the given society. In the given answer with income inequality equal to 3:
* Person 2 is envious of person 1.
* Person 3 is envious of person 2.
* Person 5 is envious of person 2.
* Person 6 is envious of person 5 (the required direction is satisfied).
* Person 6 is envious of person 3.
* Person 2 is envious of person 4 (the required direction is satisfied).
In the second test, we can show that there is no way to assign incomes to satisfy all requirements.
Submitted Solution:
```
#!/usr/bin/env python3
from collections import *
from heapq import *
from itertools import *
from functools import *
from random import *
import sys
INF = float('Inf')
def genTokens(lines):
for line in lines:
for token in line.split():
yield token
def nextFn(fn):
return lambda it: fn(it.__next__())
nint = nextFn(int)
def genCases():
it = genTokens(sys.stdin)
T = 1
for _ in range(T):
N = nint(it)
M = nint(it)
Es = [(nint(it),nint(it),nint(it)) for _ in range(M)]
yield (N, M,Es)
def main():
for case in genCases():
solve(case)
def solve(case):
N, M,Es=case
adjList=[205*[INF] for _ in range(205)]
for i in range(1,N+1):
adjList[i][i]=0
for i,j,b in Es:
if b==0:
adjList[i][j]=1
adjList[j][i]=1
else:
adjList[i][j]=b
adjList[j][i]=-b
for k in range(1,N+1):
for i in range(1,N+1):
for j in range(1,N+1):
adjList[i][j]=min(adjList[i][j],adjList[i][k]+adjList[k][j])
for i in range(1,N+1):
if adjList[i][i]<0:
print("NO")
return
for i,j,_ in Es:
if adjList[0][i]%2 == adjList[0][j]%2:
print("NO")
return
resMaxi=-INF
resNode=None
for i in range(1,N+1):
maxi=0
for j in range(1,N+1):
maxi=max(maxi,adjList[i][j])
if maxi>resMaxi:
resMaxi=maxi
resNode=i
print("YES")
print(resMaxi)
prow=[]
for j in range(1,N+1):
prow.append(str(adjList[resNode][j]))
print(' '.join(prow))
# print(adjList)
main()
``` | instruction | 0 | 31,211 | 14 | 62,422 |
No | output | 1 | 31,211 | 14 | 62,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
1. Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
2. Delete the first number of the current sequence.
The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
Input
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105).
The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
Output
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
Examples
Input
3 2
3 1 1
Output
1
Input
3 1
3 1 1
Output
-1
Note
In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.
In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1. | instruction | 0 | 31,257 | 14 | 62,514 |
Tags: brute force, implementation
Correct Solution:
```
n, k = map(int, input().split())
l = list(map(int, input().split()))
count = 0
prev = l[n-1]
for i in range(n-1, -1, -1):
if l[i]!=prev:
break
else:
count+=1
count = n-count
if k <= count:
print(-1)
else:
print(count)
``` | output | 1 | 31,257 | 14 | 62,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,448 | 14 | 62,896 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
i=0
while i<n//2:
if i%2==0:
a[i],a[n-1-i]=a[n-1-i],a[i]
i+=1
for i in range(n):
print(a[i],end=' ')
``` | output | 1 | 31,448 | 14 | 62,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,449 | 14 | 62,898 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
for i in range(0,n//2,2):
(l[i],l[-i-1]) = (l[-i-1],l[i])
print(*l)
``` | output | 1 | 31,449 | 14 | 62,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,450 | 14 | 62,900 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
nums = list(map(int, input().split()))
m = n//2
for i in range(m):
if i%2 == 0:
nums[i], nums[n-i-1] = nums[n-i-1], nums[i]
for j in nums:
print(j, end=' ')
``` | output | 1 | 31,450 | 14 | 62,901 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,451 | 14 | 62,902 |
Tags: constructive algorithms, implementation
Correct Solution:
```
num = int(input())
l = list(map(int,(input().split())))
l = list(reversed(l))
for i in range(num//2):
if i%2 != 0:
l[i],l[num-i-1] = l[num-i-1],l[i]
output = ' '.join(map(str,l))
print(output)
``` | output | 1 | 31,451 | 14 | 62,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,452 | 14 | 62,904 |
Tags: constructive algorithms, implementation
Correct Solution:
```
N, l = int(input()), [int(x) for x in input().split()]
for i in range(N // 2):
if(i % 2 == 0):
l[i], l[N - i - 1] = l[N - i - 1], l[i]
print(*l)
``` | output | 1 | 31,452 | 14 | 62,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,453 | 14 | 62,906 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, a = int(input()), input().split()
for i in range(0, n // 2, 2):
a[i], a[-i - 1] = a[-i - 1], a[i]
print(*a)
``` | output | 1 | 31,453 | 14 | 62,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,454 | 14 | 62,908 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, A = int(input()), input().split()
for i in range(0, n // 2, 2):
A[i], A[-i-1] = A[-i-1], A[i]
print(*A)
``` | output | 1 | 31,454 | 14 | 62,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Young Timofey has a birthday today! He got kit of n cubes as a birthday present from his parents. Every cube has a number ai, which is written on it. Timofey put all the cubes in a row and went to unpack other presents.
In this time, Timofey's elder brother, Dima reordered the cubes using the following rule. Suppose the cubes are numbered from 1 to n in their order. Dima performs several steps, on step i he reverses the segment of cubes from i-th to (n - i + 1)-th. He does this while i ≤ n - i + 1.
After performing the operations Dima went away, being very proud of himself. When Timofey returned to his cubes, he understood that their order was changed. Help Timofey as fast as you can and save the holiday — restore the initial order of the cubes using information of their current location.
Input
The first line contains single integer n (1 ≤ n ≤ 2·105) — the number of cubes.
The second line contains n integers a1, a2, ..., an ( - 109 ≤ ai ≤ 109), where ai is the number written on the i-th cube after Dima has changed their order.
Output
Print n integers, separated by spaces — the numbers written on the cubes in their initial order.
It can be shown that the answer is unique.
Examples
Input
7
4 3 7 6 9 1 2
Output
2 3 9 6 7 1 4
Input
8
6 1 4 2 5 6 9 2
Output
2 1 6 2 5 4 9 6
Note
Consider the first sample.
1. At the begining row was [2, 3, 9, 6, 7, 1, 4].
2. After first operation row was [4, 1, 7, 6, 9, 3, 2].
3. After second operation row was [4, 3, 9, 6, 7, 1, 2].
4. After third operation row was [4, 3, 7, 6, 9, 1, 2].
5. At fourth operation we reverse just middle element, so nothing has changed. The final row is [4, 3, 7, 6, 9, 1, 2]. So the answer for this case is row [2, 3, 9, 6, 7, 1, 4]. | instruction | 0 | 31,455 | 14 | 62,910 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
for i in range(n//2):
if (i+1) % 2:
a[i], a[n-1-i] = a[n-1-i], a[i]
for i in range(n):
print(a[i], end=' ')
``` | output | 1 | 31,455 | 14 | 62,911 |
Provide a correct Python 3 solution for this coding contest problem.
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10 | instruction | 0 | 31,557 | 14 | 63,114 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
N = int(readline())
P3 = [pow(3, i) for i in range(N+1)]
St = [1 if s == 'R' else 0 for s in readline().strip()]
LS = len(St)
ans = [None]*P3[N]
arr = [None]*P3[N]
ans[0] = 0
arr[0] = St[:]
REV = (0, 2, 1)
for l in range(N):
p3l = P3[l]
for i in range(p3l):
k0, k1, k2 = 0, 1, 2
r0, r1, r2 = [], [], []
for s in arr[i]:
if s:
k0 += 1
k1 += 1
k2 += 1
if k0 == 3:
k0 = 0
r0.append(1)
if k1 == 3:
k1 = 0
r1.append(1)
if k2 == 3:
k2 = 0
r2.append(1)
else:
k0 = REV[k0]
k1 = REV[k1]
k2 = REV[k2]
if r0 and r0[-1] == 0:
r0.pop()
else:
r0.append(0)
if r1 and r1[-1] == 0:
r1.pop()
else:
r1.append(0)
if r2 and r2[-1] == 0:
r2.pop()
else:
r2.append(0)
arr[2*p3l+i] = r2[:]
arr[p3l+i] = r1[:]
arr[i] = r0[:]
a = ans[i]
ans[2*p3l+i] = k2*p3l+a
ans[p3l+i] = k1*p3l+a
ans[i] = k0*p3l+a
print(*ans)
``` | output | 1 | 31,557 | 14 | 63,115 |
Provide a correct Python 3 solution for this coding contest problem.
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10 | instruction | 0 | 31,558 | 14 | 63,116 |
"Correct Solution:
```
# salsa=0, rumba=1
# [0 1 0 1] 1より上の位に帯する操作
# 繰り上がりを考慮しつつ、3(より上)の位に対する操作を考える
# [1] 1の位が0である数字の、3の位に対する操作
# [0 1 0] 1の位が1である数字の、3の位に対する操作
# [] 1の位が2である数字の、3の位に対する操作
# ある数字が"2"の時にルンバが来れば繰り上がる(上の位にルンバが波及)
# それ以外の状態では、上の位にとってルンバは無いのと同じことになる
# サルサは常に影響するが、連続した2つのサルサは打ち消し合い、無いのと同じことになる
# 再帰的に上の位を決める
# [] 3,1の位が00,10である数字の、9の位に対する操作
# [1] 3,1の位が20である数字の、9の位に対する操作
# [] 3,1の位が01,21である数字の、9の位に対する操作
# [0 1 0] 3,1の位が11である数字の、9の位に対する操作
# [] 3,1の位が02,12,22である数字の、9の位に対する操作
# 一度繰り上がったら、例えば100.. と0がd個続くとして、
# 更にその上の位に波及させるには 2^d オーダーの操作が必要となるので、各操作列は徐々に減っていく
n = int(input())
t = input()
op = [[int(c == 'R') for c in t]]
ans = [0]
for d in range(n):
k = 3 ** d
nop = []
nans = [0] * (k * 3)
for g in range(3): # d桁目の数
for i in range(k): # d桁目未満の数
opg = op[i]
opn = []
h = g
for o in opg:
if o == 0:
if len(opn) > 0 and opn[-1] == 0:
opn.pop()
else:
opn.append(0)
if h == 1:
h = 2
elif h == 2:
h = 1
else:
if h == 2:
h = 0
opn.append(1)
else:
h += 1
nop.append(opn)
nans[g * k + i] = h * k + ans[i]
op = nop
ans = nans
print(*ans)
``` | output | 1 | 31,558 | 14 | 63,117 |
Provide a correct Python 3 solution for this coding contest problem.
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10 | instruction | 0 | 31,559 | 14 | 63,118 |
"Correct Solution:
```
n = int(input())
s = input()
m = 3 ** n
ans = [0] * m
c = 3
t = [[0 if q == 'S' else 1 for q in s]]
for i in range(n) :
nt = [[]] * c
for j in range(c) :
x = j
x = x // (3**i)
pre = j - x*c//3
nxt = []
for q in t[pre] :
if q == 0 :
if x != 0 : x = 3 - x
if len(nxt) >= 1 and nxt[-1] == 0 : nxt.pop()
else : nxt.append(0)
else :
x += 1
if x == 3 :
x = 0
nxt.append(1)
for k in range(j,m,c):
ans[k] += x*c//3
nt[j] = nxt
t = nt
c *= 3
print(*ans)
``` | output | 1 | 31,559 | 14 | 63,119 |
Provide a correct Python 3 solution for this coding contest problem.
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10 | instruction | 0 | 31,560 | 14 | 63,120 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
def calc(x):
stack = []
for _ in range(N):
stack.append((3-x%3)%3)
x //= 3
res = 0
for i in range(N-1, -1, -1):
res *= 3
res += stack[i]
return res
N = int(readline())
P3 = [pow(3, i) for i in range(N+1)]
St = [1 if s == 'R' else 0 for s in readline().strip()]
LS = len(St)
ans = [None]*P3[N]
arr = [None]*P3[N]
ans[0] = 0
arr[0] = St[:]
REV = (0, 2, 1)
for l in range(N):
p3l = P3[l]
for i in range(p3l):
k0, k1, k2 = 0, 1, 2
r0, r1, r2 = [], [], []
for s in arr[i]:
if s:
k0 += 1
k1 += 1
k2 += 1
if k0 == 3:
k0 = 0
r0.append(1)
if k1 == 3:
k1 = 0
r1.append(1)
if k2 == 3:
k2 = 0
r2.append(1)
else:
k0 = REV[k0]
k1 = REV[k1]
k2 = REV[k2]
if r0 and r0[-1] == 0:
r0.pop()
else:
r0.append(0)
if r1 and r1[-1] == 0:
r1.pop()
else:
r1.append(0)
if r2 and r2[-1] == 0:
r2.pop()
else:
r2.append(0)
arr[2*p3l+i] = r2[:]
arr[p3l+i] = r1[:]
arr[i] = r0[:]
a = ans[i]
ans[2*p3l+i] = k2*p3l+a
ans[p3l+i] = k1*p3l+a
ans[i] = k0*p3l+a
print(*ans)
``` | output | 1 | 31,560 | 14 | 63,121 |
Provide a correct Python 3 solution for this coding contest problem.
There are 3^N people dancing in circle. We denote with 0,1,\dots, 3^{N}-1 the positions in the circle, starting from an arbitrary position and going around clockwise. Initially each position in the circle is occupied by one person.
The people are going to dance on two kinds of songs: salsa and rumba.
* When a salsa is played, the person in position i goes to position j, where j is the number obtained replacing all digits 1 with 2 and all digits 2 with 1 when reading i in base 3 (e.g., the person in position 46 goes to position 65).
* When a rumba is played, the person in position i moves to position i+1 (with the identification 3^N = 0).
You are given a string T=T_1T_2\cdots T_{|T|} such that T_i=`S` if the i-th song is a salsa and T_i=`R` if it is a rumba. After all the songs have been played, the person that initially was in position i is in position P_i. Compute the array P_0,P_1,\dots, P_{3^N-1}.
Constraints
* 1 \le N \le 12
* 1 \le |T| \le 200,000
* T contains only the characters `S` and `R`.
Input
Input is given from Standard Input in the following format:
N
T
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Output
You should print on Standard Output:
P_0 P_1 \cdots P_{3^N-1}
Examples
Input
1
SRS
Output
2 0 1
Input
2
RRSRSSSSR
Output
3 8 1 0 5 7 6 2 4
Input
3
SRSRRSRRRSRRRR
Output
23 9 22 8 3 7 20 24 19 5 18 4 17 12 16 2 6 1 14 0 13 26 21 25 11 15 10 | instruction | 0 | 31,561 | 14 | 63,122 |
"Correct Solution:
```
n = int(input())
t = input()
new_pos = [0]
new_w = [0]*len(t)
for i in range(1, n+1):
ith_bit = [0]*(3**i) # ith_bit[p] : 位置 (p mod 3**i) のi番目bit
for k in range(3):
for l in range(3**(i-1)):
ith_bit[k*3**(i-1)+l] = k
pos = new_pos
w = new_w # 繰り上がりが起きても ith_bit を正確に捉えるため、j 曲流したあとの "222..22" の位置を把握しておく
q = 0
already = [0]*3**i
new_w = [0]*len(t)
for j in range(len(t)):
mark = w[j]
for k in range(3):
cand = mark + k*3**(i-1)
if ith_bit[cand] and (q - already[cand]) % 2:
# "122..22", "222..22" の最上位 bit のみ Salsa を流す
ith_bit[cand] = 3 - ith_bit[cand]
already[cand] = q # 位置 cand に何回 Salsa を流したか記憶しておく
if ith_bit[cand] == 2:
new_w[j] = cand
if t[j] == 'S':
q += 1
else:
for k in range(3):
ith_bit[mark + k*3**(i-1)] = (ith_bit[mark + k*3**(i-1)]+1) % 3
new_pos = [0]*(3**i)
for j in range(3**i):
if ith_bit[j] and (q - already[j]) % 2:
# 全ての位置に Salsa を流す。
# 曲の途中で "*22..22" が位置 j に訪れている場合、上で Salsa を流してしまっている。
# その分 already[j] を引く。
ith_bit[j] = 3-ith_bit[j]
new_pos[j] = pos[j % 3**(i-1)] + ith_bit[j]*3**(i-1)
print(*new_pos)
``` | output | 1 | 31,561 | 14 | 63,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.