message
stringlengths
2
433k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
113
108k
cluster
float64
12
12
__index_level_0__
int64
226
217k
Provide tags and a correct Python 3 solution for this coding contest problem. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
instruction
0
88,546
12
177,092
Tags: brute force, constructive algorithms, data structures, greedy, implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) segs = [tuple(sorted(int(x) for x in input().split()[1:])) for __ in range(n - 1)] segs_set = set(segs) segs_having = [[j for j, seg in enumerate(segs) if i in seg] for i in range(n + 1)] unsorted = list(range(1, n + 1)) ans = [] def rb(avoid=0): if len(unsorted) > 1: candidate_lasts = [i for i in unsorted if len(segs_having[i]) == 1 and i != avoid] for last in candidate_lasts: seg_to_remove = segs_having[last][0] for ii in segs[seg_to_remove]: segs_having[ii].remove(seg_to_remove) unsorted.remove(last) ans.insert(0, last) if rb(avoid=next((i for i in candidate_lasts if i != last), avoid)): return True ans.pop(0) unsorted.append(last) for ii in segs[seg_to_remove]: segs_having[ii].append(seg_to_remove) return False else: ans.insert(0, unsorted[0]) valid = all(any(tuple(sorted(ans[j:i])) in segs_set for j in range(0, i - 1)) for i in range(2, n + 1)) if not valid: ans.pop(0) return valid rb() print(*ans) ```
output
1
88,546
12
177,093
Provide tags and a correct Python 3 solution for this coding contest problem. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
instruction
0
88,547
12
177,094
Tags: brute force, constructive algorithms, data structures, greedy, implementation Correct Solution: ``` import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LI1(): return list(map(int1, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): def ok(): if len(ans)<n:return False for r,si in enumerate(sii,2): s=ss[si] cur=set(ans[r-len(s):r]) if s!=cur:return False return True for _ in range(II()): n=II() ee=[[n**2]*n for _ in range(n)] for ei in range(n):ee[ei][ei]=0 ss=[set(LI()[1:]) for _ in range(n-1)] for a0 in range(1,n+1): used=set([a0]) ans=[a0] sii=[] for _ in range(n-1): nxt=[] for si,s in enumerate(ss): cur=s-used if len(cur)==1: for a in cur:nxt.append(a) sii.append(si) if len(nxt)!=1:break ans.append(nxt[0]) used.add(nxt[0]) if ok():break print(*ans) main() ```
output
1
88,547
12
177,095
Provide tags and a correct Python 3 solution for this coding contest problem. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
instruction
0
88,548
12
177,096
Tags: brute force, constructive algorithms, data structures, greedy, implementation Correct Solution: ``` if __name__== "__main__": t = int(input()) for _ in range(t): n = int(input()) ns = {} for _ in range(n - 1): _, *p = map(int, input().split()) tp = tuple(p) for pp in p: ns.setdefault(pp, set()).add(tp) first = [(k, list(v)[0]) for k, v in ns.items() if len(v) == 1] found = False while not found: nns = {k: v.copy() for k, v in ns.items()} min_index = {} cur, cur_tp = first.pop() result = [cur] failed = False while len(nns) > 0 and not failed: nxt = set() for k in cur_tp: mi = n - len(result) - len(cur_tp) + 1 min_index[k] = max(min_index.get(k, 0), mi) nsk = nns[k] nsk.remove(cur_tp) if k == cur: nns.pop(k) elif len(nsk) == 1: nxt.add(k) if len(nns) == len(nxt) or len(nns) == 1: break if len(nxt) == 0: failed = True else: mmi = -1 for nx in nxt: if min_index[nx] > mmi: mmi = min_index[nx] cur = nx cur_tp = list(nns[cur])[0] result.append(cur) if not failed: found = True if len(nns) == 1: result.append(nns.popitem()[0]) else: a1, a2 = nns.keys() if min_index[a1] == 1: result.extend((a1, a2)) else: result.extend((a2, a1)) print(" ".join(map(str, reversed(result)))) ```
output
1
88,548
12
177,097
Provide tags and a correct Python 3 solution for this coding contest problem. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
instruction
0
88,549
12
177,098
Tags: brute force, constructive algorithms, data structures, greedy, implementation Correct Solution: ``` from collections import Counter from itertools import chain def dfs(n, r, hint_sets, count, removed, result): # print(n, r, hint_sets, count, removed, result) if len(result) == n - 1: last = (set(range(1, n + 1)) - set(result)).pop() result.append(last) return True i, including_r = 0, None for i, including_r in enumerate(hint_sets): if i in removed: continue if r in including_r: break removed.add(i) next_r = [] for q in including_r: count[q] -= 1 if count[q] == 1: next_r.append(q) if not next_r: return False # print(r, next_r, result) if len(next_r) == 2: nr = -1 can1, can2 = next_r for h in hint_sets: if can1 in h and can2 not in h and not h.isdisjoint(result): nr = can1 break if can1 not in h and can2 in h and not h.isdisjoint(result): nr = can2 break if nr == -1: nr = can1 else: nr = next_r[0] result.append(nr) res = dfs(n, nr, hint_sets, count, removed, result) if res: return True result.pop() for q in including_r: count[q] += 1 return False t = int(input()) buf = [] for l in range(t): n = int(input()) hints = [] for _ in range(n - 1): k, *ppp = map(int, input().split()) hints.append(ppp) count = Counter(chain.from_iterable(hints)) most_common = count.most_common() hint_sets = list(map(set, hints)) r = most_common[-1][0] result = [r] if dfs(n, r, hint_sets, dict(count), set(), result): buf.append(' '.join(map(str, result[::-1]))) continue r = most_common[-2][0] result = [r] assert dfs(n, r, hint_sets, dict(count), set(), result) buf.append(' '.join(map(str, result[::-1]))) print('\n'.join(map(str, buf))) ```
output
1
88,549
12
177,099
Provide tags and a correct Python 3 solution for this coding contest problem. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1
instruction
0
88,550
12
177,100
Tags: brute force, constructive algorithms, data structures, greedy, implementation Correct Solution: ``` import sys input = sys.stdin.readline def dfs(x,S): #print(x,S) for i in range(len(S)): if x in S[i]: S[i].remove(x) #print(x,S) LEN1=0 for s in S: if len(s)==1: LEN1+=1 ne=list(s)[0] if LEN1==2: return [-1] if LEN1==1: return [ne]+dfs(ne,S) else: return [-1] import copy t=int(input()) for tests in range(t): n=int(input()) A=tuple(set(list(map(int,input().split()))[1:]) for i in range(n-1)) for i in range(1,n+1): ANS=[i]+dfs(i,copy.deepcopy(A)) #print(i,ANS) if -1 in ANS[:n]: continue else: #print(ANS[:n]) USE=[0]*(n-1) flag=1 for i in range(n-1,0,-1): SET=set() for j in range(i,-1,-1): SET.add(ANS[j]) if SET in A: break else: flag=0 break if flag: print(*ANS[:n]) break ```
output
1
88,550
12
177,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` import sys from copy import copy, deepcopy input = sys.stdin.readline ''' n, m = map(int, input().split()) n = int(input()) A = list(map(int, input().split())) S = input().strip() for tests in range(int(input())): ''' inf = 100000000000000000 # 1e17 mod = 998244353 ''' 1 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 ''' def check(): F = [0] * (n + 1) for i in range(len(ANS)): F[ANS[i]] = i isok = 1 for a in A: l = inf r = 0 for char in a: l = min(l, F[char]) r = max(r, F[char]) # print(a, l, r,isok) if r - l + 1 != len(a): isok = 0 break return isok def dfs(x, S): if x == n: # check # print(ANS) global flag if check()==1: if flag==0: flag=1 print(*ANS) # iter find for s in S: new_member = 0 for char in s: if char not in SET: if new_member == 0: new_member = char else: new_member = 0 break if new_member != 0: # get new one S.remove(s) SET.add(new_member) ANS.append(new_member) dfs(x + 1, S) for tests in range(int(input())): flag = 0 n = int(input()) A = list(list(map(int, input().split()))[1:] for i in range(n - 1)) for a in A: if len(a) == 2: ANS = [a[0], a[1]] S = deepcopy(A) S.remove(a) SET = set() SET.add(a[0]) SET.add(a[1]) dfs(2, S) S = deepcopy(A) S.remove(a) ANS = [a[1], a[0]] SET = set() SET.add(a[0]) SET.add(a[1]) dfs(2, S) ```
instruction
0
88,551
12
177,102
Yes
output
1
88,551
12
177,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` from sys import stdin, gettrace from copy import deepcopy if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): def solve(): n = int(input()) segs = [] occur = [set() for _ in range(n+1)] for j in range(n-1): seg = frozenset(int(a) for a in input().split()[1:]) for i in seg: occur[i].add(seg) pl = [] for i in range(1, n+1): if len(occur[i]) == 1: pl.append(i) for p in pl: occurc = deepcopy(occur) res = [0] * n pos = n-1 sum = (n * (n+1))//2 while True: sum -= p res[pos] = p if pos == 1: res[0] = sum print(' '.join(map(str, res))) return np = [] for seg in occurc[p]: for i in seg: if i == p: continue occurc[i].remove(seg) if len(occurc[i]) == 1: np.append(i) occurc[p].remove(seg) if len(np) == 1: p = np[0] elif len(np) == 2: if len(occur[np[0]]) > len(occur[np[1]]): p = np[0] else: p = np[1] else: break pos -= 1 q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main() ```
instruction
0
88,552
12
177,104
Yes
output
1
88,552
12
177,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` for _ in range(int(input())): n = int(input()) segs = [tuple(sorted(int(x) for x in input().split()[1:])) for __ in range(n - 1)] segs_having = [[j for j, seg in enumerate(segs) if i in seg] for i in range(n + 1)] segs_set = set(segs) for first in range(1, n + 1): try: segs_copy = [set(seg) for seg in segs] ans = [first] while len(ans) < n: for seg in segs_having[ans[-1]]: segs_copy[seg].remove(ans[-1]) ans.append(next(iter(next(seg for seg in segs_copy if len(seg) == 1)))) if all(any(tuple(sorted(ans[j:i])) in segs_set for j in range(0, i - 1)) for i in range(2, n + 1)): print(*ans) break except StopIteration: pass ```
instruction
0
88,553
12
177,106
Yes
output
1
88,553
12
177,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` from collections import defaultdict as dd from pprint import pprint as pp def solve(): n = int(input()) seqs = [] d = dd(list) for _ in range(n-1): seqs.append(list(map(int, input().split()[1:]))) for seq in seqs: for i in range(len(seq)): s = ' '.join(str(x) for j, x in enumerate(seq) if j != i) d[s].append(seq[i]) for st in range(1, n+1): seq = [st] seq_set = {st} for _ in range(n-1): found = False for l in range(len(seq)): k = ' '.join(str(x) for x in sorted(seq[-(l+1):])) if k in d: for j in d[k]: if j not in seq_set: seq.append(j) seq_set.add(j) found = True break if found: break if not found: break if len(seq) == n: print(' '.join(str(x) for x in seq)) break for _ in range(int(input())): solve() ```
instruction
0
88,554
12
177,108
Yes
output
1
88,554
12
177,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` import io import os from collections import defaultdict def solve(N, segments): memToSeg = defaultdict(set) for i, segment in enumerate(segments): for x in segment: memToSeg[x].add(i) ans = [] for i in range(N - 1): for k, indices in memToSeg.items(): if len(indices) == 1: (index,) = indices ans.append(k) for x in segments[index]: memToSeg[x].discard(index) if len(memToSeg[x]) == 0: del memToSeg[x] break else: assert False (unused,) = set(range(1, N + 1)) - set(ans) ans.append(unused) return " ".join(map(str, ans[::-1])) if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] segments = [] for i in range(N - 1): segment = [int(x) for x in input().split()] assert segment[0] == len(segment) - 1 segments.append(segment[1:]) ans = solve(N, segments) print(ans) ```
instruction
0
88,555
12
177,110
No
output
1
88,555
12
177,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` a=int(input()) for i in range(a): length=int(input()) k=[] for i in range(length-1): l=[int(i) for i in input().split(" ")] for i in range(1,len(l)): k.append(l[i]) s=set(k) t=list(s) for i in range(len(t)): print(t[i],end=" ") print("") ```
instruction
0
88,556
12
177,112
No
output
1
88,556
12
177,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` l=[] t=int(input()) for j in range(t): n=int(input()) for i in range(n-1): # print(i) m,*s=input().split(" ") s=list(map(int,s)) l.append(s) d=[i for j in l for i in j] print(list(set(d))) d,s,l=[],[],[] ```
instruction
0
88,557
12
177,114
No
output
1
88,557
12
177,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We guessed a permutation p consisting of n integers. The permutation of length n is the array of length n where each element from 1 to n appears exactly once. This permutation is a secret for you. For each position r from 2 to n we chose some other index l (l < r) and gave you the segment p_l, p_{l + 1}, ..., p_r in sorted order (i.e. we rearranged the elements of this segment in a way that the elements of this segment are sorted). Thus, you are given exactly n-1 segments of the initial permutation but elements inside each segment are sorted. The segments are given to you in random order. For example, if the secret permutation is p=[3, 1, 4, 6, 2, 5] then the possible given set of segments can be: * [2, 5, 6] * [4, 6] * [1, 3, 4] * [1, 3] * [1, 2, 4, 6] Your task is to find any suitable permutation (i.e. any permutation corresponding to the given input data). It is guaranteed that the input data corresponds to some permutation (i.e. such permutation exists). You have to answer t independent test cases. Input The first line of the input contains one integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (2 ≤ n ≤ 200) — the length of the permutation. The next n-1 lines describe given segments. The i-th line contains the description of the i-th segment. The line starts with the integer k_i (2 ≤ k_i ≤ n) — the length of the i-th segment. Then k_i integers follow. All integers in a line are distinct, sorted in ascending order, between 1 and n, inclusive. It is guaranteed that the required p exists for each test case. It is also guaranteed that the sum of n over all test cases does not exceed 200 (∑ n ≤ 200). Output For each test case, print the answer: n integers p_1, p_2, ..., p_n (1 ≤ p_i ≤ n, all p_i should be distinct) — any suitable permutation (i.e. any permutation corresponding to the test case input). Example Input 5 6 3 2 5 6 2 4 6 3 1 3 4 2 1 3 4 1 2 4 6 5 2 2 3 2 1 2 2 1 4 2 4 5 7 3 1 2 6 4 1 3 5 6 2 1 2 3 4 5 7 6 1 2 3 4 5 6 3 1 3 6 2 2 1 2 5 2 2 5 3 2 3 5 4 2 3 4 5 5 1 2 3 4 5 Output 3 1 4 6 2 5 3 2 1 4 5 2 1 6 3 5 4 7 1 2 2 5 3 4 1 Submitted Solution: ``` from sys import stdin, gettrace from copy import deepcopy if not gettrace(): def input(): return next(stdin)[:-1] # def input(): # return stdin.buffer.readline() def main(): def solve(): n = int(input()) segs = [] occur = [set() for _ in range(n+1)] for j in range(n-1): seg = frozenset(int(a) for a in input().split()[1:]) for i in seg: occur[i].add(seg) pl = [] for i in range(1, n+1): if len(occur[i]) == 1: pl.append(i) for p in pl: used = [False] * (n+1) occurc = deepcopy(occur) res = [0] * n pos = n-1 while True: used[p] = True if pos == 1: for r in range(1, n+1): if not used[r]: break if len(occur[p]) > len(occur[r]): res[0] = r res[1] = p else: res[0] = p res[1] = r print(' '.join(map(str, res))) return res[pos] = p np = -1 for seg in occurc[p]: for i in seg: if i == p: continue occurc[i].remove(seg) if len(occurc[i]) == 1: np = i occurc[p].remove(seg) if np == -1: break p = np pos -= 1 q = int(input()) for _ in range(q): solve() if __name__ == "__main__": main() ```
instruction
0
88,558
12
177,116
No
output
1
88,558
12
177,117
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,559
12
177,118
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` from sys import stdin, gettrace if gettrace(): inputi = input else: def input(): return next(stdin)[:-1] def inputi(): return stdin.buffer.readline() def solve(): n = int(inputi()) aa = [] aa.append([0] + [int(a) for a in inputi().split()]) aa.append([0] + [int(a) for a in inputi().split()]) ndx = [[[] for _ in range(n+1)] for _ in range(2)] for i in range(n+1): ndx[0][aa[0][i]].append(i) ndx[1][aa[1][i]].append(i) res = set() for i in range(1, n+1): if len(ndx[0][i]) + len(ndx[1][i]) != 2: print(-1) return for r in range(2): if len(ndx[r][i]) == 2: swaps = [] nsc = [] for j in range(2): c = ndx[r][i][j] swaps.append([c]) nsc.append(1) v = aa[1-r][c] while len(ndx[1-r][v]) == 1: if len(ndx[r][v]) != 1: print(-1) return c = ndx[r][v][0] swaps[-1].append(c) nsc[-1] += -1 if c in res else 1 v = aa[1-r][c] swaps = swaps[0] if nsc[0] <= nsc[1] else swaps[1] for c in swaps: ndx[0][aa[0][c]].remove(c) ndx[1][aa[1][c]].remove(c) aa[0][c], aa[1][c] = aa[1][c], aa[0][c] ndx[0][aa[0][c]].append(c) ndx[1][aa[1][c]].append(c) if c in res: res.remove(c) else: res.add(c) print(len(res)) print(' '.join(map(str, res))) def main(): t = int(inputi()) for _ in range(t): solve() if __name__ == "__main__": main() ```
output
1
88,559
12
177,119
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,560
12
177,120
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` t = int(input()) Maxn = 210000 while t > 0: t -= 1 n = int(input()) a = input().split() b = input().split() a1 = [-1] * (n + 1) a2 = [-1] * (n + 1) b1 = [-1] * (n + 1) b2 = [-1] * (n + 1) for i in range(0, n): now = int(a[i]) if a1[now] == -1: a1[now] = i b1[now] = 1 else: a2[now] = i b2[now] = 1 now = int(b[i]) if a1[now] == -1: a1[now] = i b1[now] = 2 else: a2[now] = i b2[now] = 2 flag = 0 for i in range(1, n + 1): if a2[i] == -1: print("-1") flag = 1 break if flag: continue to = [] nxt = [] w = [] que = [] first = [-1] * (n + 1) col = [-1] * (n + 1) def add(u, v, wi): to.append(v) nxt.append(first[u]) w.append(wi) first[u] = len(to) - 1 to.append(u) nxt.append(first[v]) first[v] = len(to) - 1 w.append(wi) for i in range(1, n + 1): if a1[i] == a2[i]: continue elif b1[i] == b2[i]: add(a1[i], a2[i], 1) else: add(a1[i], a2[i], 0) ans = [] for i in range(0, n): if first[i] != -1 and col[i] == -1: col[i] = 0 que.append(i) q = [[i], []] while len(que): now = que.pop() cur = first[now] while cur != -1: if col[to[cur]] == -1: if w[cur] == 0: col[to[cur]] = col[now] else: col[to[cur]] = (col[now] + 1) % 2 q[col[to[cur]]].append(to[cur]) que.append(to[cur]) cur = nxt[cur] if len(q[0]) < len(q[1]): while len(q[0]): ans.append(q[0].pop() + 1) else: while len(q[1]): ans.append(q[1].pop() + 1) print(len(ans)) for i in ans: print(i, end=' ') print('') ```
output
1
88,560
12
177,121
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,561
12
177,122
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` import sys # range = xrange # input = raw_input inp = [int(x) for x in sys.stdin.read().split()] ii = 0 out = [] def solve(n, A): same = [-1]*(2 * n);pos = [-1] * n for i in range(2 * n): a = A[i] if pos[a] == -1: pos[a] = i elif pos[a] == -2: return None else: p = pos[a] pos[a] = -2 same[p] = i same[i] = p ans = [] found = [0] * (2 * n) for root in range(2 * n): if found[root]: continue count0 = [] count1 = [] node = root while not found[node]: found[node] = 1 found[same[node]] = 1 if node & 1: count0.append(node >> 1) else: count1.append(node >> 1) node = same[node ^ 1] if len(count0) < len(count1): ans += count0 else: ans += count1 return ans t = inp[ii] ii += 1 for _ in range(t): n = inp[ii] ii += 1 A = [x - 1 for x in inp[ii: ii + n]] ii += n B = [x - 1 for x in inp[ii: ii + n]] ii += n A = [A[i >> 1] if i & 1 == 0 else B[i >> 1] for i in range(2 * n)] ans = solve(n, A) if ans is None: out.append('-1') else: out.append(str(len(ans))) out.append(' '.join(str(x + 1) for x in ans)) print('\n'.join(out)) ```
output
1
88,561
12
177,123
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,562
12
177,124
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` from sys import stdin, setrecursionlimit from collections import deque input = stdin.readline setrecursionlimit(int(2e5)) def getstr(): return input()[:-1] def getint(): return int(input()) def getints(): return list(map(int, input().split())) def getint1(): return list(map(lambda x : int(x) - 1, input().split())) adj = col = comp = [] cnt0 = cnt1 = 0 def dfs(us, cs, cmp, n): global adj, col, comp, cnt0, cnt1 stack = [(us, cs)] inq = [False] * n inq[us] = True while len(stack) > 0: u, c = stack.pop() # print(u, c) inq[u] = False col[u] = c if col[u] == 0: cnt0 += 1 else: cnt1 += 1 comp[u] = cmp for v, ch in adj[u]: if col[v] == -1 and not inq[v]: inq[v] = True stack.append((v, c ^ ch)) # print(col, comp) def solve(): global adj, col, comp, cnt0, cnt1 n = getint() a = [] pos = [[] for _ in range(n)] adj = [[] for _ in range(n)] for i in [0, 1]: a.append(getint1()) for j, x in enumerate(a[i]): pos[x].append(j) for i, c in enumerate(pos): if len(c) != 2: print("-1") return if c[0] == c[1]: continue r1 = int(a[0][c[0]] != i) r2 = int(a[0][c[1]] != i) adj[c[0]].append((c[1], int(r1 == r2))) adj[c[1]].append((c[0], int(r1 == r2))) # print(adj) col = [-1] * n comp = [-1] * n colcnt = [] ans = cnt = 0 # cnt = 0 for i in range(n): if col[i] == -1: cnt0, cnt1 = 0, 0 dfs(i, 0, cnt, n) cnt += 1 colcnt.append((cnt0, cnt1)) ans += min(cnt0, cnt1) # print(colcnt) print(ans) alist = [] for i in range(n): chz = int(colcnt[comp[i]][0] < colcnt[comp[i]][1]) if col[i] ^ chz: alist.append(i + 1) # print(len(alist)) print(*alist) if __name__ == "__main__": # solve() # for t in range(getint()): # print("Case #{}: ".format(t + 1), end="") # solve() for _ in range(getint()): solve() ```
output
1
88,562
12
177,125
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,563
12
177,126
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 for t in range(int(data())): n=int(data()) a1=mdata() a2=mdata() d=dd(int) g=[[] for i in range(n+1)] for i in range(n): d[a1[i]] += 1 d[a2[i]] += 1 if a1[i]==a2[i]: continue g[a1[i]].append((a2[i],i+1,0)) g[a2[i]].append((a1[i],i+1,1)) if max(d.values())>2: out(-1) continue vis=[0]*(n+1) vis1=[0]*(n+1) ans=[] for i in range(1,n+1): if vis[i]==0 and g[i]: s=[[],[]] vis[i]=1 s[g[i][0][2]].append(g[i][0][1]) s[1-g[i][1][2]].append(g[i][1][1]) vis[g[i][0][0]] = -1 vis[g[i][1][0]] = 1 vis1[g[i][0][1]] = 1 vis1[g[i][1][1]] = 1 q=[] q.append(g[i][0][0]) q.append(g[i][1][0]) while q: a=q.pop() if vis[a]==1: for nei in g[a]: if vis1[nei[1]]==0: s[1-nei[2]].append(nei[1]) vis[nei[0]] = -1 vis1[nei[1]] = 1 q.append(nei[0]) else: for nei in g[a]: if vis1[nei[1]]==0: s[1-nei[2]].append(nei[1]) vis[nei[0]] = 1 vis1[nei[1]] = 1 q.append(nei[0]) if len(s[0])<len(s[1]): ans+=s[0] else: ans+=s[1] out(len(ans)) outl(ans) ```
output
1
88,563
12
177,127
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,564
12
177,128
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` from collections import defaultdict,deque import sys input=sys.stdin.readline def bfs(i): queue=deque([(i,1)]) while queue: #print(queue) vertex,colour=queue.popleft() res.append(vertex) if colour==1: up,down=a[vertex],b[vertex] else: up,down=b[vertex],a[vertex] for child in graph[vertex]: if not vis[child]: vis[child]=True if a[child]==up or b[child]==down: tmp.append(child) queue.append((child,0)) else: queue.append((child,1)) t=int(input()) for ii in range(t): n=int(input()) a=[int(i) for i in input().split() if i!='\n'] b=[int(i) for i in input().split() if i!='\n'] data=[[] for _ in range(n)] for i in range(n): data[a[i]-1].append(i) data[b[i]-1].append(i) graph=defaultdict(list) for i in range(n): if len(data[i])!=2: print(-1) break else: for i in range(n): u,v=data[i][0],data[i][1] graph[u].append(v) graph[v].append(u) #print(graph,data) vis,ans=[False]*(n),[] for i in range(n): if not vis[i]: tmp,res=[],[] vis[i]=True bfs(i) if len(res)-len(tmp)>=len(tmp): ans+=tmp else: tmp=set(tmp) for i in res: if i not in tmp: ans.append(i) print(len(ans)) ans=[i+1 for i in ans] print(*ans) ```
output
1
88,564
12
177,129
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,565
12
177,130
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` import sys from collections import deque input=sys.stdin.readline #sys.setrecursionlimit(2*10**5) for _ in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) data=[[] for i in range(n)] for i in range(n): data[a[i]-1].append(i) data[b[i]-1].append(i) for i in range(n): if len(data[i])!=2: print(-1) break else: edge=[[] for i in range(n)] for i in range(n): u,v=data[i][0],data[i][1] edge[u].append((v,i)) edge[v].append((u,i)) seen=[False]*n temp=[] res=0 def dfs(v,cond): global temp,res res.append(v) if cond==1: up,down=a[v],b[v] else: up,down=b[v],a[v] for nv,val in edge[v]: if not seen[nv]: seen[nv]=True if a[nv]==up or b[nv]==down: temp.append(nv) dfs(nv,-1) else: dfs(nv,1) def bfs(i): global temp,res deq=deque([(i,1)]) while deq: v,cond=deq.popleft() res.append(v) if cond==1: up,down=a[v],b[v] else: up,down=b[v],a[v] for nv,val in edge[v]: if not seen[nv]: seen[nv]=True if a[nv]==up or b[nv]==down: temp.append(nv) deq.append((nv,-1)) else: deq.append((nv,1)) ans=[] for i in range(0,n): if not seen[i]: res=[] temp=[] seen[i]=True bfs(i) if len(res)-len(temp)>=len(temp): ans+=temp else: temp=set(temp) for v in res: if v not in temp: ans.append(v) if ans: ans=[ans[i]+1 for i in range(len(ans))] print(len(ans)) print(*ans) ```
output
1
88,565
12
177,131
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1
instruction
0
88,566
12
177,132
Tags: 2-sat, dfs and similar, dsu, graphs, implementation Correct Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc farr=[1] ifa=[] def fact(x,mod=0): if mod: while x>=len(farr): farr.append(farr[-1]*len(farr)%mod) else: while x>=len(farr): farr.append(farr[-1]*len(farr)) return farr[x] def ifact(x,mod): global ifa ifa.append(pow(farr[-1],mod-2,mod)) for i in range(x,0,-1): ifa.append(ifa[-1]*i%mod) ifa=ifa[::-1] def per(i,j,mod=0): if i<j: return 0 if not mod: return fact(i)//fact(i-j) return farr[i]*ifa[i-j]%mod def com(i,j,mod=0): if i<j: return 0 if not mod: return per(i,j)//fact(j) return per(i,j,mod)*ifa[j]%mod def catalan(n): return com(2*n,n)//(n+1) def linc(f,t,l,r): while l<r: mid=(l+r)//2 if t>f(mid): l=mid+1 else: r=mid return l def rinc(f,t,l,r): while l<r: mid=(l+r+1)//2 if t<f(mid): r=mid-1 else: l=mid return l def ldec(f,t,l,r): while l<r: mid=(l+r)//2 if t<f(mid): l=mid+1 else: r=mid return l def rdec(f,t,l,r): while l<r: mid=(l+r+1)//2 if t>f(mid): r=mid-1 else: l=mid return l def isprime(n): for i in range(2,int(n**0.5)+1): if n%i==0: return False return True def binfun(x): c=0 for w in arr: c+=ceil(w/x) return c def lowbit(n): return n&-n def inverse(a,m): a%=m if a<=1: return a return ((1-inverse(m,a)*m)//a)%m class BIT: def __init__(self,arr): self.arr=arr self.n=len(arr)-1 def update(self,x,v): while x<=self.n: self.arr[x]+=v x+=x&-x def query(self,x): ans=0 while x: ans+=self.arr[x] x&=x-1 return ans ''' class SMT: def __init__(self,arr): self.n=len(arr)-1 self.arr=[0]*(self.n<<2) self.lazy=[0]*(self.n<<2) def Build(l,r,rt): if l==r: self.arr[rt]=arr[l] return m=(l+r)>>1 Build(l,m,rt<<1) Build(m+1,r,rt<<1|1) self.pushup(rt) Build(1,self.n,1) def pushup(self,rt): self.arr[rt]=self.arr[rt<<1]+self.arr[rt<<1|1] def pushdown(self,rt,ln,rn):#lr,rn表区间数字数 if self.lazy[rt]: self.lazy[rt<<1]+=self.lazy[rt] self.lazy[rt<<1|1]=self.lazy[rt] self.arr[rt<<1]+=self.lazy[rt]*ln self.arr[rt<<1|1]+=self.lazy[rt]*rn self.lazy[rt]=0 def update(self,L,R,c,l=1,r=None,rt=1):#L,R表示操作区间 if r==None: r=self.n if L<=l and r<=R: self.arr[rt]+=c*(r-l+1) self.lazy[rt]+=c return m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) if L<=m: self.update(L,R,c,l,m,rt<<1) if R>m: self.update(L,R,c,m+1,r,rt<<1|1) self.pushup(rt) def query(self,L,R,l=1,r=None,rt=1): if r==None: r=self.n #print(L,R,l,r,rt) if L<=l and R>=r: return self.arr[rt] m=(l+r)>>1 self.pushdown(rt,m-l+1,r-m) ans=0 if L<=m: ans+=self.query(L,R,l,m,rt<<1) if R>m: ans+=self.query(L,R,m+1,r,rt<<1|1) return ans ''' class DSU:#容量+路径压缩 def __init__(self,n): self.c=[-1]*n def same(self,x,y): return self.find(x)==self.find(y) def find(self,x): if self.c[x]<0: return x self.c[x]=self.find(self.c[x]) return self.c[x] def union(self,u,v): u,v=self.find(u),self.find(v) if u==v: return False if self.c[u]<self.c[v]: u,v=v,u self.c[u]+=self.c[v] self.c[v]=u return True def size(self,x): return -self.c[self.find(x)] class UFS:#秩+路径 def __init__(self,n): self.parent=[i for i in range(n)] self.ranks=[0]*n def find(self,x): if x!=self.parent[x]: self.parent[x]=self.find(self.parent[x]) return self.parent[x] def union(self,u,v): pu,pv=self.find(u),self.find(v) if pu==pv: return False if self.ranks[pu]>=self.ranks[pv]: self.parent[pv]=pu if self.ranks[pv]==self.ranks[pu]: self.ranks[pu]+=1 else: self.parent[pu]=pv def Prime(n): c=0 prime=[] flag=[0]*(n+1) for i in range(2,n+1): if not flag[i]: prime.append(i) c+=1 for j in range(c): if i*prime[j]>n: break flag[i*prime[j]]=prime[j] if i%prime[j]==0: break return prime def dij(s,graph): d={} d[s]=0 heap=[(0,s)] seen=set() while heap: dis,u=heappop(heap) if u in seen: continue for v in graph[u]: if v not in d or d[v]>d[u]+graph[u][v]: d[v]=d[u]+graph[u][v] heappush(heap,(d[v],v)) return d def GP(it): return [[ch,len(list(g))] for ch,g in groupby(it)] class DLN: def __init__(self,val): self.val=val self.pre=None self.next=None @bootstrap def dfs(r,p): if len(g[r])==1 and p!=-1: isl[r]=1 yield 1 tmp=0 for ch in g[r]: if ch!=p: tmp+=yield(dfs(ch,r)) cnt[r]+=tmp if p==-1 and len(g[r])==1: isl[r]=1 cnt[g[r][0]]+=1 yield 0 t=N() for i in range(t): n=N() a=RLL() b=RLL() c=Counter(a)+Counter(b) if any(c[i]!=2 for i in range(1,n+1)): print(-1) else: fi={} se={} for i in range(n): if a[i] not in fi: fi[a[i]]=i else: se[a[i]]=i if b[i] not in fi: fi[b[i]]=i else: se[b[i]]=i #vis=[0]*(1+n) uf=UFS(n+1) ans=0 res=[] g=[[] for i in range(1+n)] for i in range(1,n+1): if fi[i]!=se[i]: uf.union(fi[i],se[i]) for i in range(n): g[uf.find(i)].append(i) for i in range(n): if len(g[i])<2: continue rem=[g[i][0]+1] inv=[] ind=g[i][0] cur=b[ind] while cur!=a[g[i][0]]: for j in (fi[cur],se[cur]): if j!=ind: if a[j]==cur: rem.append(j+1) cur=b[j] else: inv.append(j+1) cur=a[j] ind=j break if len(rem)<=len(inv): res+=rem ans+=len(rem) else: res+=inv ans+=len(inv) print(ans) print(*res) ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ''' sys.setrecursionlimit(200000) import threading threading.stack_size(10**8) t=threading.Thread(target=main) t.start() t.join() ''' ```
output
1
88,566
12
177,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) mod = 998244353 INF = float('inf') from math import factorial from collections import Counter, defaultdict, deque from heapq import heapify, heappop, heappush from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc # ------------------------------ # f = open('../input.txt') # sys.stdin = f def main(): for _ in range(N()): n = N() arra = RLL() arrb = RLL() rec = [0]*(n+1) prec = [[] for _ in range(n+1)] for i in range(n): rec[arra[i]]+=1 rec[arrb[i]]+=1 prec[arra[i]].append(i) prec[arrb[i]].append(i) for i in range(1, n+1): if rec[i]!=2: print(-1) break else: res, reca, recb = [], [], [] vis = [0]*(n+1) @bootstrap def dfs(node, pos): nonlocal reca, recb, vis if vis[node] == 1: yield None vis[node] = 1 for p in prec[node]: if p==pos: continue if arra[p]==node: reca.append(p) yield dfs(arrb[p], p) else: recb.append(p) yield dfs(arra[p], p) yield None yield None for i in range(1, n+1): if vis[i] or prec[0]==prec[1]: continue dfs(i, 0) if len(reca)>len(recb): res.extend(recb) else: res.extend(reca) reca.clear() recb.clear() print(len(res)) print(*[i+1 for i in res]) if __name__ == "__main__": main() ```
instruction
0
88,567
12
177,134
Yes
output
1
88,567
12
177,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` import sys, math import io, os #data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline from bisect import bisect_left as bl, bisect_right as br, insort from heapq import heapify, heappush, heappop from collections import defaultdict as dd, deque, Counter #from itertools import permutations,combinations def data(): return sys.stdin.readline().strip() def mdata(): return list(map(int, data().split())) def outl(var) : sys.stdout.write(' '.join(map(str, var))+'\n') def out(var) : sys.stdout.write(str(var)+'\n') #from decimal import Decimal from fractions import Fraction #sys.setrecursionlimit(100000) INF = float('inf') mod = int(1e9)+7 for t in range(int(data())): n=int(data()) a1=mdata() a2=mdata() d=dd(int) g=[[] for i in range(n+1)] for i in range(n): d[a1[i]] += 1 d[a2[i]] += 1 if a1[i]==a2[i]: continue g[a1[i]].append((a2[i],i+1,0)) g[a2[i]].append((a1[i],i+1,1)) if max(d.values())>2: out(-1) continue vis=[0]*(n+1) vis1=[0]*(n+1) ans=[] for i in range(1,n+1): if vis[i]==0 and g[i]: s=[[],[]] vis[i]=1 a,b=g[i][0],g[i][1] s[a[2]].append(a[1]) s[1-b[2]].append(b[1]) vis[a[0]] = -1 vis[b[0]] = 1 vis1[a[1]] = 1 vis1[b[1]] = 1 q=[] q.append(g[i][0][0]) q.append(g[i][1][0]) while q: a=q.pop() for nei in g[a]: if vis1[nei[1]]==0: s[1-nei[2]].append(nei[1]) vis[nei[0]] = -1*vis[a] vis1[nei[1]] = 1 q.append(nei[0]) if len(s[0])<len(s[1]): ans+=s[0] else: ans+=s[1] out(len(ans)) outl(ans) ```
instruction
0
88,568
12
177,136
Yes
output
1
88,568
12
177,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` for t in range(int(input())): n = int(input()) aa = [ [int(s)-1 for s in input().split(' ')] for _ in [0, 1] ] maxv = max(max(aa[0]), max(aa[1])) minv = min(min(aa[0]), min(aa[1])) if minv != 0 or maxv != n - 1: print(-1) continue counts = [0] * n index = [[] for _ in range(n)] for row in aa: for x, a in enumerate(row): counts[a] += 1 index[a] += [x] if not min(counts) == 2 == max(counts): print(-1) continue proc = [False] * n ans = [] for i in range(n): if proc[i]: continue swapped = set() used = set() curcol = i curval = aa[0][i] while True: proc[curcol] = True used.add(curcol) if aa[0][curcol] == curval: nexval = aa[1][curcol] else: nexval = aa[0][curcol] swapped.add(curcol) nexcol = index[nexval][1] if index[nexval][0] == curcol else index[nexval][0] curcol = nexcol curval = nexval if curcol == i: break part = swapped if 2 * len(swapped) <= len(used) else used.difference(swapped) ans += part print(len(ans)) print(' '.join(str(v + 1) for v in ans)) ```
instruction
0
88,569
12
177,138
Yes
output
1
88,569
12
177,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` import io import os from collections import Counter, defaultdict, deque def bfs(source, getNbr): q = deque([source]) dist = {source: 0} while q: node = q.popleft() d = dist[node] for nbr in getNbr(node): if nbr not in dist: q.append(nbr) dist[nbr] = d + 1 return dist def solve(N, A1, A2): A = A1 + A2 # index bottom row with N to 2N - 1 # Put edge for any two cells that have to be on opposite sides graph = [[] for i in range(2 * N)] # Put edge between same column for i in range(N): if A[i] != A[i + N]: # Skip columns with same values which is handled below graph[i].append(i + N) graph[i + N].append(i) # Put edge between same value valToCols = defaultdict(list) for i, x in enumerate(A): valToCols[x].append(i) for x in range(1, N + 1): if len(valToCols[x]) != 2: return -1 i, j = valToCols[x] graph[i].append(j) graph[j].append(i) def getNbr(u): return graph[u] # Two color ans = [] seen = {} for source in range(2 * N): if source not in seen: dist = bfs(source, getNbr) for u in dist.keys(): color = dist[u] % 2 for v in graph[u]: color2 = dist[v] % 2 if color == color2: # conflict return -1 # The components can flip, choose smaller cols1 = [u for u in dist.keys() if u < N and dist[u] % 2 == 0] cols2 = [u for u in dist.keys() if u < N and dist[u] % 2 == 1] if len(cols1) < len(cols2): ans.extend(cols1) else: ans.extend(cols2) seen.update(dist) return str(len(ans)) + "\n" + " ".join(str(c + 1) for c in ans) if False: # print(solve(5, [1, 1, 2, 3, 4], [2, 3, 4, 5, 5])) import random random.seed(0) from itertools import combinations, product for t in range(10000): N = 5 for perm1 in product(range(1, N + 1), repeat=N): for perm2 in product(range(1, N + 1), repeat=N): best = float("inf") for mask in range(1 << N): p1 = list(perm1) p2 = list(perm2) for i in range(N): if mask & (1 << i): p1[i], p2[i] = p2[i], p1[i] if sorted(p1) == sorted(p2) == sorted(range(1, N + 1)): best = min(best, bin(mask).count("1")) if best == float("inf"): best = -1 ans = int(str(solve(N, perm1, perm2)).split("\n")[0]) if ans != best: print(perm1, perm2, best, ans) exit() if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline T = int(input()) for t in range(T): (N,) = [int(x) for x in input().split()] A1 = [int(x) for x in input().split()] A2 = [int(x) for x in input().split()] ans = solve(N, A1, A2) print(ans) ```
instruction
0
88,570
12
177,140
Yes
output
1
88,570
12
177,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` #list(map(int,input().split())) ```
instruction
0
88,571
12
177,142
No
output
1
88,571
12
177,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` from collections import Counter for _ in range(int(input())): n = int(input()) A = list(map(int, input().split())) B = list(map(int, input().split())) C = Counter(A + B) if any(v > 2 for v in C.values()): print(-1) continue adj = [set() for _ in range(n)] for l in (A, B): D = {} for i, v in enumerate(l): if v in D: j = D[v] adj[i].add(j) adj[j].add(i) else: D[v] = i R = [] V = [False] * n for i in range(n): if V[i]: continue V[i] = True use = len(adj[i]) == 2 Q = [(i, use)] for i, use in Q: if use: R.append(i+1) for j in adj[i]: if V[j]: continue V[j] = True Q.append((j, not use)) print(len(R)) print(*R) ```
instruction
0
88,572
12
177,144
No
output
1
88,572
12
177,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` from collections import Counter for iota in range(int(input())): n=int(input()) a=list(map(int,input().split())) b=list(map(int,input().split())) temp=a[:]+b[:] count=Counter(temp) ans=0 for i in range(n): if count[n]%2==1: ans=-1 break if ans==-1: print(ans) continue anslist=[] temp=a[:] for i in range(n): if a[i]==b[i]: continue if (b[i] not in temp) and ((temp[i] in (temp[:i]+temp[i+1:]))or (temp[i] in b[i+1:])): temp[i],b[i]=b[i],temp[i] ans+=1 anslist.append(i+1) print(ans) print(*anslist) ```
instruction
0
88,573
12
177,146
No
output
1
88,573
12
177,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a table a of size 2 × n (i.e. two rows and n columns) consisting of integers from 1 to n. In one move, you can choose some column j (1 ≤ j ≤ n) and swap values a_{1, j} and a_{2, j} in it. Each column can be chosen no more than once. Your task is to find the minimum number of moves required to obtain permutations of size n in both first and second rows of the table or determine if it is impossible to do that. You have to answer t independent test cases. Recall that the permutation of size n is such an array of size n that contains each integer from 1 to n exactly once (the order of elements doesn't matter). Input The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow. The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of columns in the table. The second line of the test case contains n integers a_{1, 1}, a_{1, 2}, ..., a_{1, n} (1 ≤ a_{1, i} ≤ n), where a_{1, i} is the i-th element of the first row of the table. The third line of the test case contains n integers a_{2, 1}, a_{2, 2}, ..., a_{2, n} (1 ≤ a_{2, i} ≤ n), where a_{2, i} is the i-th element of the second row of the table. It is guaranteed that the sum of n does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5). Output For each test case print the answer: -1 if it is impossible to obtain permutation of size n in both first and the second rows of the table, or one integer k in the first line, where k is the minimum number of moves required to obtain permutations in both rows, and k distinct integers pos_1, pos_2, ..., pos_k in the second line (1 ≤ pos_i ≤ n) in any order — indices of columns in which you need to swap values to obtain permutations in both rows. If there are several answers, you can print any. Example Input 6 4 1 2 3 4 2 3 1 4 5 5 3 5 1 4 1 2 3 2 4 3 1 2 1 3 3 2 4 1 2 2 1 3 4 3 4 4 4 3 1 4 3 2 2 1 3 1 1 2 3 2 2 Output 0 2 2 3 1 1 2 3 4 2 3 4 -1 Submitted Solution: ``` import collections def last(x,y): s1=collections.Counter(x) s2=collections.Counter(y) n=len(x) s=[] count=0 res=[] for i in range(1,n+1): s.append(i) s=collections.Counter(s) for i in range(n): if s1==s: if s2==s: print(count) if res: for i in res: print(i, " ", end='') print() return else: print(-1) return if s2==s: if s1==s: print(count) if res: for i in res: print(i, " ", end='') print() return else: print(-1) return if s1[y[i]]!=0 and s2[x[i]]!=0: continue if s1[y[i]]==0 or s2[x[i]]!=0: res.append(i) count+=1 s1[x[i]]-=1 s1[y[i]]+=1 s2[y[i]]-=1 s2[x[i]]+=1 print(count) if res: for i in res: print(i," ",end='') print() t=int(input()) for i in range(t): n=int(input()) x=[int(i) for i in input().split()][:n] y=[int(i) for i in input().split()][:n] last(x,y) ```
instruction
0
88,574
12
177,148
No
output
1
88,574
12
177,149
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,639
12
177,278
Tags: brute force, hashing, implementation, math Correct Solution: ``` import sys from collections import defaultdict r=sys.stdin.readline n = int(input()) a = list(map(int, r().split())) d = {} for i in range(n): for j in range(i): # print(d) if(a[i]+a[j] in d): ii,jj = d[a[i]+a[j]] if(len(set([i,j,ii,jj]))==4): print('YES') print(i+1,j+1,ii+1,jj+1) exit(0) else: d[a[i]+a[j]] = (i,j) print('NO') ```
output
1
88,639
12
177,279
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,640
12
177,280
Tags: brute force, hashing, implementation, math Correct Solution: ``` # -*- coding: utf-8 -*- """ Created on Tue Mar 23 16:06:25 2021 @author: PC-4 """ n = int(input()) A = list(map(int, input().split(" "))) def f(A, n): D = {} for j in range(n): for i in range(j): s = A[i] + A[j] if s in D: x, y = D[s] if not(i == x or i == y or j == y): print("YES") print(x + 1, y + 1, i + 1, j + 1) return D[s] = (i, j) print("NO") f(A, n) ```
output
1
88,640
12
177,281
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,641
12
177,282
Tags: brute force, hashing, implementation, math Correct Solution: ``` from collections import Counter n=int(input()) m=[int(j) for j in input().split()] m=m[:10000] new={} res=[] for i in range(len(m)): for j in range(i+1, len(m)): if m[i]+m[j] in new: if i not in new[m[i]+m[j]] and j not in new[m[i]+m[j]]: z=new[m[i]+m[j]][0] x=new[m[i]+m[j]][1] res.extend([i, j, z, x]) break else: continue else: new[m[i]+m[j]]=[i, j] else: continue break if res: print("YES") print(" ".join([str(e+1) for e in res])) else: print("NO") ```
output
1
88,641
12
177,283
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,642
12
177,284
Tags: brute force, hashing, implementation, math Correct Solution: ``` from collections import Counter n=int(input()) m=[int(j) for j in input().split()] m=m[:2000] new={} res=[] for i in range(len(m)): for j in range(i+1, len(m)): if m[i]+m[j] in new: if i not in new[m[i]+m[j]] and j not in new[m[i]+m[j]]: z=new[m[i]+m[j]][0] x=new[m[i]+m[j]][1] res.extend([i, j, z, x]) break else: continue else: new[m[i]+m[j]]=[i, j] else: continue break if res: print("YES") print(" ".join([str(e+1) for e in res])) else: print("NO") ```
output
1
88,642
12
177,285
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,643
12
177,286
Tags: brute force, hashing, implementation, math Correct Solution: ``` def main(): n = int(input()) arr = list(map(int, input().split(' '))) cache = {} for i in range(n): for j in range(i): s = arr[i] + arr[j] if s in cache: f, t = cache[s] if i!=f and i!=t and j!=f and t!=j: print("YES") print(f+1, t+1, i+1, j+1) return cache[s] = (i, j) print("NO") if __name__ == "__main__": main() ```
output
1
88,643
12
177,287
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,644
12
177,288
Tags: brute force, hashing, implementation, math Correct Solution: ``` import sys input = sys.stdin.readline from operator import itemgetter n=int(input()) A=list(map(int,input().split())) MAX=max(A)-min(A) COUNT=[[] for i in range(max(A)+1)] fl1=0 for i in range(n): COUNT[A[i]].append(i) if len(COUNT[A[i]])==4: print("YES") print(*[c+1 for c in COUNT[A[i]]]) exit() if len(COUNT[A[i]])==2: if fl1==0: fl1=A[i] else: print("YES") print(COUNT[fl1][0]+1,COUNT[A[i]][0]+1,COUNT[A[i]][1]+1,COUNT[fl1][1]+1) exit() X=[(A[i],i) for i in range(n)] SA=[[] for i in range(MAX+1)] for i in range(n): for j in range(i+1,n): sa=abs(X[j][0]-X[i][0]) for x,y in SA[sa]: if X[i][1]!=x and X[i][1]!=y and X[j][1]!=x and X[j][1]!=y: if X[i][0]<=X[j][0]: print("YES") print(X[i][1]+1,y+1,x+1,X[j][1]+1) exit() else: print("YES") print(X[j][1]+1,y+1,x+1,X[i][1]+1) exit() if X[i][0]<=X[j][0]: SA[sa].append((X[i][1],X[j][1])) else: SA[sa].append((X[j][1],X[i][1])) print("NO") ```
output
1
88,644
12
177,289
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,645
12
177,290
Tags: brute force, hashing, implementation, math Correct Solution: ``` n = int(input()) def solve(arr,n): #me = max(arr) #hms = [0 for _ in range(0,2*(me)+1)] #hmi = [[] for _ in range(0,2*(me)+1)] d = {} for i in range(n): for j in range(i): s = arr[i] + arr[j] if s not in d: d[s]=(i,j) else: ii,jj = d[s] if len(set([i,j,ii,jj]))==4: print('YES') print(ii+1,jj+1,i+1,j+1) return 1 print('NO') #arr = [int(a) for a in input().split(' ')] arr = list(map(int, input().split())) solve(arr,n) ```
output
1
88,645
12
177,291
Provide tags and a correct Python 3 solution for this coding contest problem. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3
instruction
0
88,646
12
177,292
Tags: brute force, hashing, implementation, math Correct Solution: ``` def sol(arr): s=dict() for i in range(min(4000,len(arr)-1)): for j in range(i+1,min(4001,len(arr))): key=arr[i]+arr[j] if key not in s: s[key]=i,j elif i not in s[key] and j not in s[key]: print("YES") print(s[key][0]+1,s[key][1]+1,i+1,j+1) return print("NO") input() sol([int(i) for i in input().split()]) ```
output
1
88,646
12
177,293
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` import sys import math import heapq import bisect from collections import Counter from collections import defaultdict from io import BytesIO, IOBase import string class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None self.BUFSIZE = 8192 def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, self.BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def get_int(): return int(input()) def get_ints(): return list(map(int, input().split(' '))) def get_int_grid(n): return [get_ints() for _ in range(n)] def get_str(): return input().split(' ') def yes_no(b): if b: return "YES" else: return "NO" def binary_search(good, left, right, delta=1, right_true=False): """ Performs binary search ---------- Parameters ---------- :param good: Function used to perform the binary search :param left: Starting value of left limit :param right: Starting value of the right limit :param delta: Margin of error, defaults value of 1 for integer binary search :param right_true: Boolean, for whether the right limit is the true invariant :return: Returns the most extremal value interval [left, right] which is good function evaluates to True, alternatively returns False if no such value found """ limits = [left, right] while limits[1] - limits[0] > delta: if delta == 1: mid = sum(limits) // 2 else: mid = sum(limits) / 2 if good(mid): limits[int(right_true)] = mid else: limits[int(~right_true)] = mid if good(limits[int(right_true)]): return limits[int(right_true)] else: return False def prefix_sums(a, drop_zero=False): p = [0] for x in a: p.append(p[-1] + x) if drop_zero: return p[1:] else: return p def prefix_mins(a, drop_zero=False): p = [float('inf')] for x in a: p.append(min(p[-1], x)) if drop_zero: return p[1:] else: return p def solve_a(): n = get_int() arr = [0] dep = [0] for _ in range(n): a, b = get_ints() arr.append(a) dep.append(b) delta = get_ints() departure = 0 for idx in range(1, n + 1): arrival = (arr[idx] - dep[idx - 1] + delta[idx - 1]) + departure departure = max(dep[idx], arrival + math.ceil((dep[idx] - arr[idx])/ 2)) return arrival def solve_b(): n = get_int() a = get_ints() retval = [0] * n idx = n - 1 min_fill = n while idx >= 0: if a[idx]: min_fill = min(min_fill, idx - a[idx] + 1) if min_fill <= idx: retval[idx] = 1 idx -= 1 return retval def solve_c(): n = get_int() arr = get_ints() sums = {} for i in range(n): for j in range(i): if arr[i] + arr[j] in sums: k, l = sums[arr[i] + arr[j]] if len(set([i, j, k, l])) == 4: return [i + 1, j + 1, k + 1, l + 1] sums[arr[i] + arr[j]] = (i, j) return False ans = solve_c() if ans: print("YES") print(*ans) else: print("NO") ```
instruction
0
88,649
12
177,298
Yes
output
1
88,649
12
177,299
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya's friend presented her an integer array a. Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x, y, z, w such that a_x + a_y = a_z + a_w. Her train has already arrived the destination, but she still hasn't found the answer. Can you help her unravel the mystery? Input The first line contains the single integer n (4 ≤ n ≤ 200 000) — the size of the array. The second line contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ 2.5 ⋅ 10^6). Output Print "YES" if there are such four indices, and "NO" otherwise. If such indices exist, print these indices x, y, z and w (1 ≤ x, y, z, w ≤ n). If there are multiple answers, print any of them. Examples Input 6 2 1 5 2 7 4 Output YES 2 3 1 6 Input 5 1 3 1 9 20 Output NO Note In the first example a_2 + a_3 = 1 + 5 = 2 + 4 = a_1 + a_6. Note that there are other answer, for example, 2 3 4 6. In the second example, we can't choose four indices. The answer 1 2 2 3 is wrong, because indices should be different, despite that a_1 + a_2 = 1 + 3 = 3 + 1 = a_2 + a_3 Submitted Solution: ``` def zip_sorted(a,b): # sorted by a a,b = zip(*sorted(zip(a,b))) # sorted by b sorted(zip(a, b), key=lambda x: x[1]) return a,b import sys from collections import defaultdict input = sys.stdin.readline I = lambda : list(map(int,input().split())) S = lambda : list(map(str,input().split())) n, = I() a = I() mem1 = defaultdict(list) mem2 = defaultdict(list) count = 0 count1 = 0 for i in range(len(a)): mem1[a[i]].append(i) if len(mem1[a[i]])>=2 and a[i] not in mem2: count+=1 mem2[a[i]] = mem1[a[i]] if len(mem1[a[i]])>=4: count1+=1 if count1>=1: ans = [] for i in mem1: if len(mem1[i])>=4: for j in mem1[i][:4]: ans.append(j+1) print("YES") print(*ans) elif count>=2: count = 0 ans = [0]*4 for i in mem2: if count==0: ans[0] = mem1[i][:2][0]+1 ans[2] = mem1[i][:2][1]+1 count+=1 elif count==1: ans[1] = mem1[i][:2][0]+1 ans[3] = mem1[i][:2][1]+1 count+=1 if count==2: break print('YES') print(*ans) elif count==1: countx = 0 s = 0 ans = [] for i in mem2: s = 2*i ans = [j+1 for j in mem2[i]] for i in range(len(a)): if a[i]==(s//2): continue for j in range(i+1,len(a)): if a[i]+a[j]==s: ans.append(i+1) ans.append(j+1) countx = 1 break if countx==1: break if countx!=0: print('YES') print(*ans) else: ans = [] countx = 0 mem3 = defaultdict(list) for i in range(len(a)): for j in range(i+1,len(a)): if (a[i]+a[j]) in mem3 and (i+1) not in mem3[a[i]+a[j]][0] and (j+1) not in mem3[a[i]+a[j]][0]: countx = 1 print('YES') print(*mem3[a[i]+a[j]][0],i+1,j+1) break else: mem3[a[i]+a[j]].append([i+1,j+1]) if countx==1: break if countx==0: print('NO') else: ans = [] countx = 0 mem3 = defaultdict(list) for i in range(len(a)): for j in range(i+1,len(a)): if (a[i]+a[j]) in mem3 and (i+1) not in mem3[a[i]+a[j]][0] and (j+1) not in mem3[a[i]+a[j]][0]: countx = 1 print('YES') print(*mem3[a[i]+a[j]][0],i+1,j+1) break else: mem3[a[i]+a[j]].append([i+1,j+1]) if countx==1: break if countx==0: print('NO') ```
instruction
0
88,652
12
177,304
No
output
1
88,652
12
177,305
Provide tags and a correct Python 3 solution for this coding contest problem. During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element a_1 becomes the root of the tree. 2. Elements a_2, a_3, …, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: 1. The pointer to the current node is set to the root. 2. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 3. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a. The second line contains n distinct integers a_i (1 ≤ a_i ≤ 10^9) — the sequence a itself. Output Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it. Examples Input 3 1 2 3 Output 1 2 Input 5 4 2 3 1 6 Output 4 2 2 4
instruction
0
88,884
12
177,768
Tags: data structures, trees Correct Solution: ``` __author__ = "House" import bisect if __name__ == "__main__": n = int(input()) s = [int(i) for i in input().split()] f = [[s[0], 0]] outp = list() for i in range(1, n): now = [s[i], i] idx = bisect.bisect_left(f, now) ans = 0 if idx == 0: ans = f[0][0] elif idx == i: ans = f[idx - 1][0] else: if f[idx][1] < f[idx - 1][1]: ans = f[idx - 1][0] else: ans = f[idx][0] f[idx:idx] = [now] outp.append(str(ans)) print(" ".join(outp)) ```
output
1
88,884
12
177,769
Provide tags and a correct Python 3 solution for this coding contest problem. During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element a_1 becomes the root of the tree. 2. Elements a_2, a_3, …, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: 1. The pointer to the current node is set to the root. 2. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 3. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a. The second line contains n distinct integers a_i (1 ≤ a_i ≤ 10^9) — the sequence a itself. Output Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it. Examples Input 3 1 2 3 Output 1 2 Input 5 4 2 3 1 6 Output 4 2 2 4
instruction
0
88,885
12
177,770
Tags: data structures, trees Correct Solution: ``` from bisect import bisect n=int(input()) elements=list(map(int, input().split())) tree=[] ans=['']*n for i,x in enumerate(elements): index = bisect(tree, (x,i)) if i!= 0: if index==0: ans[i]=str(tree[0][0]) elif index==i: ans[i]=str(tree[i-1][0]) else: if tree[index-1][1] < tree[index][1]: ans[i]=str(tree[index][0]) else: ans[i]=str(tree[index-1][0]) tree[index:index] = [(x, i)] print(' '.join(ans[1:])) ```
output
1
88,885
12
177,771
Provide tags and a correct Python 3 solution for this coding contest problem. During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element a_1 becomes the root of the tree. 2. Elements a_2, a_3, …, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: 1. The pointer to the current node is set to the root. 2. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 3. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a. The second line contains n distinct integers a_i (1 ≤ a_i ≤ 10^9) — the sequence a itself. Output Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it. Examples Input 3 1 2 3 Output 1 2 Input 5 4 2 3 1 6 Output 4 2 2 4
instruction
0
88,886
12
177,772
Tags: data structures, trees Correct Solution: ``` from bisect import bisect n = int(input()) array = [int(x) for x in input().split()] tree = [] ans = [''] * n for i in range(n): item = array[i] index = bisect(tree, (item, i)) if i != 0: if index == 0: ans[i] = str(tree[0][0]) elif index == i: ans[i] = str(tree[i - 1][0]) else: ans[i] = str(tree[index - 1][0] if tree[index - 1][1] > tree[index][1] else tree[index][0]) tree[index:index] = [(item, i)] print(' '.join(ans[1:])) ```
output
1
88,886
12
177,773
Provide tags and a correct Python 3 solution for this coding contest problem. During the programming classes Vasya was assigned a difficult problem. However, he doesn't know how to code and was unable to find the solution in the Internet, so he asks you to help. You are given a sequence a, consisting of n distinct integers, that is used to construct the binary search tree. Below is the formal description of the construction process. 1. First element a_1 becomes the root of the tree. 2. Elements a_2, a_3, …, a_n are added one by one. To add element a_i one needs to traverse the tree starting from the root and using the following rules: 1. The pointer to the current node is set to the root. 2. If a_i is greater than the value in the current node, then its right child becomes the current node. Otherwise, the left child of the current node becomes the new current node. 3. If at some point there is no required child, the new node is created, it is assigned value a_i and becomes the corresponding child of the current node. Input The first line of the input contains a single integer n (2 ≤ n ≤ 100 000) — the length of the sequence a. The second line contains n distinct integers a_i (1 ≤ a_i ≤ 10^9) — the sequence a itself. Output Output n - 1 integers. For all i > 1 print the value written in the node that is the parent of the node with value a_i in it. Examples Input 3 1 2 3 Output 1 2 Input 5 4 2 3 1 6 Output 4 2 2 4
instruction
0
88,887
12
177,774
Tags: data structures, trees Correct Solution: ``` from bisect import * n=int(input()) d,a=[(0,0)],[0]*n for i,x in enumerate(map(int,input().split())): no=bisect(d,(x,0))-1 l,y=d[no] a[i]=str(y) d[no:no+1]=[(l,x),(x,x)] print(' '.join(a[1:])) ```
output
1
88,887
12
177,775
Provide tags and a correct Python 3 solution for this coding contest problem. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1
instruction
0
88,969
12
177,938
Tags: dp, math, number theory Correct Solution: ``` from math import sqrt primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463] def sqfree(x): if x == 0: return x y = 1 for p in primes: pp=p*p while x % pp == 0: x //= pp if x % p == 0: x //= p y *= p if abs(x) < p: break if int(sqrt(abs(x)))**2 == abs(x): return (y if x > 0 else -y) else: return x * y n = int(input().strip()) ais = list(map(int, input().strip().split())) bis = list(map(sqfree, ais)) prev = [-1 for i in range(n)] last = {} for i, b in enumerate(bis): if b in last: prev[i] = last[b] last[b] = i res = [0 for i in range(n)] for l in range(n): cnt = 0 for r in range(l, n): if bis[r] != 0 and prev[r] < l: cnt += 1 res[max(cnt - 1, 0)] += 1 print (' '.join(map(str, res))) ```
output
1
88,969
12
177,939
Provide tags and a correct Python 3 solution for this coding contest problem. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1
instruction
0
88,970
12
177,940
Tags: dp, math, number theory Correct Solution: ``` #!/usr/bin/env python3 from math import sqrt primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463] psq = [p*p for p in primes] def sqfree(x): if x == 0: return x y = 1 for p, pp in zip(primes, psq): while x % pp == 0: x //= pp if x % p == 0: x //= p y *= p if abs(x) < p: break if int(sqrt(abs(x)))**2 == abs(x): return (y if x > 0 else -y) else: return x * y n = int(input().strip()) ais = list(map(int, input().strip().split())) bis = list(map(sqfree, ais)) prev = [-1 for i in range(n)] last = {} for i, b in enumerate(bis): if b in last: prev[i] = last[b] last[b] = i res = [0 for i in range(n)] for l in range(n): cnt = 0 for r in range(l, n): if bis[r] != 0 and prev[r] < l: cnt += 1 res[max(cnt - 1, 0)] += 1 print (' '.join(map(str, res))) ```
output
1
88,970
12
177,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1 Submitted Solution: ``` def reduce(n): i = 2 isqr = i * i while i * i <= n: if n % i == 0: print(n, i) isqr = i * i while n % (isqr) == 0: n //= isqr i += 1 return n # def test_reduce(): # a = [2 * 3 **7 * 5**3 * 9**5] # print(a) # print([reduce(x) for x in a]) def solve(n, a): a = [reduce(x) for x in a] pair = {0 : 0} mp = [0] * len(a) for i, x in enumerate(a): if x not in pair: pair[x] = len(pair) mp[i] = pair[x] # print(a) # print(mp) # print() cntuniq = [0] * n for l in range(1, n + 1): cnt = [0] * len(mp) for i in range(l): cnt[mp[i]] += 1 uniq = sum([c > 0 for c in cnt]) if 0 < cnt[0] and 1 < uniq: cntuniq[uniq - 2] += 1 print(cnt, uniq - 1) else: cntuniq[uniq - 1] += 1 print(cnt, uniq) for i in range(l, n): if cnt[mp[i]] == 0: uniq += 1 cnt[mp[i]] += 1 cnt[mp[i - l]] -= 1 if cnt[mp[i - l]] == 0: uniq -= 1 if 0 < cnt[0] and 1 < uniq: cntuniq[uniq - 2] += 1 print(cnt, uniq - 1) else: cntuniq[uniq - 1] += 1 print(cnt, uniq) print() return cntuniq def main(): n = int(input()) a = [int(_) for _ in input().split()] ak = solve(n, a) print(' '.join(map(str, ak))) if __name__ == '__main__': # test_reduce() main() ```
instruction
0
88,971
12
177,942
No
output
1
88,971
12
177,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1 Submitted Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) n,=I() l=I() an=[0]*n an[0]=n for i in range(n): k=abs(l[i]);x=1 for j in range(2,int(k**0.5)+1): c=0 while k%j==0: c+=1;k//=j if c%2: x*=j x*=k if l[i]<0: x=-x l[i]=x for i in range(2,n+1): for j in range(n-i+1): p=set(l[j:j+i]) if 0 in p: if len(p)>1: an[len(p)-2]+=1 else: an[len(p)-1]+=1 print(*an) ```
instruction
0
88,972
12
177,944
No
output
1
88,972
12
177,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1 Submitted Solution: ``` #!/usr/bin/env python3 from math import sqrt primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] psq = [p**p for p in primes] def sqfree(x): if x == 0: return x for p in psq: while x % p == 0: x //= p if abs(x) < p: break return x n = int(input().strip()) ais = list(map(int, input().strip().split())) nz = ais.count(0) bis = list(filter(lambda v: v != 0, map(sqfree, ais))) res = [0 for _ in range(n)] res[0] += nz prev = [-1 for i in range(n - nz)] last = {} for i, b in enumerate(bis): if b in last: prev[i] = last[b] last[b] = i for l in range(n - nz): cnt = 0 for r in range(l, n - nz): if prev[r] < l: cnt += 1 res[cnt - 1] += 1 print (' '.join(map(str, res))) ```
instruction
0
88,973
12
177,946
No
output
1
88,973
12
177,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. SaMer has written the greatest test case of all time for one of his problems. For a given array of integers, the problem asks to find the minimum number of groups the array can be divided into, such that the product of any pair of integers in the same group is a perfect square. Each integer must be in exactly one group. However, integers in a group do not necessarily have to be contiguous in the array. SaMer wishes to create more cases from the test case he already has. His test case has an array A of n integers, and he needs to find the number of contiguous subarrays of A that have an answer to the problem equal to k for each integer k between 1 and n (inclusive). Input The first line of input contains a single integer n (1 ≤ n ≤ 5000), the size of the array. The second line contains n integers a_1,a_2,...,a_n (-10^8 ≤ a_i ≤ 10^8), the values of the array. Output Output n space-separated integers, the k-th integer should be the number of contiguous subarrays of A that have an answer to the problem equal to k. Examples Input 2 5 5 Output 3 0 Input 5 5 -4 2 1 8 Output 5 5 3 2 0 Input 1 0 Output 1 Submitted Solution: ``` #!/usr/bin/env python3 from math import sqrt primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463] psq = [p**p for p in primes] def sqfree(x): if x == 0: return x y = 1 for p, pp in zip(primes, psq): while x % pp == 0: x //= pp if x % p == 0: x //= p y *= p if abs(x) < pp: break if int(sqrt(abs(x)))**2 == abs(x): return (y if x > 0 else -y) else: return x * y n = int(input().strip()) ais = list(map(int, input().strip().split())) bis = list(map(sqfree, ais)) prev = [-1 for i in range(n)] last = {} for i, b in enumerate(bis): if b in last: prev[i] = last[b] last[b] = i res = [0 for i in range(n)] for l in range(n): cnt = 0 for r in range(l, n): if bis[r] != 0 and prev[r] < l: cnt += 1 res[max(cnt - 1, 0)] += 1 print (' '.join(map(str, res))) ```
instruction
0
88,974
12
177,948
No
output
1
88,974
12
177,949
Provide a correct Python 3 solution for this coding contest problem. problem Given the sequence $ A $ of length $ N $. Find the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $. The longest increasing subsequence of the sequence $ A $ is the longest subsequence that satisfies $ A_i <A_j $ with all $ i <j $. output Output the maximum value of $ \ sum B_i $, where $ B $ is one of the longest increasing subsequences of the sequence $ A $. Also, output a line break at the end. Example Input 4 6 4 7 8 Output 21
instruction
0
89,216
12
178,432
"Correct Solution: ``` import bisect N = int(input()) A = list(map(int,input().split())) lis = [] hist = [] for a in A: i = bisect.bisect_left(lis,a) if i == len(lis): lis.append(a) hist.append([a]) else: lis[i] = a hist[i].append(a) ans = last = hist[-1][0] for row in reversed(hist[:-1]): i = bisect.bisect_left(row[::-1], last) last = row[-i] ans += last print(ans) ```
output
1
89,216
12
178,433