message stringlengths 2 16.2k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 575 109k | cluster float64 16 16 | __index_level_0__ int64 1.15k 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,162 | 16 | 102,324 |
"Correct Solution:
```
#####segfunc#####
def segfunc(x, y):
if y[0]>x[0]:
return x
else:
return y
#################
#####ide_ele#####
ide_ele =(float("inf"),-1)
#################
class SegTree:
"""
init(init_val, ide_ele): 配列init_valで初期化 O(N)
update(k, x): k番目の値をxに更新 O(logN)
query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
"""
def __init__(self, init_val, segfunc, ide_ele):
"""
init_val: 配列の初期値
segfunc: 区間にしたい操作
ide_ele: 単位元
n: 要素数
num: n以上の最小の2のべき乗
tree: セグメント木(1-index)
"""
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
"""
k番目の値をxに更新
k: index(0-index)
x: update value
"""
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
"""
[l, r)のsegfuncしたものを得る
l: index(0-index)
r: index(0-index)
"""
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
import heapq
N=int(input())
p=list(map(int,input().split()))
n=N//2
op=[(p[2*i+1],2*i+1) for i in range(n)]
ep=[(p[2*i],2*i) for i in range(n)]
oseg=SegTree(op,segfunc,ide_ele)
eseg=SegTree(ep,segfunc,ide_ele)
def first(l,r):
if l>=r:
return (-1,-1,-1,-1)
if l%2==0:
val,index=eseg.query(l//2,r//2)
val2,index2=oseg.query(index//2,r//2)
return (val,val2,index,index2)
else:
val,index=oseg.query(l//2,r//2)
val2,index2=eseg.query(index//2+1,r//2+1)
return (val,val2,index,index2)
val,val2,index,index2=first(0,N)
que=[((val,val2),0,N)]
heapq.heapify(que)
ans=[]
while que:
tuple,l,r=heapq.heappop(que)
ans.append(tuple[0])
ans.append(tuple[1])
val,val2,index,index2=first(l,r)
val,val2,l1,r1=first(l,index)
if val!=-1:
heapq.heappush(que,((val,val2),l,index))
val,val2,l2,r2=first(index+1,index2)
if val!=-1:
heapq.heappush(que,((val,val2),index+1,index2))
val,val2,l3,r3=first(index2+1,r)
if val!=-1:
heapq.heappush(que,((val,val2),index2+1,r))
print(*ans)
``` | output | 1 | 51,162 | 16 | 102,325 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,163 | 16 | 102,326 |
"Correct Solution:
```
class segment_tree:
def __init__(self, N, operator_M, e_M):
self.op_M = operator_M
self.e_M = e_M
self.N0 = 1<<(N-1).bit_length()
self.dat = [self.e_M]*(2*self.N0)
# 長さNの配列 initial で初期化
def build(self, initial):
self.dat[self.N0:self.N0+len(initial)] = initial[:]
for k in range(self.N0-1,0,-1):
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
# a_k の値を x に更新
def update(self,k,x):
k += self.N0
self.dat[k] = x
k //= 2
while k:
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
k //= 2
# 区間[L,R]をopでまとめる
def query(self,L,R):
L += self.N0; R += self.N0 + 1
sl = sr = self.e_M
while L < R:
if R & 1:
R -= 1
sr = self.op_M(self.dat[R],sr)
if L & 1:
sl = self.op_M(sl,self.dat[L])
L += 1
L >>= 1; R >>= 1
return self.op_M(sl,sr)
def get(self, k): #k番目の値を取得。query[k,k]と同じ
return self.dat[k+self.N0]
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
sys.setrecursionlimit(10**5)
n,*p = map(int,read().split())
INF = 1<<30
p += [INF,INF]
def argmin(i,j):
if p[i] < p[j]: return i
else: return j
even = segment_tree(n//2+1,argmin,n)
odd = segment_tree(n//2+1,argmin,n+1)
even.build(range(0,n+2,2))
odd.build(range(1,n+2,2))
ans = [0]*n
def get(i,j):
return odd.query(i//2,(j-1)//2) if i%2 else even.query(i//2,(j-1)//2)
from heapq import *
k = get(0,n-1)
q = [(p[k],k,0,n-1)]
for I in range(n//2):
v,k,i,j = heappop(q)
l = even.query((k+1)//2,j//2) if i%2 else odd.query((k+1)//2,j//2)
#print(v,p[l])
ans[2*I] = v
ans[2*I+1] = p[l]
if i < k+1:
kk = get(i,k-1)
heappush(q,(p[kk],kk,i,k-1))
if k+1<l-1:
kk = get(k+1,l-1)
heappush(q,(p[kk],kk,k+1,l-1))
if l+1 < j:
kk = get(l+1,j)
heappush(q,(p[kk],kk,l+1,j))
print(*ans)
#x = merge3([[1,0],[4,0]],[[2,0]],[[3,0],[6,0]])
#print(x)
``` | output | 1 | 51,163 | 16 | 102,327 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,164 | 16 | 102,328 |
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
# O(NlogN)構築、クエリO(1)のRMQ
# 変更はできない
class SparseTable():
def __init__(self, N, A):
self.N = N
self.logN = N.bit_length()
self.A = A
self.table = [[i for i in range(N)]]
for k in range(self.logN):
tab = []
for i in range(self.N-(1<<(k+1))+1):
ind1 = self.table[-1][i]
ind2 = self.table[-1][i+(1<<k)]
if self.A[ind1] <= self.A[ind2]:
tab.append(ind1)
else:
tab.append(ind2)
self.table.append(tab)
# [l, r)のminの(val, key)
def query_min(self, l, r):
k = (r-l).bit_length()-1
indl = self.table[k][l]
indr = self.table[k][r-(1<<k)]
if self.A[indl] <= self.A[indr]:
return self.A[indl], indl
return self.A[indr], indr
import heapq as hp
N = int(input())
A = list(map(int, input().split()))
def main():
SP1 = SparseTable((N+1)//2, A[::2])
SP2 = SparseTable(N//2, A[1::2])
ans = []
q = []
v, k = SP1.query_min(0, N//2)
dic = {}
dic[v] = (k, 0, N//2, True)
hp.heappush(q, v)
for _ in range(N//2):
valuea = hp.heappop(q)
ka, l, r, is1 = dic[valuea]
ans.append(str(valuea))
if is1:
valueb, kb = SP2.query_min(ka, r)
if ka < kb:
m2, nk2 = SP2.query_min(ka, kb)
hp.heappush(q, m2)
dic[m2] = (nk2, ka, kb+1, False)
if l < ka:
m1, nk1 = SP1.query_min(l, ka)
hp.heappush(q, m1)
dic[m1] = (nk1, l, ka, True)
if kb+1 < r:
m3, nk3 = SP1.query_min(kb+1, r)
hp.heappush(q, m3)
dic[m3] = (nk3, kb+1, r, True)
else:
valueb, kb = SP1.query_min(ka+1, r)
if ka+1 < kb:
m1, nk1 = SP1.query_min(ka+1, kb)
hp.heappush(q, m1)
dic[m1] = (nk1, ka+1, kb, True)
if l < ka:
m2, nk2 = SP2.query_min(l, ka)
hp.heappush(q, m2)
dic[m2] = (nk2, l, ka+1, False)
if kb < r-1:
m3, nk3 = SP2.query_min(kb, r-1)
hp.heappush(q, m3)
dic[m3] = (nk3, kb, r, False)
ans.append(str(valueb))
print(" ".join(ans))
if __name__ == "__main__":
main()
``` | output | 1 | 51,164 | 16 | 102,329 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,165 | 16 | 102,330 |
"Correct Solution:
```
from heapq import heappop, heappush
import sys
sys.setrecursionlimit(10 ** 7)
input = sys.stdin.readline
n = int(input())
p = [int(x) for x in input().split()]
class SegmentTree: # 0-indexed
def __init__(self, array, operation=min, identity=10**30):
self.identity = identity
self.n = len(array)
self.N = 1 << (self.n - 1).bit_length()
self.tree = [self.identity] * 2 * self.N
self.opr = operation
for i in range(self.n):
self.tree[i+self.N-1] = array[i]
for i in range(self.N-2, -1, -1):
self.tree[i] = self.opr(self.tree[2*i+1], self.tree[2*i+2])
def values(self):
return self.tree[self.N-1:]
def update(self, k, x):
k += self.N-1
self.tree[k] = x
while k+1:
k = (k-1)//2
self.tree[k] = self.opr(self.tree[k*2+1], self.tree[k*2+2])
def query(self, p, q): # [p,q)
if q <= p:
print("Oops! That was no valid number. Try again...")
exit()
p += self.N-1
q += self.N-2
res = self.identity
while q-p > 1:
if p & 1 == 0:
res = self.opr(res, self.tree[p])
if q & 1 == 1:
res = self.opr(res, self.tree[q])
q -= 1
p = p//2
q = (q-1)//2
if p == q:
res = self.opr(res, self.tree[p])
else:
res = self.opr(self.opr(res, self.tree[p]), self.tree[q])
return res
ind = [0]*(n+1)
Odd = SegmentTree([10**30]*n)
Even = SegmentTree([10**30]*n)
for i in range(n):
ind[p[i]] = i
if i % 2 == 0:
Even.update(i, p[i])
else:
Odd.update(i, p[i])
cand = []
heappush(cand, (Even.query(0, n), 0, n, True))
q = []
while len(q) < n:
first, l, r, is_even = heappop(cand)
if is_even:
second = Odd.query(ind[first]+1, r)
q.extend([first, second])
if l < ind[first]:
heappush(cand, (Even.query(l, ind[first]), l, ind[first], True))
if ind[first] + 1 < ind[second]:
heappush(
cand, (Odd.query(ind[first]+1, ind[second]), ind[first]+1, ind[second], False))
if ind[second]+1 < r:
heappush(
cand, (Even.query(ind[second], r), ind[second]+1, r, True))
else:
second = Even.query(ind[first]+1, r)
q.extend([first, second])
if l < ind[first]:
heappush(cand, (Odd.query(l, ind[first]), l, ind[first], False))
if ind[first] + 1 < ind[second]:
heappush(
cand, (Even.query(ind[first]+1, ind[second]), ind[first]+1, ind[second], True))
if ind[second]+1 < r:
heappush(
cand, (Odd.query(ind[second], r), ind[second]+1, r, False))
print(*q)
``` | output | 1 | 51,165 | 16 | 102,331 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,166 | 16 | 102,332 |
"Correct Solution:
```
class SegTree:
def __init__(self, init_val, ide_ele, segfunc):
self.n = len(init_val)
self.num =2**(self.n-1).bit_length()
self.ide_ele = ide_ele
self.seg = [self.ide_ele]*2*self.num
self.segfunc = segfunc
#set_val
for i in range(self.n):
self.seg[i+self.num-1] = init_val[i]
#built
for i in range(self.num-2,-1,-1) :
self.seg[i] = segfunc(self.seg[2*i+1], self.seg[2*i+2])
def update(self, k, x):
k += self.num-1
self.seg[k] = x
while k+1:
k = (k-1)//2
self.seg[k] = self.segfunc(self.seg[k*2+1], self.seg[k*2+2])
def query(self, p, q):
if q<=p:
return self.ide_ele
p += self.num-1
q += self.num-2
res = self.ide_ele
while q-p>1:
if p&1 == 0:
res = self.segfunc(res, self.seg[p])
if q&1 == 1:
res = self.segfunc(res, self.seg[q])
q -= 1
p = p//2
q = (q-1)//2
if p == q:
res = self.segfunc(res, self.seg[p])
else:
res = self.segfunc(self.segfunc(res, self.seg[p]), self.seg[q])
return res
def main():
import sys
input = sys.stdin.readline
N = int(input())
P = list(map(int,input().split()))
Even = []
Odd = []
D = {}
for i in range(N//2):
e = P[2*i]
o = P[2*i+1]
D[e] = i
D[o] = i
Even.append(e)
Odd.append(o)
E_Seg = SegTree(Even,float("inf"),min)
O_Seg = SegTree(Odd,float("inf"),min)
import heapq
heap = []
# heapq.heappush(heap, item)
# heapq.heappop(heap)
def BFS(H):
L = H[0]
R = H[1]
if R <= L:
return -1,-1,-1,-1,-1
if L%2==0:
l = L//2
r = R//2
mini = E_Seg.query(l,r+1)
d_mini = D[mini]
mini_b = O_Seg.query(d_mini, r+1)
d_mini_b = D[mini_b]
leftH = (L, 2*d_mini-1)
centH = (2*d_mini+1, 2*d_mini_b)
rightH = (2*d_mini_b+2, R)
return mini, mini_b, leftH, centH, rightH
else:
l = L//2
r = R//2
mini = O_Seg.query(l, r)
d_mini = D[mini]
mini_b = E_Seg.query(d_mini+1, r+1)
d_mini_b = D[mini_b]
leftH = (L, 2*d_mini)
centH = (2*d_mini+2, 2*d_mini_b-1)
rightH = (2*d_mini_b+1, R)
return mini, mini_b, leftH, centH, rightH
H = (0, N-1)
m1,m2,LH,CH,RH = BFS(H)
#print(m1,m2)
heapq.heappush(heap, [m1,m2,LH,CH,RH])
Q = []
while heap != []:
m1,m2,LH,CH,RH = heapq.heappop(heap)
Q += [m1,m2]
m1L,m2L,LHL,CHL,RHL = BFS(LH)
if m1L != -1:
heapq.heappush(heap, [m1L,m2L,LHL,CHL,RHL])
m1C,m2C,LHC,CHC,RHC = BFS(CH)
if m1C != -1:
heapq.heappush(heap, [m1C,m2C,LHC,CHC,RHC])
m1R,m2R,LHR,CHR,RHR = BFS(RH)
if m1R != -1:
heapq.heappush(heap, [m1R,m2R,LHR,CHR,RHR])
print(*Q)
main()
``` | output | 1 | 51,166 | 16 | 102,333 |
Provide a correct Python 3 solution for this coding contest problem.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5 | instruction | 0 | 51,167 | 16 | 102,334 |
"Correct Solution:
```
def main():
n = int(input())
p = list(map(lambda x: int(x)-1, input().split()))
pos = [j for i, j in sorted([(j, i) for i, j in enumerate(p)])]
basesize = n >> 1
num = 1
while num < basesize:
num *= 2
num -= 1
tree_even = [100001]*(num*2+1)
tree_odd = [100001]*(num*2+1)
for i in range(num, num+basesize):
tree_even[i] = p[(i-num)*2]
for i in range(num-1, -1, -1):
tree_even[i] = min(tree_even[2*i+1:2*i+3])
for i in range(num, num+basesize):
tree_odd[i] = p[(i-num)*2+1]
for i in range(num-1, -1, -1):
tree_odd[i] = min(tree_odd[2*i+1:2*i+3])
g = dict()
d = dict()
q = [n-1]
qap, qp = q.append, q.pop
while q:
t = qp()
m, M = t//n, t % n
if m+1 == M:
d[t] = p[m]*n+p[M]
continue
g[t] = []
gap = g[t].append
if m % 2 == 0:
i1, j1 = m >> 1, (M >> 1)+1
even = 200000
l, r = i1+num, j1+num
while l < r:
if r % 2 == 0:
r -= 1
even = min(even, tree_even[r])
if l % 2 == 0:
even = min(even, tree_even[l])
l += 1
l >>= 1
r >>= 1
even_idx = pos[even]
odd = 200000
l, r = (even_idx >> 1)+num, j1+num
while l < r:
if r % 2 == 0:
r -= 1
odd = min(odd, tree_odd[r])
if l % 2 == 0:
odd = min(odd, tree_odd[l])
l += 1
l >>= 1
r >>= 1
odd_idx = pos[odd]
d[t] = even*n+odd
if m != even_idx:
s = m*n+even_idx-1
qap(s)
gap(s)
if M != odd_idx:
s = (odd_idx+1)*n+M
qap(s)
gap(s)
if even_idx+1 != odd_idx:
s = (even_idx+1)*n+odd_idx-1
qap(s)
gap(s)
else:
i1, j1 = m >> 1, M >> 1
odd = 200000
l, r = i1+num, j1+num
while l < r:
if r % 2 == 0:
r -= 1
odd = min(odd, tree_odd[r])
if l % 2 == 0:
odd = min(odd, tree_odd[l])
l += 1
l >>= 1
r >>= 1
odd_idx = pos[odd]
even = 200000
l, r = (odd_idx >> 1)+1+num, j1+1+num
while l < r:
if r % 2 == 0:
r -= 1
even = min(even, tree_even[r])
if l % 2 == 0:
even = min(even, tree_even[l])
l += 1
l >>= 1
r >>= 1
even_idx = pos[even]
d[t] = odd*n+even
if m != odd_idx:
s = m*n+odd_idx-1
qap(s)
gap(s)
if M != even_idx:
s = (even_idx+1)*n+M
qap(s)
gap(s)
if odd_idx+1 != even_idx:
s = (odd_idx+1)*n+even_idx-1
qap(s)
gap(s)
g2 = dict()
for i, t in g.items():
k = d[i]
g2[k] = []
ga = g2[k].append
for j in t:
ga(d[j])
import heapq
h = [d[n-1]]
heapq.heapify(h)
ans = []
hpop = heapq.heappop
hpush = heapq.heappush
while h:
t = hpop(h)
ans += [t//n+1, t % n+1]
if t in g2:
for s in g2[t]:
hpush(h, s)
print(*ans)
main()
``` | output | 1 | 51,167 | 16 | 102,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
import sys
input = sys.stdin.readline
# O(NlogN)構築、クエリO(1)のRMQ
# 変更はできない
class SparseTable():
def __init__(self, N, A):
self.N = N
self.logN = N.bit_length()
self.A = A
self.table = [[i for i in range(N)]]
for k in range(self.logN):
tab = []
for i in range(self.N-(1<<(k+1))+1):
ind1 = self.table[-1][i]
ind2 = self.table[-1][i+(1<<k)]
if self.A[ind1] <= self.A[ind2]:
tab.append(ind1)
else:
tab.append(ind2)
self.table.append(tab)
# [l, r)のminの(val, key)
def query_min(self, l, r):
k = (r-l).bit_length()-1
indl = self.table[k][l]
indr = self.table[k][r-(1<<k)]
if self.A[indl] <= self.A[indr]:
return self.A[indl], indl
return self.A[indr], indr
import heapq as hp
N = int(input())
A = list(map(int, input().split()))
def main():
SP1 = SparseTable((N+1)//2, A[::2])
SP2 = SparseTable(N//2, A[1::2])
ans = []
q = []
v, k = SP1.query_min(0, N//2)
dic = {}
dic[v] = (k, 0, N//2, True)
hp.heappush(q, v)
for _ in range(N//2):
valuea = hp.heappop(q)
ka, l, r, is1 = dic[valuea]
ans.append(str(valuea))
if is1:
valueb, kb = SP2.query_min(ka, r)
if ka < kb:
m2, nk2 = SP2.query_min(ka, kb)
hp.heappush(q, m2)
dic[m2] = (nk2, ka, kb+1, False)
if l < ka:
m1, nk1 = SP1.query_min(l, ka)
hp.heappush(q, m1)
dic[m1] = (nk1, l, ka, True)
if kb+1 < r:
m3, nk3 = SP1.query_min(kb+1, r)
hp.heappush(q, m3)
dic[m3] = (nk3, kb+1, r, True)
else:
valueb, kb = SP1.query_min(ka+1, r)
if ka+1 < kb:
m1, nk1 = SP1.query_min(ka+1, kb)
hp.heappush(q, m1)
dic[m1] = (nk1, ka+1, kb, True)
if l < ka:
m2, nk2 = SP2.query_min(l, ka)
hp.heappush(q, m2)
dic[m2] = (nk2, l, ka+1, False)
if kb < r-1:
m3, nk3 = SP2.query_min(kb, r-1)
hp.heappush(q, m3)
dic[m3] = (nk3, kb, r, False)
ans.append(str(valueb))
print(" ".join(ans))
if __name__ == "__main__":
main()
``` | instruction | 0 | 51,168 | 16 | 102,336 |
Yes | output | 1 | 51,168 | 16 | 102,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
from pprint import pprint
from copy import deepcopy
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
from pprint import pprint
sys.setrecursionlimit(2147483647)
INF = 1 << 32
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007
class Segtree:
def __init__(self, A, ide_ele, segfunc, initialize=True):
self.n = len(A)
self.size = 2 ** (self.n - 1).bit_length()
self.ide_ele = ide_ele
self.segfunc = segfunc
if initialize:
self.data = [ide_ele] * self.size + A + [ide_ele] * (self.size - self.n)
for i in range(self.size - 1, 0, -1):
self.data[i] = self.segfunc(self.data[2 * i], self.data[2 * i + 1])
else:
self.data = [ide_ele] * (2 * self.size)
def update(self, k, x):
k += self.size
self.data[k] = x
while k > 0:
k = k >> 1
self.data[k] = self.segfunc(self.data[2 * k], self.data[2 * k + 1])
def query(self, l, r):
L, R = l + self.size, r + self.size
s = self.ide_ele
while L < R:
if R & 1:
R -= 1
s = self.segfunc(s, self.data[R])
if L & 1:
s = self.segfunc(s, self.data[L])
L += 1
L >>= 1
R >>= 1
return s
n = I()
P = LI()
D = {P[i]: i for i in range(n)}
p_even = [P[i] if not i & 1 else INF for i in range(n)]
p_odd = [P[i] if i & 1 else INF for i in range(n)]
st_even = Segtree(p_even, INF, min)
st_odd = Segtree(p_odd, INF, min)
hq = [(st_even.query(0, n), 0, n)]
ans = []
for _ in range(n // 2):
v1, l, r = heappop(hq)
p1 = D[v1]
if not l & 1:
st1, st2 = st_odd, st_even
else:
st1, st2 = st_even, st_odd
v2 = st1.query(p1, r)
p2 = D[v2]
st2.update(p1, INF)
st1.update(p2, INF)
if l != p1:
heappush(hq, (st2.query(l, p1), l, p1))
if p1 + 1 != p2:
heappush(hq, (st1.query(p1 + 1, p2), p1 + 1, p2))
if p2 + 1 != r:
heappush(hq, (st2.query(p2 + 1, r), p2 + 1, r))
ans += [v1, v2]
print(*ans)
``` | instruction | 0 | 51,169 | 16 | 102,338 |
Yes | output | 1 | 51,169 | 16 | 102,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
from heapq import heappop, heappush
n = int(input())
p = [int(x) for x in input().split()]
class SegmentTree: # 0-indexed
def __init__(self, array, operation=min, identity=10**30):
self.identity = identity
self.n = len(array)
self.N = 1 << (self.n - 1).bit_length()
self.tree = [self.identity] * 2 * self.N
self.opr = operation
for i in range(self.n):
self.tree[i+self.N-1] = array[i]
for i in range(self.N-2, -1, -1):
self.tree[i] = self.opr(self.tree[2*i+1], self.tree[2*i+2])
def values(self):
return self.tree[self.N-1:]
def update(self, k, x):
k += self.N-1
self.tree[k] = x
while k+1:
k = (k-1)//2
self.tree[k] = self.opr(self.tree[k*2+1], self.tree[k*2+2])
def query(self, p, q): # [p,q)
if q <= p:
print("Oops! That was no valid number. Try again...")
exit()
p += self.N-1
q += self.N-2
res = self.identity
while q-p > 1:
if p & 1 == 0:
res = self.opr(res, self.tree[p])
if q & 1 == 1:
res = self.opr(res, self.tree[q])
q -= 1
p = p//2
q = (q-1)//2
if p == q:
res = self.opr(res, self.tree[p])
else:
res = self.opr(self.opr(res, self.tree[p]), self.tree[q])
return res
ind = [0]*(n+1)
Odd = SegmentTree([10**30]*n)
Even = SegmentTree([10**30]*n)
for i in range(n):
ind[p[i]] = i
if i % 2 == 0:
Even.update(i, p[i])
else:
Odd.update(i, p[i])
cand = []
heappush(cand, (Even.query(0, n), 0, n, True))
q = []
for _ in range(n//2):
first, l, r, is_even = heappop(cand)
if is_even:
second = Odd.query(ind[first]+1, r)
q.extend([first, second])
if l < ind[first]:
heappush(cand, (Even.query(l, ind[first]), l, ind[first], True))
if ind[first] + 1 < ind[second]:
heappush(
cand, (Odd.query(ind[first]+1, ind[second]), ind[first]+1, ind[second], False))
if ind[second]+1 < r:
heappush(
cand, (Even.query(ind[second], r), ind[second]+1, r, True))
else:
second = Even.query(ind[first]+1, r)
q.extend([first, second])
if l < ind[first]:
heappush(cand, (Odd.query(l, ind[first]), l, ind[first], False))
if ind[first] + 1 < ind[second]:
heappush(
cand, (Even.query(ind[first]+1, ind[second]), ind[first]+1, ind[second], True))
if ind[second]+1 < r:
heappush(
cand, (Odd.query(ind[second], r), ind[second]+1, r, False))
print(*q)
``` | instruction | 0 | 51,170 | 16 | 102,340 |
Yes | output | 1 | 51,170 | 16 | 102,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
import sys
from heapq import heappop, heappush
class SegTreeMin:
"""
以下のクエリを処理する
1.update: i番目の値をxに更新する
2.get_min: 区間[l, r)の最小値を得る
"""
def __init__(self, n, INF):
"""
:param n: 要素数
:param INF: 初期値(入りうる要素より十分に大きな数)
"""
n2 = 1 << (n - 1).bit_length()
self.offset = n2
self.tree = [INF] * (n2 << 1)
self.INF = INF
@classmethod
def from_array(cls, arr, INF):
ins = cls(len(arr), INF)
ins.tree[ins.offset:ins.offset + len(arr)] = arr
for i in range(ins.offset - 1, 0, -1):
l = i << 1
r = l + 1
ins.tree[i] = min(ins.tree[l], ins.tree[r])
return ins
def update(self, i, x):
"""
i番目の値をxに更新
:param i: index(0-indexed)
:param x: update value
"""
i += self.offset
self.tree[i] = x
while i > 1:
y = self.tree[i ^ 1]
if y <= x:
break
i >>= 1
self.tree[i] = x
def get_min(self, a, b):
"""
[a, b)の最小値を得る
:param a: index(0-indexed)
:param b: index(0-indexed)
"""
result = self.INF
l = a + self.offset
r = b + self.offset
while l < r:
if r & 1:
result = min(result, self.tree[r - 1])
if l & 1:
result = min(result, self.tree[l])
l += 1
l >>= 1
r >>= 1
return result
n, *ppp = map(int, sys.stdin.buffer.read().split())
INF = 10 ** 18
sgt0 = SegTreeMin.from_array([(p if i % 2 == 0 else INF, i) for i, p in enumerate(ppp)], (INF, -1))
sgt1 = SegTreeMin.from_array([(p if i % 2 == 1 else INF, i) for i, p in enumerate(ppp)], (INF, -1))
sgt = [sgt0, sgt1]
ans = []
heap = []
first_p, i = sgt0.get_min(0, n)
first_q, j = sgt1.get_min(i, n)
heap.append((first_p, first_q, 0, n, i, j))
while heap:
p, q, l, r, i, j = heappop(heap)
ans.append(p)
ans.append(q)
if l < i:
k = l % 2
np, ni = sgt[k].get_min(l, i)
nq, nj = sgt[k ^ 1].get_min(ni, i)
heappush(heap, (np, nq, l, i, ni, nj))
if i + 1 < j:
k = (i + 1) % 2
np, ni = sgt[k].get_min(i + 1, j)
nq, nj = sgt[k ^ 1].get_min(ni, j)
heappush(heap, (np, nq, i + 1, j, ni, nj))
if j + 1 < r:
k = (j + 1) % 2
np, ni = sgt[k].get_min(j + 1, r)
nq, nj = sgt[k ^ 1].get_min(ni, r)
heappush(heap, (np, nq, j + 1, r, ni, nj))
print(*ans)
``` | instruction | 0 | 51,171 | 16 | 102,342 |
Yes | output | 1 | 51,171 | 16 | 102,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
# seishin.py
N = int(input())
*P, = map(int, input().split())
M = [0]*(N+1)
for i, p in enumerate(P):
M[p] = i
INF = 10**9
def init(P, n):
n0 = 2 ** (n-1).bit_length()
data = [INF]*(n0*2)
data[n0-1:n0+n-1] = P
for i in range(n0-2, -1, -1):
data[i] = min(data[2*i+1], data[2*i+2])
return data
def __get(data, a, b, k, l, r):
if a <= l and r <= b:
return data[k]
if b <= l or r <= a:
return INF
vl = __get(data, a, b, 2*k+1, l, (l+r)//2)
vr = __get(data, a, b, 2*k+2, (l+r)//2, r)
return min(vl, vr)
def get(data, l, r):
return __get(data, l, r, 0, 0, len(data)//2)
d0 = init(P[0::2], N//2)
d1 = init(P[1::2], N//2)
def query_x(l, r):
if l % 2 == 0:
x = get(d0, l//2, r//2)
else:
x = get(d1, l//2, r//2)
return x
def query_y(l, r):
if l % 2 == 0:
y = get(d1, l//2, r//2)
else:
y = get(d0, (l+1)//2, (r+1)//2)
return y
from heapq import heappush, heappop
que = [(query_x(0, N), 0, N)]
ans = []
while que:
x, l, r = heappop(que)
if l+2 < r:
xi = M[x]
y = query_y(xi, r)
yi = M[y]
# [l, xi)
if l < xi:
heappush(que, (query_x(l, xi), l, xi))
# [xi+1, yi)
if xi+1 < yi:
heappush(que, (query_x(xi+1, yi), xi+1, yi))
# [yi+1, r)
if yi+1 < r:
heappush(que, (query_x(yi+1, r), yi+1, r))
else:
y = P[r-1]
ans.append("%d %d" % (x, y))
print(*ans)
``` | instruction | 0 | 51,172 | 16 | 102,344 |
No | output | 1 | 51,172 | 16 | 102,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
"""
https://atcoder.jp/contests/arc080/tasks/arc080_c
まず、辞書順最小なので一番左にできる要素はどれか考える
ABCD
→可能なのは A,C
→偶数番目だけ?(0 indexedで)
→右に奇数個・左に偶数個ある場合しか先頭にはなれないので正しそう
次に、2番目になる要素はどれか?
→一番目より左は確定
→奇数個並んでる場合、最後に残せるやつ
ABCDEだと
→A,C,E なので奇数番目だけ
3番目の要素は?
→偶数番目から自由に選べる
4番目は?
→最後に選んだ偶数番目から右に探索して、探索済みが出てくるまでに当たる奇数番目のうち最小
あとは高速化だ!
分割統治
偶奇分けて最小と最大2つのRMQを出せるようにしとく
→めんどすぎ!!!
偶数番目と奇数番目・最小で2つのセグ木
偶数番目から最小を選ぶ(X)
→それより右の奇数番目から最小を選ぶ(Y)
その左側、真ん中、右側を分けておなじことをする
(X,Y),3つの部分を小さいほうからどん欲にとってマージした奴
をreturnする
SPTを使えば早いか
maxは-1をかけて出せばいいや
======ちょっと答えを見た======
マージ部分がやばい?
親が選択されるまで子は選択できない
優先度付きキューで管理か
親を処理した時点で子を優先度付きキューに入れるのか
(左値,右値,左index,右index,L,R)を入れればいいか
"""
import sys
import heapq
def make_ST(n,first): #firstで初期化された、葉がn要素を超えるように2のべき乗個用意されたリストを返す
i = 0
ret = []
while 2 ** (i-1) < n:
for j in range(2 ** i):
ret.append(first)
i += 1
return ret
def RMQ_update_point(num,point,tree): #葉のindex(0-origin)がpointの要素をnumにする/treeはセグ木
i = (len(tree) - 1) // 2 + point
tree[i] = num
while i > 0:
i = (i - 1) // 2
tree[i] = min(tree[i * 2 + 2] , tree[i * 2 + 1])
return
def RMQ_query(a,b,k,l,r,tree): #query区間左,右,注目ノード番号,担当範囲左,担当範囲右,木
if r <= a or b <= l: #区間が完全にかぶらない場合inf
return (float("inf"),float("inf"))
if a <= l and r <= b: #区間が完全に含まれる場合自分
return tree[k]
c1 = RMQ_query(a,b,2*k+1,l,(l+r)//2,tree)
c2 = RMQ_query(a,b,2*k+2,(l+r)//2,r,tree)
return min(c1,c2)
def want(L,R):
if L >= R:
return
elif L + 1 == R:
heapq.heappush( q, (p[L],p[R],float("inf"),float("-inf"),float("inf"),float("-inf")) )
return
if L % 2 == 0:
nx,xind = RMQ_query(L,R+1,0,0,(len(emin)+1)//2,emin)
ny,yind = RMQ_query(xind+1,R+1,0,0,(len(omin)+1)//2,omin)
else:
nx,xind = RMQ_query(L,R+1,0,0,(len(omin)+1)//2,omin)
ny,yind = RMQ_query(xind+1,R+1,0,0,(len(emin)+1)//2,emin)
#print (L,R,xind,yind)
heapq.heappush( q , (nx,ny,xind,yind,L,R) )
return
N = int(input())
p = list(map(int,input().split()))
omin = make_ST(N, (float("inf") , float("inf")) )
emin = make_ST(N, (float("inf") , float("inf")) )
for i in range(N):
if i % 2 == 0:
RMQ_update_point( (p[i],i) ,i,emin)
else:
RMQ_update_point( (p[i],i) ,i,omin)
q = []
want(0,N-1)
ans = []
while len(q) > 0:
x,y,xi,yi,NL,NR = heapq.heappop(q)
ans.append(x)
ans.append(y)
want(NL,xi-1)
want(xi+1,yi-1)
want(yi+1,NR)
print (*ans)
``` | instruction | 0 | 51,173 | 16 | 102,346 |
No | output | 1 | 51,173 | 16 | 102,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
"""
https://atcoder.jp/contests/arc080/tasks/arc080_c
まず、辞書順最小なので一番左にできる要素はどれか考える
ABCD
→可能なのは A,C
→偶数番目だけ?(0 indexedで)
→右に奇数個・左に偶数個ある場合しか先頭にはなれないので正しそう
次に、2番目になる要素はどれか?
→一番目より左は確定
→奇数個並んでる場合、最後に残せるやつ
ABCDEだと
→A,C,E なので奇数番目だけ
3番目の要素は?
→偶数番目から自由に選べる
4番目は?
→最後に選んだ偶数番目から右に探索して、探索済みが出てくるまでに当たる奇数番目のうち最小
あとは高速化だ!
分割統治
偶奇分けて最小と最大2つのRMQを出せるようにしとく
→めんどすぎ!!!
偶数番目と奇数番目・最小で2つのセグ木
偶数番目から最小を選ぶ(X)
→それより右の奇数番目から最小を選ぶ(Y)
その左側、真ん中、右側を分けておなじことをする
(X,Y),3つの部分を小さいほうからどん欲にとってマージした奴
をreturnする
SPTを使えば早いか
maxは-1をかけて出せばいいや
======ちょっと答えを見た======
マージ部分がやばい?
親が選択されるまで子は選択できない
優先度付きキューで管理か
親を処理した時点で子を優先度付きキューに入れるのか
(左値,右値,左index,右index,L,R)を入れればいいか
"""
import sys
import heapq
sys.setrecursionlimit(200001)
#RMQ用のSparseTableを作成
import math
def make_SparseTable(lis):
spt_len = 0
while spt_len ** 2 <= len(lis):
spt_len += 1
spt_len += 5
N = len(lis)
ret = [[float("inf")] * spt_len for i in range(N)]
for i in range(N):
ret[i][0] = lis[i]
for j in range(spt_len-1):
j += 1
for i in range(N):
if i + 2**(j-1) < N:
ret[i][j] = min(ret[i][j-1] , ret[i+2**(j-1)][j-1])
else:
ret[i][j] = ret[i][j-1]
return ret
#[a,b]の最小値を求める
def RMQ_SPT(a,b,spt):
if a == b:
return (p[a],a)
qlen = b-a+1
ind = int(math.log(qlen,2))
#print (a,b,ind,b-2**ind+1)
return min(spt[a][ind] , spt[b-2**ind+1][ind])
def want(L,R):
if L >= R:
return
elif L + 1 == R:
heapq.heappush( q, (p[L],p[R],float("inf"),float("-inf"),float("inf"),float("-inf")) )
return
if L % 2 == 0:
nx,xind = RMQ_SPT(L,R,emin)
ny,yind = RMQ_SPT(xind+1,R,omin)
else:
nx,xind = RMQ_SPT(L,R,omin)
ny,yind = RMQ_SPT(xind+1,R,emin)
#print (L,R,xind,yind)
heapq.heappush( q , (nx,ny,xind,yind,L,R) )
return
N = int(input())
p = list(map(int,input().split()))
ominL = []
eminL = []
for i in range(N):
if i % 2 == 0:
ominL.append( (float("inf"),i) )
eminL.append( ( p[i] , i ) )
else:
eminL.append( (float("inf"),i) )
ominL.append( ( p[i] , i ) )
emin = make_SparseTable(eminL)
omin = make_SparseTable(ominL)
q = []
want(0,N-1)
ans = []
while len(q) > 0:
x,y,xi,yi,NL,NR = heapq.heappop(q)
ans.append(x)
ans.append(y)
want(NL,xi-1)
want(xi+1,yi-1)
want(yi+1,NR)
print (*ans)
``` | instruction | 0 | 51,174 | 16 | 102,348 |
No | output | 1 | 51,174 | 16 | 102,349 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be a positive even number.
We have a permutation of (1, 2, ..., N), p = (p_1, p_2, ..., p_N). Snuke is constructing another permutation of (1, 2, ..., N), q, following the procedure below.
First, let q be an empty sequence. Then, perform the following operation until p becomes empty:
* Select two adjacent elements in p, and call them x and y in order. Remove x and y from p (reducing the length of p by 2), and insert x and y, preserving the original order, at the beginning of q.
When p becomes empty, q will be a permutation of (1, 2, ..., N).
Find the lexicographically smallest permutation that can be obtained as q.
Constraints
* N is an even number.
* 2 ≤ N ≤ 2 × 10^5
* p is a permutation of (1, 2, ..., N).
Input
Input is given from Standard Input in the following format:
N
p_1 p_2 ... p_N
Output
Print the lexicographically smallest permutation, with spaces in between.
Examples
Input
4
3 2 4 1
Output
3 1 2 4
Input
2
1 2
Output
1 2
Input
8
4 6 3 2 8 5 7 1
Output
3 1 2 7 4 6 8 5
Submitted Solution:
```
import heapq
MAX_N = 1 << 17
INT_MAX = 2**31 - 1
class SegmentTree():
def __init__(self, n_):
self.n = 1
while self.n < n_:
self.n *= 2
self.dat = [INT_MAX] * (2 * self.n - 1)
def update(self, k, a):
k += self.n - 1
self.dat[k] = a
while k > 0:
k = int((k - 1) / 2)
self.dat[k] = min(self.dat[k * 2 + 1], self.dat[k * 2 + 2])
def query(self, a, b, k, l, r):
if (r <= a) or (b <= l):
return INT_MAX
if (a <= l) and (r <= b):
return self.dat[k]
else:
vl = self.query(a, b, k * 2 + 1, l, (l + r) / 2)
vr = self.query(a, b, k * 2 + 2, (l + r) / 2, r)
return min([vl, vr])
def wrap_query(type, a, b, k, l, r):
if type == "even":
if a % 2 == 0:
ret = st_even.query(a, b, k, l, r)
else:
ret = st_odd.query(a, b, k, l, r)
else:
if a % 2 == 0:
ret = st_odd.query(a, b, k, l, r)
else:
ret = st_even.query(a, b, k, l, r)
return ret
class Item():
def __init__(self, mini, left, right):
self.mini = mini
self.left = left
self.right = right
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().split(" ")))
st_even = SegmentTree(n)
st_odd = SegmentTree(n)
h = dict()
for i in range(n):
h[arr[i]] = i
if i % 2 == 0:
st_even.update(i, arr[i])
else:
st_odd.update(i, arr[i])
q = []
hq = []
x = wrap_query("even", 0, n, 0, 0, n)
heapq.heappush(hq, (x, Item(h[x], 0, n)))
while len(hq) != 0:
q0, item = heapq.heappop(hq)
l = item.left
r = item.right
i = item.mini
q.append(q0)
q1 = wrap_query("odd", i, r, 0, 0, n)
j = h[q1]
q.append(q1)
if i - l > 1:
x0 = wrap_query("even", l, i, 0, 0, n)
heapq.heappush(hq, (x0, Item(h[x0], l, i)))
if j - (i+1) > 1:
x1 = wrap_query("even", i+1, j, 0, 0, n)
heapq.heappush(hq, (x1, Item(h[x1], i+1, j)))
if r - (j + 1) > 1:
x2 = wrap_query("even", j+1, r, 0, 0, n)
heapq.heappush(hq, (x2, Item(h[x2], j+1, r)))
print(" ".join(map(str, q)))
``` | instruction | 0 | 51,175 | 16 | 102,350 |
No | output | 1 | 51,175 | 16 | 102,351 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,176 | 16 | 102,352 |
"Correct Solution:
```
n = int(input())
s = input()
def check(ox, l, m, r):
if l == r:
if (m == 'S' and ox == 'o') or (m == 'W' and ox == 'x'):
return True
else:
return False
else:
return not check(ox, l, m, l)
for one in 'SW':
for two in 'SW':
a = one + two
for i in range(2, n):
if check(s[i-1], a[i-2], a[i-1], 'S'):
a += 'S'
else:
a += 'W'
if check(s[n-1], a[n-2], a[n-1], a[0]) and check(s[0], a[n-1], a[0], a[1]):
print(a)
exit()
print(-1)
``` | output | 1 | 51,176 | 16 | 102,353 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,177 | 16 | 102,354 |
"Correct Solution:
```
import sys
N = int(input())
s = input()
List = [['S','S'], ['S','W'], ['W','S'], ['W','W']]
for i in range(4):
ans = List[i]
for i in range(1,N):
if i != N-1:
if (ans[i-1] == ans[i] and s[i] == 'o') or (ans[i-1] != ans[i] and s[i] == 'x'):
ans.append('S')
else:
ans.append('W')
else:
if ((((ans[N-1] == 'S' and s[N-1] == 'o') or (ans[N-1] == 'W' and s[N-1] == 'x')) and (ans[N-2] == ans[0])) or (((ans[N-1] == 'S' and s[N-1] == 'x') or (ans[N-1] == 'W' and s[N-1] == 'o')) and (ans[N-2] != ans[0]))) and ((((ans[0] == 'S' and s[0] == 'o') or (ans[0] == 'W' and s[0] == 'x')) and (ans[N-1] == ans[1])) or (((ans[0] == 'S' and s[0] == 'x') or (ans[0] == 'W' and s[0] == 'o')) and (ans[N-1] != ans[1]))):
print(''.join(ans))
sys.exit()
print(-1)
``` | output | 1 | 51,177 | 16 | 102,355 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,178 | 16 | 102,356 |
"Correct Solution:
```
N = int(input())
s = input()
def check_truth(a_0, a_1):
a = [True for i in range(N)] # True: Sheep, False: Wolf
a[0] = a_0
a[-1] = a_1
for i in range(N):
if a[i]:
if s[i] == 'o':
a[(i+1)%N] = a[i-1]
else:
a[(i+1)%N] = not a[i-1]
else:
if s[i] == 'o':
a[(i+1)%N] = not a[i-1]
else:
a[(i+1)%N] = a[i-1]
if a[0] != a_0 or a[-1] != a_1:
return -1
else:
return a
p = [True, False]
for i in range(2):
for j in range(2):
ans = check_truth(p[i], p[j])
if ans != -1:
for k in range(N):
if ans[k]:
print('S', end='')
else:
print('W', end='')
print()
exit()
print(-1)
``` | output | 1 | 51,178 | 16 | 102,357 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,179 | 16 | 102,358 |
"Correct Solution:
```
import itertools
n = int(input())
s = input()
t = [''] * n
for p in itertools.product(['o', 'x'], repeat=2):
t[-1] = p[0]
t[0] = p[1]
for i in range(1, n - 1):
if (t[i - 2] + t[i - 1] + s[i - 1]).count('x') % 2 == 0:
t[i] = 'o'
else:
t[i] = 'x'
if (t[-3] + t[-2] + t[-1] + s[-2]).count('x') % 2 == 0 and (t[-2] + t[-1] + t[0] + s[-1]).count('x') % 2 == 0:
ans = []
for c in t:
if c == 'o':
ans.append('S')
else:
ans.append('W')
print(*ans, sep='')
break
else:
print(-1)
``` | output | 1 | 51,179 | 16 | 102,359 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,180 | 16 | 102,360 |
"Correct Solution:
```
N = int(input())
s = input()
def fnc(x1, x2):
pre = x1 # s[-1] の仮定
curr = x2 # s[0] の仮定
ans = []
for i in range(N):
if curr == 1: # 羊
if s[i] == 'o':
nv = pre
else:
nv = (pre + 1) % 2
else: # 狼
if s[i] == 'x':
nv = pre
else:
nv = (pre + 1) % 2
pre = curr
curr = nv
ans.append(pre)
if pre == x1 and curr == x2:
return ans
else:
return None
def solve():
for i in [1, 0]:
for j in [1, 0]:
ans = fnc(i, j)
if ans:
return ans
return None
if __name__ == '__main__':
ans = solve()
if not ans:
print(-1)
exit()
for a in ans:
print('S' if a else 'W', end='')
print()
``` | output | 1 | 51,180 | 16 | 102,361 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,181 | 16 | 102,362 |
"Correct Solution:
```
N = int(input())
s = input()
def calcnext(a, b, c):
if b == "W":
c = "x" if c == "o" else "o"
n = a if c == "o" else "S" if a == "W" else "W"
return n
for ab in ["SS", "SW", "WS", "WW"]:
l = list(ab)
for i in range(2, N+2):
n = calcnext(l[i-2], l[i-1], s[(i-1)%N])
l.append(n)
#print(l)
if l[N:N+2] == l[0:2]:
print("".join(l[:N]))
exit()
print(-1)
``` | output | 1 | 51,181 | 16 | 102,363 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,182 | 16 | 102,364 |
"Correct Solution:
```
n=int(input())
s=input()
ss="SS"
sw="SW"
ws="WS"
ww="WW"
def f(t,c):
if t=="o":
if c[-2:]=="SS" or c[-2:]=="WW":
return c+"S"
else:
return c+"W"
else:
if c[-2:]=="SW" or c[-2:]=="WS":
return c+"S"
else:
return c+"W"
for i in s[1:n-1]:
ss=f(i,ss)
sw=f(i,sw)
ws=f(i,ws)
ww=f(i,ww)
def a(s,c):
if f(s[-1],c[-2:])[2]!=c[0]:
return 0
if f(s[0],c[-1]+c[0])[2]!=c[1]:
return 0
return 1
for i in [ss,sw,ws,ww]:
if a(s,i):
print(i)
break
else:
print(-1)
``` | output | 1 | 51,182 | 16 | 102,365 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS | instruction | 0 | 51,183 | 16 | 102,366 |
"Correct Solution:
```
n=int(input())
s=input()
ch=['S','W']
for c1 in range(2):
for c0 in range(2):
if (ch[c1]=='S' and s[1]=='o') or (ch[c1]=='W' and s[1]=='x'):
ans=ch[c0]+ch[c1]+ch[c0]
else:
ans=ch[c0]+ch[c1]+ch[(c0+1)%2]
i=2
while i<n-1:
if (ans[-1]=='S' and s[i]=='o') or (ans[-1]=='W' and s[i]=='x'):
ans+=ans[-2]
else:
ans+='W' if ans[-2]=='S' else 'S'
i+=1
for i in range(n):
bc=ans[(i-1+n)%n]
ac=ans[(i+1)%n]
if (ans[i]=='S' and s[i]=='o') or (ans[i]=='W' and s[i]=='x'):
if bc!=ac:
break
else:
if bc==ac:
break
else:
print(ans)
exit(0)
print(-1)
``` | output | 1 | 51,183 | 16 | 102,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
def d_menagerie(N, S):
s = S + S[0:2] # 円環状に並んでいることを考慮
for ans in ['SS', 'SW', 'WS', 'WW']: # Sは羊、Wは狼。1番と2番の種類を仮定する
for i in range(1, N + 1):
if (ans[-1] == 'S' and s[i] == 'o') or (ans[-1] == 'W' and s[i] == 'x'):
# この場合、今注目している動物の両隣は同じ種類。
# よって、今注目している動物の右隣を左隣と同じにする。
ans += ans[-2]
else:
# 両隣は違う種類。右隣を左隣と逆にする。
ans += ('S' if ans[-2] == 'W' else 'W')
if ans[:2] == ans[N:]:
# sの最初の2文字(仮定)と最後の2文字が一致した文字列のみ受理する。
# 1つ見つければ良いので、すぐにbreakする
ans = ans[:N]
break
else: # どの割り当て方も矛盾した
ans = '-1'
return ans
N = int(input())
S = input().strip()
print(d_menagerie(N, S))
``` | instruction | 0 | 51,184 | 16 | 102,368 |
Yes | output | 1 | 51,184 | 16 | 102,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
two = ["SS", "SW", "WS", "WW"]
n = int(input())
s = input()
flip = {"S":"W", "W":"S"}
flag = False
for i in two:
for j in s[1:]:
if j == 'o':
if i[-1] == 'S':
i += i[-2]
else:
i += flip[i[-2]]
else:
if i[-1] == 'S':
i += flip[i[-2]]
else:
i += i[-2]
if i[0] == i[-1]:
if s[0] == 'o':
if i[0] == 'S' and i[-2] == i[1] or i[0] == 'W' and i[-2] != i[1]:
flag = True
else:
if i[0] == 'S' and i[-2] != i[1] or i[0] == 'W' and i[-2] == i[1]:
flag = True
if flag:
print(i[:-1])
break
if not flag:
print(-1)
``` | instruction | 0 | 51,185 | 16 | 102,370 |
Yes | output | 1 | 51,185 | 16 | 102,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
def solve(n, S):
for i in range(4):
ans = list()
t = i
for j, s in enumerate(S):
f0 = t // 2
f1 = t % 2
f2 = f0 ^ (0 if s == 'o' else 1)
ans.append('S' if f2 == 0 else 'W')
t = ((f1 ^ f2) << 1) | f2
if (i == t) :
x = ans[:-1]
x.insert(0, ans[-1])
return "".join(x)
return "-1"
if __name__ == '__main__':
print(solve(int(input()), input()))
``` | instruction | 0 | 51,186 | 16 | 102,372 |
Yes | output | 1 | 51,186 | 16 | 102,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
N = int(input())
s = input().strip()
def check(a, b):
v = [0]*N
v[0] = a
v[1] = b
for i in range(1, N-1):
if s[i] == 'o':
if v[i]:
v[i+1] = v[i-1]
else:
v[i+1] = not v[i-1]
else:
if v[i]:
v[i+1] = not v[i-1]
else:
v[i+1] = v[i-1]
ok = True
for i in range(N):
same = v[(i-1) % N] == v[(i+1) % N]
if s[i] == 'o':
if v[i] != same:
ok = False
else:
if v[i] == same:
ok = False
return v if ok else None
p = [
[True, True],
[False, False],
[True, False],
[False, True]
]
ans = "-1"
for a, b in p:
l = check(a, b)
if l != None:
ans = "".join(["S" if v else "W" for v in l])
break
print(ans)
``` | instruction | 0 | 51,187 | 16 | 102,374 |
Yes | output | 1 | 51,187 | 16 | 102,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
import sys
def SorW(s, animal_lst):
for animal in range(1, N):
if s[animal] == "o":
if animal_lst[animal] == "S":
animal_lst.append(animal_lst[animal-1])
elif animal_lst[animal] == "W":
animal_lst.append(oppos_animal(animal_lst[animal-1]))
if s[animal] == "x":
if animal_lst[animal] == "S":
animal_lst.append(oppos_animal(animal_lst[animal-1]))
elif animal_lst[animal] == "W":
animal_lst.append(animal_lst[animal-1])
def oppos_animal(animal):
if animal == "S":
return "W"
elif animal == "W":
return "S"
N = int(input())
s = input()
lst = [["S", "S"], ["W", "W"], ["S", "W"], ["W", "S"]]
for i in lst:
SorW(s, i)
if i[0] == i[-1]:
print("".join(i[:-1]))
sys.exit()
print(-1)
``` | instruction | 0 | 51,188 | 16 | 102,376 |
No | output | 1 | 51,188 | 16 | 102,377 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
N = int(input())
s = input()
def fnc(x1, x2):
pre = x1
curr = x2
ans = [x1]
for i in range(1, N):
if curr == 1: # 羊
if s[i] == 'o':
nv = pre
else:
nv = (pre + 1) % 2
else: # 狼
if s[i] == 'x':
nv = pre
else:
nv = (pre + 1) % 2
pre = curr
curr = nv
ans.append(pre)
if curr == x1:
return ans
else:
return None
def solve():
for i in [0,1]:
for j in [0,1]:
ans = fnc(i, j)
if ans:
return ans
return None
if __name__ == '__main__':
ans = solve()
if not ans:
print(-1)
exit()
for a in ans:
print('S' if a else 'W', end='')
print()
``` | instruction | 0 | 51,189 | 16 | 102,378 |
No | output | 1 | 51,189 | 16 | 102,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
from itertools import product as prod
n = int(input())
ss = list(input())
def next_anim(a_0, a_1, s):
if s == "o":
if a_1 == "S":
return a_0
else:
return "W" if a_0 == "S" else "S"
else:
if a_1 == "S":
return "W" if a_0 == "S" else "S"
else:
return a_0
ans = -1
anims = ["" for _ in range(n)]
for fst, snd in prod(["W", "S"], repeat=2):
anims[:2] = [fst, snd]
for i in range(2, n):
anims[i] = next_anim(anims[i-2], anims[i-1], ss[i-1])
tmp_anim2 = next_anim(anims[-2], anims[-1], ss[-1])
if tmp_anim2 == anims[0]:
ans = "".join(anims)
break
print(ans)
``` | instruction | 0 | 51,190 | 16 | 102,380 |
No | output | 1 | 51,190 | 16 | 102,381 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke, who loves animals, built a zoo.
There are N animals in this zoo. They are conveniently numbered 1 through N, and arranged in a circle. The animal numbered i (2≤i≤N-1) is adjacent to the animals numbered i-1 and i+1. Also, the animal numbered 1 is adjacent to the animals numbered 2 and N, and the animal numbered N is adjacent to the animals numbered N-1 and 1.
There are two kinds of animals in this zoo: honest sheep that only speak the truth, and lying wolves that only tell lies.
Snuke cannot tell the difference between these two species, and asked each animal the following question: "Are your neighbors of the same species?" The animal numbered i answered s_i. Here, if s_i is `o`, the animal said that the two neighboring animals are of the same species, and if s_i is `x`, the animal said that the two neighboring animals are of different species.
More formally, a sheep answered `o` if the two neighboring animals are both sheep or both wolves, and answered `x` otherwise. Similarly, a wolf answered `x` if the two neighboring animals are both sheep or both wolves, and answered `o` otherwise.
Snuke is wondering whether there is a valid assignment of species to the animals that is consistent with these responses. If there is such an assignment, show one such assignment. Otherwise, print `-1`.
Constraints
* 3 ≤ N ≤ 10^{5}
* s is a string of length N consisting of `o` and `x`.
Input
The input is given from Standard Input in the following format:
N
s
Output
If there does not exist an valid assignment that is consistent with s, print `-1`. Otherwise, print an string t in the following format. The output is considered correct if the assignment described by t is consistent with s.
* t is a string of length N consisting of `S` and `W`.
* If t_i is `S`, it indicates that the animal numbered i is a sheep. If t_i is `W`, it indicates that the animal numbered i is a wolf.
Examples
Input
6
ooxoox
Output
SSSWWS
Input
3
oox
Output
-1
Input
10
oxooxoxoox
Output
SSWWSSSWWS
Submitted Solution:
```
N = int(input())
S = list(map(int, input().replace('o', '0').replace('x', '1')))
for p in [[0, 0], [0, 1], [1, 0], [1, 1]]:
for s in S[1:]:
if p[-1] ^ p[-2] ^ s == 1:
p.append(1)
else:
p.append(0)
if (p[0] == p[-1]) and (p[-2] ^ p[-3] ^ p[0] ^ S[-1] == 0):
print(''.join(map(str, p[:-1])).replace('0', 'S').replace('1', 'W'))
break
else:
print(-1)
``` | instruction | 0 | 51,191 | 16 | 102,382 |
No | output | 1 | 51,191 | 16 | 102,383 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,917 | 16 | 105,834 |
"Correct Solution:
```
# coding: utf-8
# Your code here!
import sys
read = sys.stdin.read
readline = sys.stdin.readline
n,m = map(int,readline().split())
#lrx = [tuple(map(int,readline().split())) for _ in range(m)]
#lrx.sort(key=lambda x: x[1])
cond = [[] for _ in range(n+1)]
for _ in range(m):
l,r,x = map(int,readline().split())
cond[r].append((l,x))
"""
dp[i][j][k] = iまで見て 2 色目は j個前に、3 色目は k個前 に登場
1 <= j < k
"""
N = n+3
dp = [[0]*(N) for _ in range(N)]
dp[1][2] = 1
MOD = 10**9+7
def f(r,j,k,v,ndp):
if j >= N or k >= N: return
for l,x in cond[r]:
if x==1 and l <= r-j: return
if x==2 and (r-j < l or l <= r-k): return
if x==3 and r-k < l: return
ndp[j][k] += v
ndp[j][k] %= MOD
return
for i in range(1,n+1):
ndp = [[0]*(N) for _ in range(N)]
for q in range(1,N):
for r in range(q+1,N):
v = dp[q][r]
if v:
f(i,q+1,r+1,v,ndp)
f(i,1,r+1,v,ndp)
f(i,1,q+1,v,ndp)
dp = ndp
#print(dp)
ans = sum(sum(i) for i in dp)
print(ans%MOD)
``` | output | 1 | 52,917 | 16 | 105,835 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,918 | 16 | 105,836 |
"Correct Solution:
```
import sys
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
# 一番後ろの色を(赤に)固定した上で、もらうDPに書き換え
def main():
md = 10 ** 9 + 7
n, m = MI()
rtol = defaultdict(list)
for _ in range(m):
l, r, x = MI()
rtol[r].append([l, x])
dp = [[0] * (n + 1) for _ in range(n + 1)]
dp[0][0] = 1
for k in range(1, n + 1):
for i in range(k - 1):
dp[i][k - 1] = dp[k - 1][i] = sum(dp[i][:k - 1]) % md
for l, x in rtol[k]:
if x == 1:
for i in range(l, k):
for j in range(k):
dp[i][j] = dp[j][i] = 0
if x == 2:
for i in range(l, k):
for j in range(i + 1, k):
dp[i][j] = dp[j][i] = 0
for i in range(l):
for j in range(i + 1):
dp[i][j] = dp[j][i] = 0
if x == 3:
for i in range(l):
for j in range(k):
dp[i][j] = dp[j][i] = 0
# p2D(dp)
print(sum(sum(dr) for dr in dp) * 3 % md)
main()
``` | output | 1 | 52,918 | 16 | 105,837 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,919 | 16 | 105,838 |
"Correct Solution:
```
MOD = 10**9 + 7
N, M = map(int, input().split())
S = [[N]*(N+1) for i in [0,1,2]]
T = [[0]*(N+1) for i in [0,1,2]]
C = [0]*(N+1)
for i in range(M):
l, r, x = map(int, input().split())
S[x-1][r] = min(S[x-1][r], l)
T[x-1][r] = max(T[x-1][r], l)
C[r] = 1
S0, S1, S2 = S
T0, T1, T2 = T
ok = 1
for i in range(N+1):
if not T2[i] < S1[i] or not T1[i] < S0[i]:
ok = 0
break
if not ok:
print(0)
exit(0)
X = {(0, 0): 3}
for b in range(1, N):
t2 = T2[b+1]; s1 = S1[b+1]; t1 = T1[b+1]; s0 = S0[b+1]
check = lambda r, g: t2 <= r < s1 and t1 <= g < s0
Z = [0]*(N+1)
if C[b+1]:
if t1 <= b < s0:
for (r, g), v in X.items():
if t2 <= g < s1:
# r <- b+1
Z[g] += v
if t2 <= r < s1:
# g <- b+1
Z[r] += v
X = {(r, g): v for (r, g), v in X.items() if t2 <= r < s1 and t1 <= g < s0}
else:
Z = [0]*(N+1)
for (r, g), v in X.items():
# r <- b+1
Z[g] += v
# g <- b+1
Z[r] += v;
for z, v in enumerate(Z):
if v:
X[z, b] = v % MOD
print(sum(X.values()) % MOD)
``` | output | 1 | 52,919 | 16 | 105,839 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,920 | 16 | 105,840 |
"Correct Solution:
```
from collections import defaultdict
MOD = 1000000007
iist = lambda: map(int,input().split())
N,M = iist()
Q = defaultdict(list)
for i in range(M):
l,r,x = iist()
Q[r].append((l,x-1))
if any(x != 0 for l,x in Q[1]):
print(0)
exit(0)
dp = {(0,0):3}
memo = [6]
s = 3
for pk in range(1,N):
k = pk+1
for i,c in enumerate(memo):
c %= MOD
dp[i,pk] = c
memo[i] *= 2
memo[i] %= MOD
memo.append(2*s%MOD)
s = 3*s%MOD
subQ = Q[k]
for i,j in list(dp.keys()):
for l,x in subQ:
if x != (l<=i)+(l<=j):
c = dp[i,j]
memo[i] -= c
memo[j] -= c
s -= c
del dp[i,j]
break
s %= MOD
print(s)
``` | output | 1 | 52,920 | 16 | 105,841 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,921 | 16 | 105,842 |
"Correct Solution:
```
from itertools import permutations
n,m = map(int,input().split())
lrx = [list(map(int,input().split())) for i in range(m)]
lrx.sort(key = lambda x:x[1])
mod = 10**9+7
dp = [[[0 for b in range(max(1,g))] for g in range(max(1,r))] for r in range(n+1)]
dp[0][0][0] = 1
for l,r,t in lrx:
if t != 1:
for g in range(l):
for b in range(max(1,g)):
dp[r][g][b] = -1
if t != 2:
for g in range(l,r):
for b in range(l):
dp[r][g][b] = -1
if t != 3:
for g in range(l,r):
for b in range(l,g):
dp[r][g][b] = -1
for r in range(n):
for g in range(max(1,r)):
for b in range(max(1,g)):
v = dp[r][g][b]
if v == -1:
continue
if dp[r+1][g][b] >= 0:
dp[r+1][g][b] += v
dp[r+1][g][b] %= mod
if dp[r+1][r][b] >= 0:
dp[r+1][r][b] += v
dp[r+1][r][b] %= mod
if dp[r+1][r][g] >= 0:
dp[r+1][r][g] += v
dp[r+1][r][g] %= mod
ans = 0
for i in range(n):
for j in range(max(1,i)):
if dp[n][i][j] >= 0:
ans += dp[n][i][j]
ans %= mod
print(ans%mod)
``` | output | 1 | 52,921 | 16 | 105,843 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,922 | 16 | 105,844 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
mod = 10**9+7
# (i, j, k+1)に置くのが、条件(l,x)に適しているか
def check(i, j, l, x):
return (x == 3 and l <= i) or (x == 2 and i < l <= j) or (x == 1 and j < l)
N, M = map(int, input().split())
LRX = [list(map(int, input().split())) for _ in range(M)]
LX = [[] for _ in range(N+2)]
for l, r, x in LRX:
LX[r].append((l, x))
dp = [[[0]*(j+1) for j in range(i+1)] for i in range(N+2)]
# dp[i][j][k] (k <= j <= i)
# 三色それぞれ、最後に使ったindex(1-indexed)がi,j,k
dp[0][0][0] = 1
for i in range(N+1):
for j in range(i, N+1):
for k in range(j, N+1):
# 一番前の色を置く
ok = True
for l, x in LX[k+1]:
if not check(j, k, l, x):
ok = False
break
if ok:
dp[k+1][k][j] = (dp[k+1][k][j] + dp[k][j][i]) % mod
# 最後
ok = True
for l, x in LX[k+1]:
if not check(i, j, l, x):
ok = False
break
if ok:
dp[k+1][j][i] = (dp[k+1][j][i] + dp[k][j][i]) % mod
# 二番目
ok = True
for l, x in LX[k+1]:
if not check(i, k, l, x):
ok = False
break
if ok:
dp[k+1][k][i] = (dp[k+1][k][i] + dp[k][j][i]) % mod
ans = 0
for a in range(N+1):
for b in range(a,N+1):
ans = (ans + dp[N][b][a]) % mod
print(ans)
``` | output | 1 | 52,922 | 16 | 105,845 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,923 | 16 | 105,846 |
"Correct Solution:
```
from collections import defaultdict
MOD = 1000000007
iist = lambda: map(int,input().split())
N,M = iist()
Q = defaultdict(list)
for i in range(M):
l,r,x = iist()
Q[r].append((l,x))
if any(x != 1 for l,x in Q[1]):
print(0)
exit(0)
dp = defaultdict(int)
dp[0,0] = 3
x_sum = [3]
y_sum = [3]
s = 3
for pk in range(1,N):
k = pk+1
for i,(a,b) in enumerate(zip(x_sum,y_sum)):
c = (a+b)%MOD
dp[i,pk] = c
x_sum[i] += c
x_sum.append(0)
y_sum.append((2*s)%MOD)
s *= 3
subQ = Q[k]
for i,j in list(dp.keys()):
for l,x in subQ:
if x != (l<=i)+(l<=j)+1:
c = dp[i,j]
x_sum[i] -= c
y_sum[j] -= c
s -= c
del dp[i,j]
break
for i in range(pk):
x_sum[i] %= MOD
y_sum[i] %= MOD
s %= MOD
print(s)
``` | output | 1 | 52,923 | 16 | 105,847 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108 | instruction | 0 | 52,924 | 16 | 105,848 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
def viol(c2, c3, l, x):
res = False
if x == 1:
if not c2 < l:
res = True
elif x == 2:
if not c3 < l <= c2:
res = True
else:
if not l <= c3:
res = True
return res
MOD = 10**9+7
N, M = map(int, readline().split())
limit = [[] for _ in range(N+3)]
for _ in range(M):
l, r, x = map(int, readline().split())
limit[r+2].append((l+2, x))
dp = [[0, 0], [1, 0]]
for i in range(2, N+2):
dp2 = [[0]*(i+1) for _ in range(i+1)]
r = i
for g in range(r):
for b in range(g):
d = dp[g][b]
dp2[g][b] = (dp2[g][b] + d)%MOD
dp2[r][b] = (dp2[r][b] + d)%MOD
dp2[r][g] = (dp2[r][g] + d)%MOD
for l, x in limit[i+1]:
r = i+1
for g in range(r):
for b in range(g):
if viol(g, b, l, x):
dp2[g][b] = 0
dp = [d[:] for d in dp2]
res = 0
for g in range(N+2):
for b in range(g):
res = (res + dp[g][b]) % MOD
print(res)
``` | output | 1 | 52,924 | 16 | 105,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
N,M=map(int,input().split())
q=[[] for i in range(N+1)]
for i in range(M):
l,r,x=map(int,input().split())
q[r].append((l,x))
mod=10**9+7
dp=[[0 for i in range(N+1)] for i in range(N+1)]
i=N
for j in range(N+1):
for k in range(N+1):
check=7
for l,x in q[i]:
if i==l:
check=(x==1)*check
elif i-1>=l>j:
check=(x==1)*(check%2)+(x==2)*(check&6)
elif j>=l>k:
check=(x==2)*(check&3)+(x==3)*(check&4)
else:
check*=(x==3)
dp[j][k]=bin(check).count("1")
ndp=[[0 for j in range(N+1)] for k in range(N+1)]
for i in range(N-1,0,-1):
for j in range(i):
for k in range(j+1):
check=7
for l,x in q[i]:
if i==l:
check=(x==1)*check
elif i-1>=l>j:
check=(x==1)*(check%2)+(x==2)*(check&6)
elif j>=l>k:
check=(x==2)*(check&3)+(x==3)*(check&4)
else:
check*=(x==3)
ndp[j][k]=(dp[j][k]*((check//1)%2)+dp[i-1][k]*((check//2)%2)+dp[i-1][j]*((check//4)%2))%mod
dp=ndp
print(dp[0][0])
``` | instruction | 0 | 52,925 | 16 | 105,850 |
Yes | output | 1 | 52,925 | 16 | 105,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
MOD = 10**9 + 7
N, M = map(int, input().split())
S = [[N+1]*(N+1) for i in [0,1,2]]
T = [[0]*(N+1) for i in [0,1,2]]
C = [0]*(N+1)
for i in range(M):
l, r, x = map(int, input().split())
if r-l < x-1:
print(0)
exit(0)
S[x-1][r] = min(S[x-1][r], l)
T[x-1][r] = max(T[x-1][r], l)
C[r] = 1
S0, S1, S2 = S
T0, T1, T2 = T
ok = 1
for i in range(N+1):
if not T2[i] < S1[i] or not T1[i] < S0[i]:
ok = 0
break
if not ok:
print(0)
exit(0)
RM = [N+1]*(N+1); GM = [N+1]*(N+1)
for i in range(N-1, -1, -1):
RM[i] = min(RM[i+1], S1[i+1])
GM[i] = min(GM[i+1], S0[i+1])
X = {(0, 0): 3}
D = [0]*(N+1); D[0] = 6
B = [{} for i in range(N+1)]
B[0][0] = 3
bb = 0
for b in range(1, N):
t2 = T2[b+1]; s1 = S1[b+1]; t1 = T1[b+1]; s0 = S0[b+1]
rm = RM[b]
gm = GM[b]
if t1 <= b < gm:
F = B[b]
for z in range(t2, min(rm, b)):
v = D[z] % MOD
if v:
F[z] = v; D[z] += v; D[b] += v
if C[b+1]:
for g in range(bb, min(t1, b)):
for r, v in B[g].items():
D[r] -= v; D[g] -= v
B[g] = None
bb = max(t1, bb)
for g in range(bb, b):
for r, v in B[g].items():
if not t2 <= r < s1:
D[r] -= v; D[g] -= v
B[g] = {r: v for r, v in B[g].items() if t2 <= r < s1}
ans = 0
for b in range(bb, N+1):
if B[b]:
ans += sum(B[b].values())
print(ans % MOD)
``` | instruction | 0 | 52,926 | 16 | 105,852 |
Yes | output | 1 | 52,926 | 16 | 105,853 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
N,M=map(int,input().split())
Q=[[int(i) for i in input().split()] for i in range(M)]
Q.sort(key=lambda x:x[1])
mod=10**9+7
dp=[[[0]*max(1,c) for c in range(max(1,b+1))] for b in range(N+1)]
dp[0][0][0]=1
k=0
for a in range(N+1):
check=[]
if k<=M-1:
while a==Q[k][1]:
l,r,x=Q[k]
check.append((l,r,x))
k+=1
if k==M:
break
for b in range(max(1,a)):
for c in range(max(1,b)):
for l,r,x in check:
if x==1:
if not b<l:
dp[a][b][c]=0
continue
elif x==2:
if not (b>=l and c<l):
dp[a][b][c]=0
continue
elif x==3:
if not c>=l:
dp[a][b][c]=0
continue
dp[a][b][c]%=mod
if a<=N-1:
dp[a+1][b][c]+=dp[a][b][c]
dp[a+1][a][c]+=dp[a][b][c]
dp[a+1][a][b]+=dp[a][b][c]
ans=0
for b in range(N):
for c in range(max(1,b)):
ans+=dp[N][b][c]
ans%=mod
print(ans)
``` | instruction | 0 | 52,927 | 16 | 105,854 |
Yes | output | 1 | 52,927 | 16 | 105,855 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
# seishin.py
N, M = map(int, input().split())
r_min = [0]*(N+1); r_max = [N+1]*(N+1)
g_min = [0]*(N+1); g_max = [N+1]*(N+1)
for i in range(M):
l, r, x = map(int, input().split())
# 仮定: R < G < B を元に各r,gの値の範囲を絞り込む(B = rになるため計算しない)
if x == 1:
# x = 1の時、あるrに紐づく全てのl_iについて G < l_i を満たす必要がある
# => G < min(l_i) を満たせばよい
g_max[r] = min(g_max[r], l-1)
elif x == 2:
# x = 2の時、あるrに紐づく全てのl_iについて R < l_i, l_i <= G を満たす必要がある
# => R < min(l_i), max(l_i) <= G を満たせばよい
g_min[r] = max(g_min[r], l)
r_max[r] = min(r_max[r], l-1)
elif x == 3:
# x = 3の時、あるrに紐づく全てのl_iについて l_i <= R を満たす必要がある
# => max(l_i) <= R を満たせばよい
r_min[r] = max(r_min[r], l)
MOD = 10**9 + 7
def check(r, g, k):
return +(r_min[k] <= r <= r_max[k] and g_min[k] <= g <= g_max[k])
# 左からk個置いた時、各色の最右の位置を持ってbfs
# r < g < b(= k) を維持して計算していく
que = [{} for i in range(N+1)]
que[0][0, 0] = 1
for k in range(N):
cur = que[k]
nxt = que[k+1]
for r, g in cur:
# r < g < b < k+1 の関係を元に次の状態に伝播
# 制約を満たす場合のみに伝播
if check(g, k, k+1):
nxt[g, k] = (nxt.get((g, k), 0) + cur[r, g]) % MOD
if check(r, k, k+1):
nxt[r, k] = (nxt.get((r, k), 0) + cur[r, g]) % MOD
if check(r, g, k+1):
nxt[r, g] = (nxt.get((r, g), 0) + cur[r, g]) % MOD
print(sum(que[N].values()) % MOD)
``` | instruction | 0 | 52,928 | 16 | 105,856 |
No | output | 1 | 52,928 | 16 | 105,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9, MOD = 1e9 + 7,
around[] = {0, 1, 1, -1, -1, 0, -1, 1, 0, 0};
const long long LINF = 1e18;
const long double PI = abs(acos(-1));
int n, m, a, b, c;
long long dp[310][310][310];
vector<pair<int, int> > vec[310];
bool ch(int i, int j, int k) {
int r = max(i, max(j, k));
for (auto s : vec[r]) {
if (((s.first < i) + (s.first < j) + (s.first < k)) != s.second) return 0;
}
return 1;
}
int main() {
cin >> n >> m;
for (int i = (0); i < (m); i++)
cin >> a >> b >> c, vec[b].push_back(pair<int, int>(a - 1, c));
dp[0][0][0] = 1;
for (int i = (0); i < (n); i++) {
for (int j = (0); j < (n); j++) {
for (int k = (0); k < (n); k++) {
int ma = max(i, max(j, k));
if (ch(i, j, ma + 1)) (dp[i][j][ma + 1] += dp[i][j][k]) %= MOD;
if (ch(i, ma + 1, k)) (dp[i][ma + 1][k] += dp[i][j][k]) %= MOD;
if (ch(ma + 1, j, k)) (dp[ma + 1][j][k] += dp[i][j][k]) %= MOD;
}
}
}
long long s = 0;
for (int i = (0); i < (n + 1); i++) {
for (int j = (0); j < (n + 1); j++) {
s += dp[n][i][j];
s += dp[i][n][j];
s += dp[i][j][n];
}
}
cout << s % MOD << endl;
return 0;
}
``` | instruction | 0 | 52,929 | 16 | 105,858 |
No | output | 1 | 52,929 | 16 | 105,859 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
import sys
from collections import defaultdict
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def main():
md=10**9+7
n, m = MI()
rtol = defaultdict(list)
for _ in range(m):
l, r, x = MI()
rtol[r].append([l, x])
dp = [[[0] * (n + 1) for _ in range(n + 1)] for _ in range(n + 1)]
dp[0][0][0] = 1
ans = 0
for r in range(n):
for g in range(n):
for b in range(n):
pre = dp[r][g][b]
if pre == 0: continue
i = max(r, g, b) + 1
dp[i][g][b] += pre
dp[r][i][b] += pre
dp[r][g][i] += pre
for l, x in rtol[i]:
over_l = [r >= l, g >= l, b >= l]
if over_l[1] + over_l[2] + 1 != x:
dp[i][g][b] = 0
if over_l[0] + over_l[2] + 1 != x:
dp[r][i][b] = 0
if over_l[0] + over_l[1] + 1 != x:
dp[r][g][i] = 0
#if i == n:
# ans += dp[i][g][b] + dp[r][i][b] + dp[r][g][i]
ans+=sum(dp[i][j][n] for i in range(n) for j in range(n))
ans%=md
ans+=sum(dp[i][n][j] for i in range(n) for j in range(n))
ans%=md
ans+=sum(dp[n][j][i] for i in range(n) for j in range(n))
ans%=md
print(ans)
main()
``` | instruction | 0 | 52,930 | 16 | 105,860 |
No | output | 1 | 52,930 | 16 | 105,861 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row. The squares are numbered 1, 2, ..., N, from left to right.
Snuke is painting each square in red, green or blue. According to his aesthetic sense, the following M conditions must all be satisfied. The i-th condition is:
* There are exactly x_i different colors among squares l_i, l_i + 1, ..., r_i.
In how many ways can the squares be painted to satisfy all the conditions? Find the count modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 300
* 1 ≤ M ≤ 300
* 1 ≤ l_i ≤ r_i ≤ N
* 1 ≤ x_i ≤ 3
Input
Input is given from Standard Input in the following format:
N M
l_1 r_1 x_1
l_2 r_2 x_2
:
l_M r_M x_M
Output
Print the number of ways to paint the squares to satisfy all the conditions, modulo 10^9+7.
Examples
Input
3 1
1 3 3
Output
6
Input
4 2
1 3 1
2 4 2
Output
6
Input
1 3
1 1 1
1 1 2
1 1 3
Output
0
Input
8 10
2 6 2
5 5 1
3 5 2
4 7 3
4 4 1
2 3 1
7 7 1
1 5 2
1 7 3
3 4 2
Output
108
Submitted Solution:
```
from itertools import permutations
n,m = map(int,input().split())
lrx = [list(map(int,input().split())) for i in range(m)]
lrx.sort(key = lambda x:x[1])
mod = 10**9+7
dp = [[[0 for i in range(n+1)] for j in range(n+1)] for k in range(n+1)]
dp[0][0][0] = 1
for l,r,t in lrx:
if t != 1:
for g in range(l):
for b in range(max(1,g)):
dp[r][g][b] = -1
if t != 2:
for g in range(l,r):
for b in range(l):
dp[r][g][b] = -1
if t != 3:
for g in range(l,r):
for b in range(l,g):
dp[r][g][b] = -1
for r in range(n):
for g in range(max(1,r)):
for b in range(max(1,g)):
v = dp[r][g][b]
if v == -1:
continue
if dp[r+1][g][b] >= 0:
dp[r+1][g][b] += v
dp[r+1][g][b] %= mod
if dp[r+1][r][b] >= 0:
dp[r+1][r][b] += v
dp[r+1][r][b] %= mod
if dp[r+1][g][b] >= 0:
dp[r+1][g][b] += v
dp[r+1][g][b] %= mod
ans = 0
for i in range(n):
for j in range(max(1,i)):
if dp[n][i][j] >= 0:
ans += dp[n][i][j]
ans %= mod
print(ans*6%mod)
``` | instruction | 0 | 52,931 | 16 | 105,862 |
No | output | 1 | 52,931 | 16 | 105,863 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Consider all integers between 1 and 2N, inclusive. Snuke wants to divide these integers into N pairs such that:
* Each integer between 1 and 2N is contained in exactly one of the pairs.
* In exactly A pairs, the difference between the two integers is 1.
* In exactly B pairs, the difference between the two integers is 2.
* In exactly C pairs, the difference between the two integers is 3.
Note that the constraints guarantee that N = A + B + C, thus no pair can have the difference of 4 or more.
Compute the number of ways to do this, modulo 10^9+7.
Constraints
* 1 ≤ N ≤ 5000
* 0 ≤ A, B, C
* A + B + C = N
Input
The input is given from Standard Input in the following format:
N A B C
Output
Print the answer.
Examples
Input
3 1 2 0
Output
2
Input
600 100 200 300
Output
522158867
Submitted Solution:
```
#include <bits/stdc++.h>
using namespace std;
using Int = long long;
template <typename T1, typename T2>
inline void chmin(T1& a, T2 b) {
if (a > b) a = b;
}
template <typename T1, typename T2>
inline void chmax(T1& a, T2 b) {
if (a < b) a = b;
}
template <typename T, T MOD = 1000000007>
struct Mint {
T v;
Mint() : v(0) {}
Mint(signed v) : v(v) {}
Mint(long long t) {
v = t % MOD;
if (v < 0) v += MOD;
}
Mint pow(long long k) {
Mint res(1), tmp(v);
while (k) {
if (k & 1) res *= tmp;
tmp *= tmp;
k >>= 1;
}
return res;
}
static Mint add_identity() { return Mint(0); }
static Mint mul_identity() { return Mint(1); }
Mint inv() { return pow(MOD - 2); }
Mint& operator+=(Mint a) {
v += a.v;
if (v >= MOD) v -= MOD;
return *this;
}
Mint& operator-=(Mint a) {
v += MOD - a.v;
if (v >= MOD) v -= MOD;
return *this;
}
Mint& operator*=(Mint a) {
v = 1LL * v * a.v % MOD;
return *this;
}
Mint& operator/=(Mint a) { return (*this) *= a.inv(); }
Mint operator+(Mint a) const { return Mint(v) += a; };
Mint operator-(Mint a) const { return Mint(v) -= a; };
Mint operator*(Mint a) const { return Mint(v) *= a; };
Mint operator/(Mint a) const { return Mint(v) /= a; };
Mint operator-() const { return v ? Mint(MOD - v) : Mint(v); }
bool operator==(const Mint a) const { return v == a.v; }
bool operator!=(const Mint a) const { return v != a.v; }
bool operator<(const Mint a) const { return v < a.v; }
static Mint comb(long long n, int k) {
Mint num(1), dom(1);
for (int i = 0; i < k; i++) {
num *= Mint(n - i);
dom *= Mint(i + 1);
}
return num / dom;
}
};
template <typename M>
struct Enumeration {
static vector<M> fact, finv, invs;
static void init(int n) {
int m = fact.size();
if (n < m) return;
fact.resize(n + 1, 1);
finv.resize(n + 1, 1);
invs.resize(n + 1, 1);
if (m == 0) m = 1;
for (int i = m; i <= n; i++) fact[i] = fact[i - 1] * M(i);
finv[n] = M(1) / fact[n];
for (int i = n; i >= m; i--) finv[i - 1] = finv[i] * M(i);
for (int i = m; i <= n; i++) invs[i] = finv[i] * fact[i - 1];
}
static M C(int n, int k) {
if (n < k || k < 0) return M(0);
init(n);
return fact[n] * finv[n - k] * finv[k];
}
static M P(int n, int k) {
if (n < k || k < 0) return M(0);
init(n);
return fact[n] * finv[n - k];
}
static M H(int n, int k) {
if (n < 0 || k < 0) return M(0);
if (!n && !k) return M(1);
init(n + k - 1);
return C(n + k - 1, k);
}
static M S(int n, int k) {
M res;
init(k);
for (int i = 1; i <= k; i++) {
M tmp = C(k, i) * M(i).pow(n);
if ((k - i) & 1)
res -= tmp;
else
res += tmp;
}
return res *= finv[k];
}
static vector<vector<M> > D(int n, int m) {
vector<vector<M> > dp(n + 1, vector<M>(m + 1, 0));
dp[0][0] = M(1);
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (i - j >= 0)
dp[i][j] = dp[i][j - 1] + dp[i - j][j];
else
dp[i][j] = dp[i][j - 1];
}
}
return dp;
}
static M B(int n, int k) {
if (n == 0) return M(1);
k = min(k, n);
init(k);
vector<M> dp(k + 1);
dp[0] = M(1);
for (int i = 1; i <= k; i++)
dp[i] = dp[i - 1] + ((i & 1) ? -finv[i] : finv[i]);
M res;
for (int i = 1; i <= k; i++) res += M(i).pow(n) * finv[i] * dp[k - i];
return res;
}
static M montmort(int n) {
M res;
init(n);
for (int k = 2; k <= n; k++) {
if (k & 1)
res -= finv[k];
else
res += finv[k];
}
return res *= fact[n];
}
static M LagrangePolynomial(vector<M>& y, M t) {
int n = y.size() - 1;
if (t.v <= n) return y[t.v];
init(n + 1);
M num(1);
for (int i = 0; i <= n; i++) num *= t - M(i);
M res;
for (int i = 0; i <= n; i++) {
M tmp = y[i] * num / (t - M(i)) * finv[i] * finv[n - i];
if ((n - i) & 1)
res -= tmp;
else
res += tmp;
}
return res;
}
};
template <typename M>
vector<M> Enumeration<M>::fact = vector<M>();
template <typename M>
vector<M> Enumeration<M>::finv = vector<M>();
template <typename M>
vector<M> Enumeration<M>::invs = vector<M>();
signed main() {
int n, a, b, c;
cin >> n >> a >> b >> c;
using M = Mint<int>;
using E = Enumeration<M>;
E::init(1e5);
M ans{0};
for (int x = 0; x <= c; x++) {
for (int y = 0; y * 3 <= c; y++) {
int w = a - x;
int z = b / 2;
int k = c - (x + y * 3);
if (w < 0 || z < 0 || k < 0) continue;
if (w + x == a && z * 2 == b && x + y * 3 + k == c) {
M res = E::H(z, k);
int sum = w + x + y + z;
res *= E::fact[sum];
res *= E::finv[w];
res *= E::finv[x];
res *= E::finv[y];
res *= E::finv[z];
ans += res;
}
}
}
cout << ans.v << endl;
return 0;
}
``` | instruction | 0 | 52,932 | 16 | 105,864 |
No | output | 1 | 52,932 | 16 | 105,865 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke loves colorful balls. He has a total of N×K balls, K in each of his favorite N colors. The colors are numbered 1 through N.
He will arrange all of the balls in a row from left to right, in arbitrary order. Then, for each of the N colors, he will paint the leftmost ball of that color into color 0, a color different from any of the N original colors.
After painting, how many sequences of the colors of the balls are possible? Find this number modulo 10^9+7.
Constraints
* 1≤N,K≤2,000
Input
The input is given from Standard Input in the following format:
N K
Output
Print the number of the possible sequences of the colors of the balls after painting, modulo 10^9+7.
Examples
Input
2 2
Output
4
Input
3 1
Output
1
Input
2 3
Output
14
Input
2000 2000
Output
546381702 | instruction | 0 | 52,933 | 16 | 105,866 |
"Correct Solution:
```
def pow_mod(MOD, a, n):
ret = 1
while n != 0:
if n % 2 == 1: ret = ret * a % MOD
a = a * a % MOD
n //= 2
return ret
def fac(n):
MOD = 1000000007
ret = 1
for i in range(1, n + 1):
ret = ret * i % MOD
return ret
def fac_gen(first, last):
MOD = 1000000007
ret = fac(first)
yield ret
for i in range(first + 1, last):
ret = ret * i % MOD
yield ret
def build_comb_list(f, m, K):
MOD = 1000000007
v = pow_mod(MOD, f[m - K * 2] * f[0], MOD - 2)
for i in range(m - K, -1, -1):
f[i] *= v
v = v * i % MOD
def solve_dp(n, k, comb):
MOD = 1000000007
dp = [1] * (n + 1)
for i in range(2, n + 1):
ci = (i - 1) * (k - 1)
v = 0
for j, c in zip(range(i), comb[ci:ci + i]):
v = (v + dp[j] * c) % MOD
dp[j] = v
dp[i] = v
return dp[n] * fac(n) % MOD
def solve(n, k):
if n == 1 or k == 1: return 1
m = n * k
comb = list(fac_gen(k - 2, m - 1))
build_comb_list(comb, m - 2, k - 2)
return solve_dp(n, k, comb)
n, k = (int(s) for s in input().split(' '))
print(solve(n, k))
``` | output | 1 | 52,933 | 16 | 105,867 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke is playing with red and blue balls, placing them on a two-dimensional plane.
First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i). Then, he performed another N operations to place blue balls. In the i-th of these operations, he placed BC_i blue balls at coordinates (BX_i,BY_i). The total number of red balls placed and the total number of blue balls placed are equal, that is, \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i. Let this value be S.
Snuke will now form S pairs of red and blue balls so that every ball belongs to exactly one pair. Let us define the score of a pair of a red ball at coordinates (rx, ry) and a blue ball at coordinates (bx, by) as |rx-bx| + |ry-by|.
Snuke wants to maximize the sum of the scores of the pairs. Help him by finding the maximum possible sum of the scores of the pairs.
Constraints
* 1 \leq N \leq 1000
* 0 \leq RX_i,RY_i,BX_i,BY_i \leq 10^9
* 1 \leq RC_i,BC_i \leq 10
* \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
RX_1 RY_1 RC_1
RX_2 RY_2 RC_2
\vdots
RX_N RY_N RC_N
BX_1 BY_1 BC_1
BX_2 BY_2 BC_2
\vdots
BX_N BY_N BC_N
Output
Print the maximum possible sum of the scores of the pairs.
Examples
Input
2
0 0 1
3 2 1
2 2 1
5 0 1
Output
8
Input
3
0 0 1
2 2 1
0 0 2
1 1 1
1 1 1
3 3 2
Output
16
Input
10
582463373 690528069 8
621230322 318051944 4
356524296 974059503 6
372751381 111542460 9
392867214 581476334 6
606955458 513028121 5
882201596 791660614 9
250465517 91918758 3
618624774 406956634 6
426294747 736401096 5
974896051 888765942 5
726682138 336960821 3
715144179 82444709 6
599055841 501257806 6
390484433 962747856 4
912334580 219343832 8
570458984 648862300 6
638017635 572157978 10
435958984 585073520 7
445612658 234265014 6
Output
45152033546 | instruction | 0 | 54,593 | 16 | 109,186 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from heapq import heappop, heappush
N = int(readline())
m = map(int,read().split())
data = list(zip(m,m,m))
R = data[:N]
B = data[N:]
class MinCostFlow:
"""
最小費用流。負辺がないと仮定して、BellmanFordを省略している。
"""
def __init__(self, N, source, sink):
self.N = N
self.G = [[] for _ in range(N)]
self.source = source
self.sink = sink
def add_edge(self, fr, to, cap, cost):
n1 = len(self.G[fr])
n2 = len(self.G[to])
self.G[fr].append([to, cap, cost, n2])
self.G[to].append([fr, 0, -cost, n1])
def MinCost(self, flow, negative_edge = False):
if negative_edge:
raise ValueError
N = self.N; G = self.G; source = self.source; sink = self.sink
INF = 10 ** 18
prev_v = [0] * N; prev_e = [0] * N # 経路復元用
H = [0] * N # potential
mincost=0
while flow:
dist=[INF] * N
dist[source]=0
q = [source]
mask = (1 << 20) - 1
while q:
x = heappop(q)
dv = (x >> 20); v = x & mask
if dist[v] < dv:
continue
if v == sink:
break
for i,(w,cap,cost,rev) in enumerate(G[v]):
dw = dist[v] + cost + H[v] - H[w]
if (not cap) or (dist[w] <= dw):
continue
dist[w] = dw
prev_v[w] = v; prev_e[w] = i
heappush(q, (dw << 20) + w)
#if dist[sink] == INF:
# raise Exception('No Flow Exists')
# ポテンシャルの更新
for v,d in enumerate(dist):
H[v] += d
# 流せる量を取得する
d = flow; v = sink
while v != source:
pv = prev_v[v]; pe = prev_e[v]
cap = G[pv][pe][1]
if d > cap:
d = cap
v = pv
# 流す
mincost += d * H[sink]
flow -= d
v = sink
while v != source:
pv = prev_v[v]; pe = prev_e[v]
G[pv][pe][1] -= d
rev = G[pv][pe][3]
G[v][rev][1] += d
v = pv
return mincost
source = N+N; sink = N+N+1
V1 = N+N+2; V2 = N+N+3; V3 = N+N+4; V4 = N+N+5
G = MinCostFlow(N+N+6, source = source, sink = sink)
base = 10 ** 9 * 2 # 各辺に上乗せしておく -> 最後に引く
INF = 10 ** 18
flow = 0
for i,(x,y,c) in enumerate(R):
flow += c
G.add_edge(fr=source, to=i, cap=c, cost=0)
G.add_edge(i,V1,INF,base-x-y)
G.add_edge(i,V2,INF,base-x+y)
G.add_edge(i,V3,INF,base+x-y)
G.add_edge(i,V4,INF,base+x+y)
for i,(x,y,c) in enumerate(B,N):
G.add_edge(fr=i, to=sink, cap=c, cost=0)
G.add_edge(V1,i,INF,base+x+y)
G.add_edge(V2,i,INF,base+x-y)
G.add_edge(V3,i,INF,base-x+y)
G.add_edge(V4,i,INF,base-x-y)
cost = G.MinCost(flow)
answer = base * (2 * flow) - cost
print(answer)
``` | output | 1 | 54,593 | 16 | 109,187 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke is playing with red and blue balls, placing them on a two-dimensional plane.
First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i). Then, he performed another N operations to place blue balls. In the i-th of these operations, he placed BC_i blue balls at coordinates (BX_i,BY_i). The total number of red balls placed and the total number of blue balls placed are equal, that is, \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i. Let this value be S.
Snuke will now form S pairs of red and blue balls so that every ball belongs to exactly one pair. Let us define the score of a pair of a red ball at coordinates (rx, ry) and a blue ball at coordinates (bx, by) as |rx-bx| + |ry-by|.
Snuke wants to maximize the sum of the scores of the pairs. Help him by finding the maximum possible sum of the scores of the pairs.
Constraints
* 1 \leq N \leq 1000
* 0 \leq RX_i,RY_i,BX_i,BY_i \leq 10^9
* 1 \leq RC_i,BC_i \leq 10
* \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
RX_1 RY_1 RC_1
RX_2 RY_2 RC_2
\vdots
RX_N RY_N RC_N
BX_1 BY_1 BC_1
BX_2 BY_2 BC_2
\vdots
BX_N BY_N BC_N
Output
Print the maximum possible sum of the scores of the pairs.
Examples
Input
2
0 0 1
3 2 1
2 2 1
5 0 1
Output
8
Input
3
0 0 1
2 2 1
0 0 2
1 1 1
1 1 1
3 3 2
Output
16
Input
10
582463373 690528069 8
621230322 318051944 4
356524296 974059503 6
372751381 111542460 9
392867214 581476334 6
606955458 513028121 5
882201596 791660614 9
250465517 91918758 3
618624774 406956634 6
426294747 736401096 5
974896051 888765942 5
726682138 336960821 3
715144179 82444709 6
599055841 501257806 6
390484433 962747856 4
912334580 219343832 8
570458984 648862300 6
638017635 572157978 10
435958984 585073520 7
445612658 234265014 6
Output
45152033546 | instruction | 0 | 54,594 | 16 | 109,188 |
"Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
N_ = 2 * N + 6
N1, N2, N3, N4, N5 = range(N + 1, N + 6)
G = [[] for i in range(2 * N + 6)]
INF = 10 ** 12
def add_edge(fr, to, cap, cost) :
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr]) - 1])
def flow(s, t, f) :
ret = 0
pre_v = [0] * N_
pre_e = [0] * N_
while f :
dist = [INF] * N_
dist[s] = 0
que = deque([s])
updated = [False] * N_
updated[s] = True
while que :
v = que.popleft()
if not updated[v] :
continue
updated[v] = False
for i, (w, cap, cost, _) in enumerate(G[v]) :
if cap > 0 and dist[w] > dist[v] + cost:
dist[w] = dist[v] + cost
pre_v[w], pre_e[w] = v, i
que.append(w)
updated[w] = True
d, v = f, t
while v != s :
d = min(d, G[pre_v[v]][pre_e[v]][1])
v = pre_v[v]
f -= d
ret += d * dist[t]
v = t
while v != s :
e = G[pre_v[v]][pre_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = pre_v[v]
return ret
S = 0
for i in range(1, N + 1) :
Rx, Ry, Rc = map(int, input().split())
add_edge(0, i, Rc, 0)
add_edge(i, N1, INF, -Rx - Ry)
add_edge(i, N2, INF, Rx - Ry)
add_edge(i, N3, INF, -Rx + Ry)
add_edge(i, N4, INF, Rx + Ry)
S += Rc
for i in range(N5, N_ - 1) :
Bx, By, Bc = map(int, input().split())
add_edge(N1, i, INF, Bx + By)
add_edge(N2, i, INF, -Bx + By)
add_edge(N3, i, INF, Bx - By)
add_edge(N4, i, INF, -Bx - By)
add_edge(i, N_ - 1, Bc, 0)
print(-flow(0, N_ - 1, S))
``` | output | 1 | 54,594 | 16 | 109,189 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke is playing with red and blue balls, placing them on a two-dimensional plane.
First, he performed N operations to place red balls. In the i-th of these operations, he placed RC_i red balls at coordinates (RX_i,RY_i). Then, he performed another N operations to place blue balls. In the i-th of these operations, he placed BC_i blue balls at coordinates (BX_i,BY_i). The total number of red balls placed and the total number of blue balls placed are equal, that is, \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i. Let this value be S.
Snuke will now form S pairs of red and blue balls so that every ball belongs to exactly one pair. Let us define the score of a pair of a red ball at coordinates (rx, ry) and a blue ball at coordinates (bx, by) as |rx-bx| + |ry-by|.
Snuke wants to maximize the sum of the scores of the pairs. Help him by finding the maximum possible sum of the scores of the pairs.
Constraints
* 1 \leq N \leq 1000
* 0 \leq RX_i,RY_i,BX_i,BY_i \leq 10^9
* 1 \leq RC_i,BC_i \leq 10
* \sum_{i=1}^{N} RC_i = \sum_{i=1}^{N} BC_i
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
RX_1 RY_1 RC_1
RX_2 RY_2 RC_2
\vdots
RX_N RY_N RC_N
BX_1 BY_1 BC_1
BX_2 BY_2 BC_2
\vdots
BX_N BY_N BC_N
Output
Print the maximum possible sum of the scores of the pairs.
Examples
Input
2
0 0 1
3 2 1
2 2 1
5 0 1
Output
8
Input
3
0 0 1
2 2 1
0 0 2
1 1 1
1 1 1
3 3 2
Output
16
Input
10
582463373 690528069 8
621230322 318051944 4
356524296 974059503 6
372751381 111542460 9
392867214 581476334 6
606955458 513028121 5
882201596 791660614 9
250465517 91918758 3
618624774 406956634 6
426294747 736401096 5
974896051 888765942 5
726682138 336960821 3
715144179 82444709 6
599055841 501257806 6
390484433 962747856 4
912334580 219343832 8
570458984 648862300 6
638017635 572157978 10
435958984 585073520 7
445612658 234265014 6
Output
45152033546 | instruction | 0 | 54,595 | 16 | 109,190 |
"Correct Solution:
```
def main():
import sys
input=sys.stdin.readline
from collections import deque
inf=10**12
class MinCostFlow:
def __init__(self,n):
self.n=n
self.edges=[[] for i in range(n)]
def add_edge(self,fr,to,cap,cost):
self.edges[fr].append([to,cap,cost,len(self.edges[to])])
self.edges[to].append([fr,0,-cost,len(self.edges[fr])-1])
def MinCost(self,source,sink,flow):
n=self.n; E=self.edges
mincost=0
prev_v=[0]*n; prev_e=[0]*n
while flow:
dist=[inf]*n
dist[source]=0
q=deque([source])
Flag=[False] *n
Flag[source]=True
while q:
v=q.popleft()
if not Flag[v] :
continue
Flag[v]=False
for i,(w,cap,cost,_) in enumerate(E[v]):
if cap>0 and dist[w]>dist[v]+cost:
dist[w]=dist[v]+cost
prev_v[w],prev_e[w]=v,i
q.append(w)
Flag[w]=True
d,v=flow,sink
while v!=source:
d=min(d,E[prev_v[v]][prev_e[v]][1])
v=prev_v[v]
flow-=d
mincost+=d*dist[sink]
v=sink
while v!=source:
e=E[prev_v[v]][prev_e[v]]
e[1]-=d
E[v][e[3]][1]+=d
v=prev_v[v]
return mincost
n=int(input())
flow=MinCostFlow(2*n+6)
s=0
for i in range(n):
rx,ry,rc=map(int,input().split())
s+=rc
flow.add_edge(0,i+1,rc,0)
flow.add_edge(i+1,n+1,inf,-rx-ry)
flow.add_edge(i+1,n+2,inf,rx-ry)
flow.add_edge(i+1,n+3,inf,-rx+ry)
flow.add_edge(i+1,n+4,inf,rx+ry)
for i in range(n):
bx,by,bc=map(int,input().split())
flow.add_edge(n+5+i,2*n+5,bc,0)
flow.add_edge(n+1,n+5+i,inf,bx+by)
flow.add_edge(n+2,n+5+i,inf,-bx+by)
flow.add_edge(n+3,n+5+i,inf,bx-by)
flow.add_edge(n+4,n+5+i,inf,-bx-by)
print(-(flow.MinCost(0,2*n+5,s)))
if __name__=='__main__':
main()
``` | output | 1 | 54,595 | 16 | 109,191 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.