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 start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5;
instruction
0
55,783
12
111,566
Tags: combinatorics, data structures, dsu, greedy, implementation Correct Solution: ``` mod = 998244353 import sys def input(): return sys.stdin.readline() for _ in range(int(input())): n, k = map(int, input().split()) A = list(map(int, input().split())) B = list(map(int, input().split())) X = [0] * n for i in range(n): X[A[i] - 1] = i Y = [-1] * n for i in range(k): Y[X[B[i] - 1]] = i ans = 1 Y += [n] i = -1 while i < n: if Y[i] == -1: i += 1 continue j = i + 1 x = 0 while j <= n and Y[j] != -1: if x == 0: if Y[j] < Y[j - 1]: x += 1 else: if Y[j] > Y[j - 1]: ans = 0 break j += 1 if 0 <= i and j < n: ans *= 2 ans %= mod i = j print(ans) ```
output
1
55,783
12
111,567
Provide tags and a correct Python 3 solution for this coding contest problem. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5;
instruction
0
55,784
12
111,568
Tags: combinatorics, data structures, dsu, greedy, implementation Correct Solution: ``` import io,os from math import * input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline M = 998244353 for _ in range(int(input())): n,k = map(int, input().split()) a_ = list(map(int, input().split())) a = {x:i for i,x in enumerate(a_)} b_ = list(map(int, input().split())) b = [a[x] for x in b_] c = {x:i for i,x in enumerate(b)} poss = 1 for i,d in enumerate(b): canleft = d > 0 and (d-1 not in c or c[d-1] < i) canright = d < n - 1 and (d+1 not in c or c[d+1] < i) poss = poss * (canleft + canright) % M print(poss) ```
output
1
55,784
12
111,569
Provide tags and a correct Python 3 solution for this coding contest problem. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5;
instruction
0
55,785
12
111,570
Tags: combinatorics, data structures, dsu, greedy, implementation Correct Solution: ``` import sys import math def II(): return int(sys.stdin.readline()) def LI(): return list(map(int, sys.stdin.readline().split())) def MI(): return map(int, sys.stdin.readline().split()) def SI(): return sys.stdin.readline().strip() t = II() for q in range(t): n,k = MI() ans = 1 x = [0]*(n+1) y = [0]*(n+1) a = LI() b = LI() mod = 998244353 boo = True for i in range(n): x[a[i]] = i for i in range(k): y[b[i]] = i for i in range(k): count = 0 tot = 0 if x[b[i]]-1>=0: if y[a[x[b[i]]-1]] > i: count+=1 tot+=1 if x[b[i]]+1<n: if y[a[x[b[i]]+1]] > i: count+=1 tot+=1 if tot == count: boo = False break elif count == 0 and tot == 2: ans*=2 ans%=mod print(0 if not boo else ans) ```
output
1
55,785
12
111,571
Provide tags and a correct Python 3 solution for this coding contest problem. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5;
instruction
0
55,786
12
111,572
Tags: combinatorics, data structures, dsu, greedy, implementation Correct Solution: ``` """T=int(input()) for _ in range(0,T): n=int(input()) a,b=map(int,input().split()) s=input() s=[int(x) for x in input().split()] for i in range(0,len(s)): a,b=map(int,input().split())""" MOD = 998244353 T=int(input()) for _ in range(0,T): n,k=map(int,input().split()) a=[int(x) for x in input().split()] b=[int(x) for x in input().split()] pos=[0]*(n+1) ind=[-1]*(n+1) for i in range(0,len(b)): pos[b[i]]=1 for i in range(0,len(a)): ind[a[i]]=i ans=1 for i in range(0,len(b)): ptr=ind[b[i]] c=0 if((ptr-1)>=0 and pos[a[ptr-1]]==0): c=(c+1)%MOD if((ptr+1)<n and pos[a[ptr+1]]==0): c=(c+1)%MOD pos[a[ptr]]=0 ans=(ans*c)%MOD print(ans) ```
output
1
55,786
12
111,573
Provide tags and a correct Python 3 solution for this coding contest problem. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5;
instruction
0
55,787
12
111,574
Tags: combinatorics, data structures, dsu, greedy, implementation Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict #threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase #sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**32, func=lambda a, b: min(a,b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b:max(a , b)): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <=key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ class TrieNode: def __init__(self): self.children = [None] * 26 self.isEndOfWord = False class Trie: def __init__(self): self.root = self.getNode() def getNode(self): return TrieNode() def _charToIndex(self, ch): return ord(ch) - ord('a') def insert(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: pCrawl.children[index] = self.getNode() pCrawl = pCrawl.children[index] pCrawl.isEndOfWord = True def search(self, key): pCrawl = self.root length = len(key) for level in range(length): index = self._charToIndex(key[level]) if not pCrawl.children[index]: return False pCrawl = pCrawl.children[index] return pCrawl != None and pCrawl.isEndOfWord #-----------------------------------------trie--------------------------------- class Node: def __init__(self, data): self.data = data self.count=0 self.left = None # left node for 0 self.right = None # right node for 1 class BinaryTrie: def __init__(self): self.root = Node(0) def insert(self, pre_xor): self.temp = self.root for i in range(31, -1, -1): val = pre_xor & (1 << i) if val: if not self.temp.right: self.temp.right = Node(0) self.temp = self.temp.right self.temp.count+=1 if not val: if not self.temp.left: self.temp.left = Node(0) self.temp = self.temp.left self.temp.count += 1 self.temp.data = pre_xor def query(self, xor): self.temp = self.root for i in range(31, -1, -1): val = xor & (1 << i) if not val: if self.temp.left and self.temp.left.count>0: self.temp = self.temp.left elif self.temp.right: self.temp = self.temp.right else: if self.temp.right and self.temp.right.count>0: self.temp = self.temp.right elif self.temp.left: self.temp = self.temp.left self.temp.count-=1 return xor ^ self.temp.data #-------------------------bin trie------------------------------------------- for ik in range(int(input())): n,k = map(int,input().split()) l = list(map(int, input().split())) rem=set(l) b=list(map(int,input().split())) if n==1: print(0) continue ans=1 re=set(b) d=defaultdict(int) for i in range(n): d[l[i]]=i for i in range(k): t=0 ind =d[b[i]] if ind-1>=0: if l[ind-1] not in re: t+=1 if ind+1<n: if l[ind+1] not in re: t+=1 re.remove(l[ind]) ans*=t ans%=mod1 if t==0: break print(ans%mod1) ```
output
1
55,787
12
111,575
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` # Enter your code here. Read input from STDIN. Print output to STDOUT# =============================================================================================== # importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from itertools import * import bisect from heapq import * from math import ceil, floor from copy import * from collections import deque, defaultdict from collections import Counter as counter # Counter(list) return a dict with {key: count} from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)] from itertools import permutations as permutate from bisect import bisect_left as bl from operator import * # If the element is already present in the list, # the left most position where element has to be inserted is returned. from bisect import bisect_right as br from bisect import bisect # If the element is already present in the list, # the right most position where element has to be inserted is returned # ============================================================================================== # fast I/O region BUFSIZE = 8192 from sys import stderr class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") # =============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### ########################### # Sorted list class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) # =============================================================================================== # some shortcuts mod = 1000000007 def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def out(var): sys.stdout.write(str(var)) # for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def nextline(): out("\n") # as stdout.write always print sring. def testcase(t): for p in range(t): solve() def pow(x, y, p): res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res from functools import reduce def factors(n): return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))) def gcd(a, b): if a == b: return a while b > 0: a, b = b, a % b return a # discrete binary search # minimise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # if isvalid(l): # return l # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m - 1): # return m # if isvalid(m): # r = m + 1 # else: # l = m # return m # maximise: # def search(): # l = 0 # r = 10 ** 15 # # for i in range(200): # # print(l,r) # if isvalid(r): # return r # if l == r: # return l # m = (l + r) // 2 # if isvalid(m) and not isvalid(m + 1): # return m # if isvalid(m): # l = m # else: # r = m - 1 # return m ##############Find sum of product of subsets of size k in a array # ar=[0,1,2,3] # k=3 # n=len(ar)-1 # dp=[0]*(n+1) # dp[0]=1 # for pos in range(1,n+1): # dp[pos]=0 # l=max(1,k+pos-n-1) # for j in range(min(pos,k),l-1,-1): # dp[j]=dp[j]+ar[pos]*dp[j-1] # print(dp[k]) def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10] return list(accumulate(ar)) def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4] return list(accumulate(ar[::-1]))[::-1] def N(): return int(inp()) dx = [0, 0, 1, -1] dy = [1, -1, 0, 0] def YES(): print("YES") def NO(): print("NO") def Yes(): print("Yes") def No(): print("No") # ========================================================================================= from collections import defaultdict def numberOfSetBits(i): i = i - ((i >> 1) & 0x55555555) i = (i & 0x33333333) + ((i >> 2) & 0x33333333) return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24 class MergeFind: def __init__(self, n): self.parent = list(range(n)) self.size = [1] * n self.num_sets = n # self.lista = [[_] for _ in range(n)] def find(self, a): to_update = [] while a != self.parent[a]: to_update.append(a) a = self.parent[a] for b in to_update: self.parent[b] = a return self.parent[a] def merge(self, a, b): a = self.find(a) b = self.find(b) if a == b: return self.num_sets -= 1 self.parent[a] = b self.size[b] += self.size[a] # self.lista[a] += self.lista[b] # self.lista[b] = [] def set_size(self, a): return self.size[self.find(a)] def __len__(self): return self.num_sets def lcm(a, b): return abs((a // gcd(a, b)) * b) # # # to find factorial and ncr # tot = 400005 # mod = 10 ** 9 + 7 # fac = [1, 1] # finv = [1, 1] # inv = [0, 1] # # for i in range(2, tot + 1): # fac.append((fac[-1] * i) % mod) # inv.append(mod - (inv[mod % i] * (mod // i) % mod)) # finv.append(finv[-1] * inv[-1] % mod) # # # def comb(n, r): # if n < r: # return 0 # else: # return fac[n] * (finv[r] * finv[n - r] % mod) % mod def solve(): mod=998244353 n,k=sep() ar=[-1]+lis()+[-1] ar2=lis() s=set(ar2) s.add(-1) ind=defaultdict(int) for i in range(1,n+1): ind[ar[i]]=i ans=1 for i in range(k): s.remove(ar2[i]) t=2 inde=ind[ar2[i]] if ar[inde+1] in s: t-=1 if ar[inde-1] in s: t-=1 ans*=t ans%=mod # print(i, s,ans) # print(ar2) # print(ind) print(ans) #solve() testcase(int(inp())) ```
instruction
0
55,788
12
111,576
Yes
output
1
55,788
12
111,577
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` from sys import stdin caso=int(stdin.readline().strip()) mod= 998244353 for cas in range(caso): n,m=map(int,stdin.readline().strip().split()) s=list(map(int,stdin.readline().strip().split())) s1=list(map(int,stdin.readline().strip().split())) vis=[True for i in range(n+1)] pos=[-1 for i in range(n+1)] for i in range(m): vis[s1[i]]=False for i in range(n): pos[s[i]]=i ans=1 for i in range(m): aux=0 if pos[s1[i]]>0 and vis[s[pos[s1[i]]-1]]: aux+=1 if pos[s1[i]]<n-1 and vis[s[pos[s1[i]]+1]]: aux+=1 vis[s1[i]]=True ans=(ans*aux)%mod print(ans) ```
instruction
0
55,789
12
111,578
Yes
output
1
55,789
12
111,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading #sys.setrecursionlimit(300000) #threading.stack_size(10**8) 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") #-------------------game starts now----------------------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD #------------------------------------------------------------------------- mod=998244353 for _ in range (int(input())): n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) s=set(b) el=dict() for i in range (n): el[a[i]]=i r=1 for i in range (k): e=el[b[i]] c=0 if e>0: if a[e-1] not in s: c+=1 if e<n-1: if a[e+1] not in s: c+=1 s.remove(b[i]) #print(e,c,s) r*=c r%=mod print(r) ```
instruction
0
55,790
12
111,580
Yes
output
1
55,790
12
111,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` import sys import math from collections import defaultdict,Counter input=sys.stdin.readline def print(x): sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') # mod=pow(10,9)+7 mod=998244353 t=int(input()) for i in range(t): n,k=map(int,input().split()) a=list(map(int,input().split())) b=list(map(int,input().split())) s1=defaultdict(set) s1[a[0]].add(a[1]) s1[a[-1]].add(a[-2]) for ii in range(1,n-1): s1[a[ii]].add(a[ii-1]) s1[a[ii]].add(a[ii+1]) s2=set(b) ans=1 for j in range(k): # print(s1) s2.remove(b[j]) cur=0 r=0 for kk in s1[b[j]]: if kk not in s2: r=kk cur+=1 if cur==0: ans=0 break else: s1[b[j]].remove(r) for kk in s1[r]: if kk!=b[j]: s1[b[j]].add(kk) s1[kk].add(b[j]) s1[kk].remove(r) break if cur==2: ans=(ans*2)%mod print(ans) ```
instruction
0
55,791
12
111,582
Yes
output
1
55,791
12
111,583
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` """ Author - Satwik Tiwari . 2nd NOV , 2020 - Monday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 998244353 #=============================================================================================== # code here ;)) def solve(case): n,k = sep() a = lis() b = lis() have = {} for i in range(k): have[b[i]] = 1 pos = {} for i in range(n): pos[a[i]] = i if(len(b) == 1): if(b[0] in a): print(1) else: print(0) return ans = 1 for i in range(k): # print(i) # print(have) left = -1 right = -1 ind = pos[b[i]] del have[b[i]] if(ind == 0): if(a[ind+1] in have): ans = 0 break elif(ind == n-1): if(a[ind-1] in have): ans = 0 break else: if(a[ind-1] in have and a[ind+1] in have): ans = 0 break if(a[ind-1] not in have and a[ind+1] not in have): ans*=2 # print(i,ans) ans%=mod print(ans%mod) """ 2 13 1 1 1 1 1 4 3 4 4 3 4 3 13 1 1 1 2 2 2 3 3 3 4 4 4 """ # testcase(1) testcase(int(inp())) ```
instruction
0
55,792
12
111,584
No
output
1
55,792
12
111,585
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` from bisect import * from collections import * from math import gcd,ceil,sqrt,floor,inf from heapq import * from itertools import * from operator import add,mul,sub,xor,truediv,floordiv from functools import * #------------------------------------------------------------------------ import os import sys from io import BytesIO, IOBase # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #------------------------------------------------------------------------ def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) #------------------------------------------------------------------------ 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,l,r,arr): self.l=l self.r=r self.value=(1<<31)-1 if l<r else arr[l] mid=(l+r)//2 if(l<r): self.left=smt(l,mid,arr) self.right=smt(mid+1,r,arr) self.value&=self.left.value&self.right.value #print(l,r,self.value) def setvalue(self,x,val): if(self.l==self.r): self.value=val return mid=(self.l+self.r)//2 if(x<=mid): self.left.setvalue(x,val) else: self.right.setvalue(x,val) self.value=self.left.value&self.right.value def ask(self,l,r): if(l<=self.l and r>=self.r): return self.value val=(1<<31)-1 mid=(self.l+self.r)//2 if(l<=mid): val&=self.left.ask(l,r) if(r>mid): val&=self.right.ask(l,r) return val 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): res=[] for ch,g in groupby(it): res.append((ch,len(list(g)))) return res def judge(i): return i not in s and i!=-1 t=N() for i in range(t): n,k=RL() a=RLL() b=RLL() mod=998244353 s=set(b) ans=1 left=[-1]*(n+1) right=[-1]*(n+1) for i in range(n): if i!=0: left[a[i]]=a[i-1] if i!=n-1: right[a[i]]=a[i+1] for i in range(k): if judge(left[b[i]]) and judge(right[b[i]]): ans=ans*2%mod left[b[i]]=left[left[b[i]]] right[left[left[b[i]]]]=b[i] s.remove(b[i]) elif judge(left[b[i]]): left[b[i]]=left[left[b[i]]] right[left[left[b[i]]]]=b[i] s.remove(b[i]) elif judge(right[b[i]]): right[b[i]]=right[right[b[i]]] left[right[right[b[i]]]]=b[i] s.remove(b[i]) else: ans=0 break #print(right[1],right[2],right[) #print(s) print(ans) ```
instruction
0
55,793
12
111,586
No
output
1
55,793
12
111,587
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` """ Author - Satwik Tiwari . 2nd NOV , 2020 - Monday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def zerolist(n): return [0]*n def nextline(): out("\n") #as stdout.write always print sring. def testcase(t): for pp in range(t): solve(pp) def printlist(a) : for p in range(0,len(a)): out(str(a[p]) + ' ') def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 998244353 #=============================================================================================== # code here ;)) def solve(case): n,k = sep() a = lis() b = lis() have = {} for i in range(k): have[b[i]] = 1 pos = {} for i in range(n): pos[a[i]] = i if(len(b) == 1 and len(a)<3): if(b[0] in a): print(1) else: print(0) return ans = 1 for i in range(k): # print(i) # print(have) left = -1 right = -1 ind = pos[b[i]] del have[b[i]] print(ind) if(ind == 0): if(a[ind+1] in have): ans = 0 break elif(ind == n-1): if(a[ind-1] in have): ans = 0 break else: if(a[ind-1] in have and a[ind+1] in have): ans = 0 break if(a[ind-1] not in have and a[ind+1] not in have): ans*=2 # print(i,ans) ans%=mod print(ans%mod) """ 2 13 1 1 1 1 1 4 3 4 4 3 4 3 13 1 1 1 2 2 2 3 3 3 4 4 4 """ # testcase(1) testcase(int(inp())) ```
instruction
0
55,794
12
111,588
No
output
1
55,794
12
111,589
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We start with a permutation a_1, a_2, …, a_n and with an empty array b. We apply the following operation k times. On the i-th iteration, we select an index t_i (1 ≤ t_i ≤ n-i+1), remove a_{t_i} from the array, and append one of the numbers a_{t_i-1} or a_{t_i+1} (if t_i-1 or t_i+1 are within the array bounds) to the right end of the array b. Then we move elements a_{t_i+1}, …, a_n to the left in order to fill in the empty space. You are given the initial permutation a_1, a_2, …, a_n and the resulting array b_1, b_2, …, b_k. All elements of an array b are distinct. Calculate the number of possible sequences of indices t_1, t_2, …, t_k modulo 998 244 353. Input Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases. The first line of each test case contains two integers n, k (1 ≤ k < n ≤ 200 000): sizes of arrays a and b. The second line of each test case contains n integers a_1, a_2, …, a_n (1 ≤ a_i ≤ n): elements of a. All elements of a are distinct. The third line of each test case contains k integers b_1, b_2, …, b_k (1 ≤ b_i ≤ n): elements of b. All elements of b are distinct. The sum of all n among all test cases is guaranteed to not exceed 200 000. Output For each test case print one integer: the number of possible sequences modulo 998 244 353. Example Input 3 5 3 1 2 3 4 5 3 2 5 4 3 4 3 2 1 4 3 1 7 4 1 4 7 3 6 2 5 3 2 4 5 Output 2 0 4 Note \require{cancel} Let's denote as a_1 a_2 … \cancel{a_i} \underline{a_{i+1}} … a_n → a_1 a_2 … a_{i-1} a_{i+1} … a_{n-1} an operation over an element with index i: removal of element a_i from array a and appending element a_{i+1} to array b. In the first example test, the following two options can be used to produce the given array b: * 1 2 \underline{3} \cancel{4} 5 → 1 \underline{2} \cancel{3} 5 → 1 \cancel{2} \underline{5} → 1 2; (t_1, t_2, t_3) = (4, 3, 2); * 1 2 \underline{3} \cancel{4} 5 → \cancel{1} \underline{2} 3 5 → 2 \cancel{3} \underline{5} → 1 5; (t_1, t_2, t_3) = (4, 1, 2). In the second example test, it is impossible to achieve the given array no matter the operations used. That's because, on the first application, we removed the element next to 4, namely number 3, which means that it couldn't be added to array b on the second step. In the third example test, there are four options to achieve the given array b: * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → \cancel{1} \underline{4} 3 2 5 → 4 3 \cancel{2} \underline{5} → 4 3 5; * 1 4 \cancel{7} \underline{3} 6 2 5 → 1 4 3 \cancel{6} \underline{2} 5 → 1 \underline{4} \cancel{3} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → \cancel{1} \underline{4} 7 2 5 → 4 7 \cancel{2} \underline{5} → 4 7 5; * 1 4 7 \underline{3} \cancel{6} 2 5 → 1 4 7 \cancel{3} \underline{2} 5 → 1 \underline{4} \cancel{7} 2 5 → 1 4 \cancel{2} \underline{5} → 1 4 5; Submitted Solution: ``` import sys input=sys.stdin.readline R=lambda:map(int,input().split()) t,=R() for _ in [0]*t: n,k=R() vis=[1]*(n+2) # 1可以删 vis[0]=vis[n+1]=0 a=[0]+list(R())+[0] b=list(R()) ans=0 for i in b: vis[i]=0 for i in b: index=a.index(i) if vis[a[index-1]]==0 and vis[a[index+1]]==0: ans=-1 break if vis[a[index-1]]==1 and vis[a[index+1]]==1: ans+=1 vis[i]=1 if ans!=-1: print(2**ans) else: print(0) ```
instruction
0
55,795
12
111,590
No
output
1
55,795
12
111,591
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,932
12
111,864
Tags: constructive algorithms, dp, math Correct Solution: ``` import sys input = sys.stdin.readline import math import copy import collections from collections import deque n,k = list(map(int,input().split())) ans = [] for i in range(n): if k>0: ans.append(2*n-2*i-1) ans.append(2*n-2*i) k-=1 else: ans.append(2*n-2*i) ans.append(2*n-2*i-1) for num in ans: print(num, end = " ") print() ```
output
1
55,932
12
111,865
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,933
12
111,866
Tags: constructive algorithms, dp, math Correct Solution: ``` n,k = map(int,input().split()) r = 2*n-2*k for i in range(2*n,r,-2): print(i-1,i,end=' ') for i in range(r,1,-2): print(i,i-1,end=' ') ```
output
1
55,933
12
111,867
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,934
12
111,868
Tags: constructive algorithms, dp, math Correct Solution: ``` i,k = [int(a) for a in input().split()] A = [] for i in range(1,2*i+1): A.append(str(i)) for i in range(k): A[4*i],A[4*i+1] = A[4*i+1],A[4*i] s = " ".join(A) print(s) ```
output
1
55,934
12
111,869
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,935
12
111,870
Tags: constructive algorithms, dp, math Correct Solution: ``` import math def f(perm): a1 = 0 a2 = 0 for i in range(len(perm)//2): a1+=abs(perm[2*i]-perm[2*i+1]) for i in range(len(perm)): if i%2 == 0: a2+=perm[i] else: a2-=perm[i] a2 = abs(a2) return (a1-a2)//2 perm = [7, 1, 2, 3, 4, 5, 6, 8, 9, 10] #print(f(perm)) n, k = map(int, input().split(' ')) res = [] if k == 0: for i in range(1, 2*n+1): res.append(i) print(res.__str__().replace(",", "").replace("[", "").replace("]", "")) exit(0) if n%2 == 0: znak = 1+k else: if k == n: znak = k+2 else: znak = k+1 res.append(znak) res.append(1) pointer = 2 if pointer == znak: pointer+=1 for i in range(n-1): a = pointer pointer+=1 if pointer == znak: pointer+=1 b = pointer pointer+=1 if pointer == znak: pointer+=1 res.append(a) res.append(b) print(res.__str__().replace(",", "").replace("[", "").replace("]", "")) ```
output
1
55,935
12
111,871
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,936
12
111,872
Tags: constructive algorithms, dp, math Correct Solution: ``` n,k=map(int,input().split()) for i in range(n): if(i<k): print(2*i+2,2*i+1,end=' ') else: print(2*i+1,2*i+2,end=' ') ```
output
1
55,936
12
111,873
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,937
12
111,874
Tags: constructive algorithms, dp, math Correct Solution: ``` n,k=list(map(int,input().split())) a=[i for i in range(1,2*n+1)] for i in range(k): a[2*i],a[2*i+1]=a[2*i+1],a[2*i] print(*a) ```
output
1
55,937
12
111,875
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,938
12
111,876
Tags: constructive algorithms, dp, math Correct Solution: ``` n,k=map(int,input().split()) if(k==0): for i in range(1,2*n+1): print(i,end=" ") else: l=[i for i in range(1,2*n+1)] for i in range(1,k+1): j=2*i-1 m=2*i while(j<=m): temp=l[j-1] l[j-1]=l[m-1] l[m-1]=temp j=j+1 m=m-1 for i in range(2*n): print(l[i],end=" ") ```
output
1
55,938
12
111,877
Provide tags and a correct Python 3 solution for this coding contest problem. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0.
instruction
0
55,939
12
111,878
Tags: constructive algorithms, dp, math Correct Solution: ``` n, k = map(int, input().split()) if n == 0: print(0) else: arr = [0] * 2 * n for i in range(2 * n): arr[i] = i + 1 for i in range(0, 2 * k, 2): temp = arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp for i in range(2 * n): print(arr[i], sep=' ', end=' ') ```
output
1
55,939
12
111,879
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` ''' ___ ___ ___ ___ ___ ___ /\__\ /\ \ _____ /\ \ /\ \ /\ \ /\__\ /:/ _/_ \:\ \ /::\ \ \:\ \ ___ /::\ \ |::\ \ ___ /:/ _/_ /:/ /\ \ \:\ \ /:/\:\ \ \:\ \ /\__\ /:/\:\__\ |:|:\ \ /\__\ /:/ /\ \ /:/ /::\ \ ___ \:\ \ /:/ \:\__\ ___ /::\ \ /:/__/ /:/ /:/ / __|:|\:\ \ /:/ / /:/ /::\ \ /:/_/:/\:\__\ /\ \ \:\__\ /:/__/ \:|__| /\ /:/\:\__\ /::\ \ /:/_/:/__/___ /::::|_\:\__\ /:/__/ /:/_/:/\:\__\ \:\/:/ /:/ / \:\ \ /:/ / \:\ \ /:/ / \:\/:/ \/__/ \/\:\ \__ \:\/:::::/ / \:\~~\ \/__/ /::\ \ \:\/:/ /:/ / \::/ /:/ / \:\ /:/ / \:\ /:/ / \::/__/ ~~\:\/\__\ \::/~~/~~~~ \:\ \ /:/\:\ \ \::/ /:/ / \/_/:/ / \:\/:/ / \:\/:/ / \:\ \ \::/ / \:\~~\ \:\ \ \/__\:\ \ \/_/:/ / /:/ / \::/ / \::/ / \:\__\ /:/ / \:\__\ \:\__\ \:\__\ /:/ / \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ \/__/ ''' """ ░░██▄░░░░░░░░░░░▄██ ░▄▀░█▄░░░░░░░░▄█░░█░ ░█░▄░█▄░░░░░░▄█░▄░█░ ░█░██████████████▄█░ ░█████▀▀████▀▀█████░ ▄█▀█▀░░░████░░░▀▀███ ██░░▀████▀▀████▀░░██ ██░░░░█▀░░░░▀█░░░░██ ███▄░░░░░░░░░░░░▄███ ░▀███▄░░████░░▄███▀░ ░░░▀██▄░▀██▀░▄██▀░░░ ░░░░░░▀██████▀░░░░░░ ░░░░░░░░░░░░░░░░░░░░ """ import sys import math import collections import operator as op from collections import deque from math import gcd, inf, sqrt, pi, cos, sin, ceil, log2 from bisect import bisect_right, bisect_left # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') from functools import reduce from sys import stdin, stdout, setrecursionlimit setrecursionlimit(2**20) def factorial(n): if n == 0: return 1 return (n * factorial(n - 1)) def ncr(n, r): r = min(r, n - r) numer = reduce(op.mul, range(n, n - r, -1), 1) denom = reduce(op.mul, range(1, r + 1), 1) return numer // denom # or / in Python 2 def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return (list(factors)) MOD = 1000000007 PMOD = 998244353 T = 1 # T = int(stdin.readline()) for _ in range(T): n, k = list(map(int, stdin.readline().rstrip().split())) # n = int(stdin.readline()) # a = list(map(int, stdin.readline().rstrip().split())) # b = list(map(int, stdin.readline().rstrip().split())) # a = str(stdin.readline().strip('\n')) # k = int(stdin.readline()) # c = list(map(int, stdin.readline().rstrip().split())) for i in range(n): if i > 0: print(' ', end='') if k > 0: print(str(2 * i + 2) + ' ' + str(2 * i + 1), end='') else: print(str(2 * i + 1) + ' ' + str(2 * i + 2), end='') k -= 1 ```
instruction
0
55,940
12
111,880
Yes
output
1
55,940
12
111,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` n, k = map(int, input().split()) a = [i + 1 for i in range(2 * n)] for i in range(k): a[2 * i], a[2 * i + 1] = a[2 * i + 1], a[2 * i] a = " ".join([str(i) for i in a]) print(a) ```
instruction
0
55,941
12
111,882
Yes
output
1
55,941
12
111,883
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` n,k=map(int,input().split()) x=list(range(1,(2*n)+1)) for i in range(k): x[(2*i)+1],x[2*i]=x[2*i],x[(2*i)+1] print(*x) ```
instruction
0
55,942
12
111,884
Yes
output
1
55,942
12
111,885
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` a=input() n,k=a.split(" "); n=int(n) k=int(k) b=list() b+=[0] for i in range(1,2*n+1): b+=[i] for i in range(1,k+1): b[2*i],b[2*i-1]=b[2*i-1],b[2*i] for i in range(1,2*n+1): print(b[i],end=" ") ```
instruction
0
55,943
12
111,886
Yes
output
1
55,943
12
111,887
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- # @oj: codeforces # @id: hitwanyang # @email: 296866643@qq.com # @date: 2021/4/29 11:08 # @url: https://codeforces.com/contest/359/problem/B import sys, os from io import BytesIO, IOBase import collections, itertools, bisect, heapq, math, string from decimal import * from collections import deque # region fastio BUFSIZE = 8192 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") # ------------------------------ ## 注意嵌套括号!!!!!! ## 先有思路,再写代码,别着急!!! ## 先有朴素解法,不要有思维定式,试着换思路解决 ## 精度 print("%.10f" % ans) ## sqrt:int(math.sqrt(n))+1 ## 字符串拼接不要用+操作,会超时 ## 二进制转换:bin(1)[2:].rjust(32,'0') ## array copy:cur=array[::] ## oeis(CROSSREFS):example 1, 3, _, 1260, _, _, _, _, _, 12164510040883200 ## sqrt:Decimal(x).sqrt()避免精度误差 ## 无穷大表示:float('inf') ## py 10**6 排序+双指针 3秒可能TLE ## 按区间右端点排序,current.left>pre.right,贪心求不相交区间的最大个数 ## 加法>位运算 def main(): n, k = map(int, input().split()) odd = [x for x in range(1, 2 * n + 1, 2)] even = [x for x in range(2, 2 * n + 2, 2)] # print(odd,even) odd.reverse() even.reverse() # print(res) i = 0 while k > 0: odd[i], odd[i + 1] = odd[i + 1], odd[i] i += 2 k -= 1 res = odd + even print(" ".join([str(x) for x in res])) if __name__ == "__main__": main() ```
instruction
0
55,944
12
111,888
No
output
1
55,944
12
111,889
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` n,k=input().split() n=int(n) k=int(k) l=[i for i in range(1,2*n+1)] for i in range(1,k+1): x=2*i-1 y=2*i l[x],l[y]=l[y],l[x] for i in range(2*n): print(l[i],end=" ") ```
instruction
0
55,945
12
111,890
No
output
1
55,945
12
111,891
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') input = sys.stdin.readline n, k = list(map(int, input().split())) ans = list(range(1, 2*n+1)) for i in range(1, k+1): ans[2*k], ans[2*k-1] = ans[2*k-1], ans[2*k] print(*ans) ```
instruction
0
55,946
12
111,892
No
output
1
55,946
12
111,893
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A permutation p is an ordered group of numbers p1, p2, ..., pn, consisting of n distinct positive integers, each is no more than n. We'll define number n as the length of permutation p1, p2, ..., pn. Simon has a positive integer n and a non-negative integer k, such that 2k ≤ n. Help him find permutation a of length 2n, such that it meets this equation: <image>. Input The first line contains two integers n and k (1 ≤ n ≤ 50000, 0 ≤ 2k ≤ n). Output Print 2n integers a1, a2, ..., a2n — the required permutation a. It is guaranteed that the solution exists. If there are multiple solutions, you can print any of them. Examples Input 1 0 Output 1 2 Input 2 1 Output 3 2 1 4 Input 4 0 Output 2 7 4 6 1 3 5 8 Note Record |x| represents the absolute value of number x. In the first sample |1 - 2| - |1 - 2| = 0. In the second sample |3 - 2| + |1 - 4| - |3 - 2 + 1 - 4| = 1 + 3 - 2 = 2. In the third sample |2 - 7| + |4 - 6| + |1 - 3| + |5 - 8| - |2 - 7 + 4 - 6 + 1 - 3 + 5 - 8| = 12 - 12 = 0. Submitted Solution: ``` import sys # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') input = sys.stdin.readline n, k = list(map(int, input().split())) ans = list(range(0, 2*n+1)) for i in range(1, k+1): ans[2*k], ans[2*k-1] = ans[2*k-1], ans[2*k] print(*ans[1:]) ```
instruction
0
55,947
12
111,894
No
output
1
55,947
12
111,895
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You come home and fell some unpleasant smell. Where is it coming from? You are given an array a. You have to answer the following queries: 1. You are given two integers l and r. Let ci be the number of occurrences of i in al: r, where al: r is the subarray of a from l-th element to r-th inclusive. Find the Mex of {c0, c1, ..., c109} 2. You are given two integers p to x. Change ap to x. The Mex of a multiset of numbers is the smallest non-negative integer not in the set. Note that in this problem all elements of a are positive, which means that c0 = 0 and 0 is never the answer for the query of the second type. Input The first line of input contains two integers n and q (1 ≤ n, q ≤ 100 000) — the length of the array and the number of queries respectively. The second line of input contains n integers — a1, a2, ..., an (1 ≤ ai ≤ 109). Each of the next q lines describes a single query. The first type of query is described by three integers ti = 1, li, ri, where 1 ≤ li ≤ ri ≤ n — the bounds of the subarray. The second type of query is described by three integers ti = 2, pi, xi, where 1 ≤ pi ≤ n is the index of the element, which must be changed and 1 ≤ xi ≤ 109 is the new value. Output For each query of the first type output a single integer — the Mex of {c0, c1, ..., c109}. Example Input 10 4 1 2 3 1 1 2 2 2 9 9 1 1 1 1 2 8 2 7 1 1 2 8 Output 2 3 2 Note The subarray of the first query consists of the single element — 1. The subarray of the second query consists of four 2s, one 3 and two 1s. The subarray of the fourth query consists of three 1s, three 2s and one 3. Submitted Solution: ``` from collections import defaultdict n,q = map(int,input().split()) a=list(map(int,input().split())) w = [defaultdict(int) for i in range(1000)] for i in range(len(a)): w[i//100][a[i]]+=1 for quey in range(q): t,l,r = map(int,input().split()) l-=1 if t==1: r-=1 if r-l>=100: M=defaultdict(int) r_ = r//100 l_=(l+99)//100 for e,cou in w[r_].items(): M[e]=cou-w[l_][e] for i in range(l,l_*100+1): M[a[i]]+=1 for i in range(r_*100,r+1): M[a[i]]+=1 else: M=defaultdict(int) for i in range(l,r+1): M[a[i]]+=1 M=set(list(M.values())) u=1 while u in M: u+=1 print(u) else: p_ = (l+99)//100 for i in range(p_,1000): w[i][a[l]]-=1 w[i][r]+=1 a[l]=r ```
instruction
0
56,147
12
112,294
No
output
1
56,147
12
112,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You come home and fell some unpleasant smell. Where is it coming from? You are given an array a. You have to answer the following queries: 1. You are given two integers l and r. Let ci be the number of occurrences of i in al: r, where al: r is the subarray of a from l-th element to r-th inclusive. Find the Mex of {c0, c1, ..., c109} 2. You are given two integers p to x. Change ap to x. The Mex of a multiset of numbers is the smallest non-negative integer not in the set. Note that in this problem all elements of a are positive, which means that c0 = 0 and 0 is never the answer for the query of the second type. Input The first line of input contains two integers n and q (1 ≤ n, q ≤ 100 000) — the length of the array and the number of queries respectively. The second line of input contains n integers — a1, a2, ..., an (1 ≤ ai ≤ 109). Each of the next q lines describes a single query. The first type of query is described by three integers ti = 1, li, ri, where 1 ≤ li ≤ ri ≤ n — the bounds of the subarray. The second type of query is described by three integers ti = 2, pi, xi, where 1 ≤ pi ≤ n is the index of the element, which must be changed and 1 ≤ xi ≤ 109 is the new value. Output For each query of the first type output a single integer — the Mex of {c0, c1, ..., c109}. Example Input 10 4 1 2 3 1 1 2 2 2 9 9 1 1 1 1 2 8 2 7 1 1 2 8 Output 2 3 2 Note The subarray of the first query consists of the single element — 1. The subarray of the second query consists of four 2s, one 3 and two 1s. The subarray of the fourth query consists of three 1s, three 2s and one 3. Submitted Solution: ``` def main(cin, mnoj): for i in range(cin[1]): mex = 1 c = list(map(int, input().split())) if (c[0] == 1): cur = mnoj[c[1] - 1:c[2]] #print(cur) # print(max(cur) - min(cur)) # print(min(cur)+1) set_cur = set(cur) while mex in set_cur: mex += 1 print(mex) if (c[0] == 2): mnoj[c[1]] = c[2] a = list(map(int, input().split())) b = list(map(int, input().split())) a = main(a, b) ```
instruction
0
56,148
12
112,296
No
output
1
56,148
12
112,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You come home and fell some unpleasant smell. Where is it coming from? You are given an array a. You have to answer the following queries: 1. You are given two integers l and r. Let ci be the number of occurrences of i in al: r, where al: r is the subarray of a from l-th element to r-th inclusive. Find the Mex of {c0, c1, ..., c109} 2. You are given two integers p to x. Change ap to x. The Mex of a multiset of numbers is the smallest non-negative integer not in the set. Note that in this problem all elements of a are positive, which means that c0 = 0 and 0 is never the answer for the query of the second type. Input The first line of input contains two integers n and q (1 ≤ n, q ≤ 100 000) — the length of the array and the number of queries respectively. The second line of input contains n integers — a1, a2, ..., an (1 ≤ ai ≤ 109). Each of the next q lines describes a single query. The first type of query is described by three integers ti = 1, li, ri, where 1 ≤ li ≤ ri ≤ n — the bounds of the subarray. The second type of query is described by three integers ti = 2, pi, xi, where 1 ≤ pi ≤ n is the index of the element, which must be changed and 1 ≤ xi ≤ 109 is the new value. Output For each query of the first type output a single integer — the Mex of {c0, c1, ..., c109}. Example Input 10 4 1 2 3 1 1 2 2 2 9 9 1 1 1 1 2 8 2 7 1 1 2 8 Output 2 3 2 Note The subarray of the first query consists of the single element — 1. The subarray of the second query consists of four 2s, one 3 and two 1s. The subarray of the fourth query consists of three 1s, three 2s and one 3. Submitted Solution: ``` from collections import defaultdict n,q = map(int,input().split()) a=list(map(int,input().split())) w = [defaultdict(int) for i in range(400)] for i in range(len(a)): w[i//300][a[i]]+=1 w=[defaultdict(int)]+w for quey in range(q): t,l,r = map(int,input().split()) l-=1 if t==1: r-=1 if r-l>=300: M=defaultdict(int) r_ = r//300 l_=l//300 for e,cou in w[r_].items(): M[e]=cou-w[l_][e] for i in range(l,l_*300+1): M[a[i]]+=1 for i in range(r_*300,r+1): M[a[i]]+=1 else: M=defaultdict(int) for i in range(l,r+1): M[a[i]]+=1 M=set(list(M.values())) u=1 while u in M: u+=1 print(u) else: p_ = l//300 for i in range(p_,400): w[i][a[l]]-=1 w[i][r]+=1 a[l]=r ```
instruction
0
56,149
12
112,298
No
output
1
56,149
12
112,299
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,576
12
113,152
Tags: binary search, combinatorics Correct Solution: ``` import math teststring = """123 42 24 """ online = "Problem_C" not in __file__ true, false = True, False if True: def spitout(): for c in teststring.splitlines(): yield c _ito = spitout() if not online: def input(): return next(_ito) def build_enum(*a): built = dict() for i, c in enumerate(a): built[c] = i return lambda x: built[x] # T = 1 ##-----------------start coding----------------- def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a): g, x, y = egcd(a, P) if g != 1: raise Exception('modular inverse does not exist') else: return x % P [n, x, pos] = map(int, input().split(" ")) P = 1000000007 a = b = 0 l = 0 r = n while l < r: m = int((l+r)/2) if m <= pos: l = m + 1 if m < pos: a += 1 else: r = m b += 1 if a > x-1 or b > n-x: ans = 0 else: ans = 1 fac = [1]*(n+1) for i in range(n): fac[i+1] = (fac[i]*(i+1)) % P ans = (ans * fac[x-1]) % P ans = (ans * fac[n-x]) % P ans = (ans * fac[n-a-b-1]) % P ans = (ans * modinv(fac[x-1-a])) % P ans = (ans * modinv(fac[n-x-b])) % P print(ans) # print('Case #{}: {}'.format(ti, '...')) ```
output
1
56,576
12
113,153
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,577
12
113,154
Tags: binary search, combinatorics Correct Solution: ``` from math import factorial n, x, pos = map(int, input().split()) MOD = (10**9) + 7 small, big, ans = x-1, n-x, 1 l, r = 0, n while l < r: mid = (l + r) //2 if mid < pos: ans *= small small -= 1 l = mid + 1 elif mid > pos: ans *= big big -= 1 r = mid else: l = mid+1 ans *= factorial(small + big) print(ans%MOD) ```
output
1
56,577
12
113,155
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,578
12
113,156
Tags: binary search, combinatorics Correct Solution: ``` import math yes = "YES" no = "NO" lower = "L" higher = "H" same = "O" def bin_search(a, x): left = 0 right = len(a) res = [] while left < right: mid = (left + right) // 2 if a[mid] < x: left = mid + 1 res.append(higher) elif a[mid] == x: left = mid + 1 res.append(same) else: right = mid res.append(lower) return res def solve(): numbers = list(map(int, input().split(" "))) options = bin_search([i for i in range(numbers[0])], numbers[2]) res = 1 higher_numbers, lower_numbers = numbers[0] - numbers[1], numbers[1] - 1 for o in options: if o == higher: res *= lower_numbers lower_numbers -= 1 elif o == lower: res *= higher_numbers higher_numbers -= 1 res *= math.factorial(numbers[0] - len(options)) print(res %(10**9 + 7)) return None if __name__ == "__main__": solve() ```
output
1
56,578
12
113,157
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,579
12
113,158
Tags: binary search, combinatorics Correct Solution: ``` mod=10**9+7 def modExp(a,n,m=10**9+7): if n==0: return 1 elif n==1: return a else: while n>=2: if n%2==0: n=n//2 return modExp(((a%m)*(a%m))%m,n,m) else: n=(n-1)//2 return ((a%m)*modExp(((a%m)*(a%m))%m,n,m)%m)%m def nCr(n,r): return (dic[n]*modExp((dic[n-r]*dic[r])%mod,mod-2))%mod #input n,x,p=map(int,input().split()) dic={0:1} for i in range(1,1001): dic[i]=dic[i-1]*i dic[i]%=mod def binS(n,p): l=0 r=n g=0 s=0 while l<r: m=(l+r)//2 if m>p: r=m g+=1 else: if m!=p: s+=1 l=m+1 return s,g s,g=binS(n,p) if n-x<g or x-1<s: print(0) else: out=(nCr(n-x,g)*dic[g])%mod out*=(nCr(x-1,s)*dic[s])%mod out%=mod out*=dic[n-g-s-1] out%=mod print(out) ```
output
1
56,579
12
113,159
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,580
12
113,160
Tags: binary search, combinatorics Correct Solution: ``` # Legends Always Come Up with Solution # Author: Manvir Singh import os from io import BytesIO, IOBase import sys from collections import defaultdict,deque,Counter from bisect import * from math import sqrt,pi,ceil,log import math from itertools import permutations from copy import deepcopy from sys import setrecursionlimit def main(): n,x,pos = map(int,input().split()) mod=10**9+7 f=[1] for i in range(1,1001): f.append((f[-1]*i)%mod) lo=0 hi=n b=x-1 c=n-x ans=1 while lo<hi: mid=(lo+hi)//2 if mid<pos: ans=(ans*b)%mod b-=1 lo=mid+1 elif mid>pos: ans=(ans*c)%mod c-=1 hi=mid else: lo=mid+1 print((ans*f[b+c])%mod) # 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") if __name__ == "__main__": main() ```
output
1
56,580
12
113,161
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,581
12
113,162
Tags: binary search, combinatorics Correct Solution: ``` import sys input = sys.stdin.readline I = lambda : list(map(int,input().split())) def ncr(n,r,p=10**9+7): if n<r: return 0 num=1 r=min(r,n-r) ct=1 while ct <=r: num=(num*n)%p num=(num*pow(ct,p-2,p))%p ct+=1;n-=1 return num%p n,x,pos=I() md=10**9+7 ft=[1,1,2] for i in range(3,1003): ft.append((ft[-1]*i)%md) an=0 ar=[] lo=0;ri=n while lo<ri: md=(lo+ri)//2 ar.append(md) if md<=pos: lo=md+1 else: ri=md md=10**9+7 a=b=0 for i in ar: if i>pos: a+=1 elif i<pos: b+=1 print((ncr(x-1,b)*ncr(n-x,a)*ft[a]*ft[b]*ft[n-a-b-1])%md) ```
output
1
56,581
12
113,163
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,582
12
113,164
Tags: binary search, combinatorics Correct Solution: ``` n,x,pos = map(int,input().split()) a = [0] * n low,high = x - 1, n - x l,r = 0,n found = False ans = 0 while l < r: m = (l + r) // 2 if pos < m: if high == 0: ans = -1 break a[m] = high high -= 1 r = m else: if m != pos: if low == 0: ans = -1; break a[m] = low low -= 1 l = m + 1 mod = 10**9 + 7 if ans == -1: print(0) else: fans = 1 for i in range(n): if a[i]: fans = (fans * a[i]) % mod left = low + high while left: fans = (fans * left) % mod left -= 1 print(fans) ```
output
1
56,582
12
113,165
Provide tags and a correct Python 3 solution for this coding contest problem. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2).
instruction
0
56,583
12
113,166
Tags: binary search, combinatorics Correct Solution: ``` mod = 10**9+7 n, x, pos = map(int, input().split()) l = 0 r = n lcheck = 0 ucheck = 0 while(l<r): mid = (l+r)//2 if mid<=pos: l = mid+1 if mid!=pos: lcheck+=1 else: r = mid ucheck+=1 ll = x-1 rr = n-x # print(ll, rr, lcheck, ucheck) ans = 1 for i in range(lcheck): ans*=ll ll-=1 for i in range(ucheck): ans*=rr rr-=1 left = n-(lcheck+ucheck)-1 lt = left for i in range(lt): ans*=left left-=1 print(ans%mod) ```
output
1
56,583
12
113,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` def perm(n,r): if n<r: return 0 ans = 1 k = n while k>n-r: ans*=k k-=1 return ans def fact(x): if x<0: return 0 ans = 1 while x: ans*=x x-=1 return ans n, x, p = map(int, input().split()) b = [0]*n left = 0 right = n small = -1 large = 0 while left < right: middle = (left + right) // 2 if middle <= p: left = middle + 1 b[middle] = -1 small += 1 else: right = middle b[middle] = 1 large += 1 # print(*b) ans = perm(x-1,small)*perm(n-x,large)*fact(n-1-small-large) print(ans%(10**9 + 7)) ```
instruction
0
56,584
12
113,168
Yes
output
1
56,584
12
113,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` n,x,p=map(int,input().split()) ans=1 l=x-1 r=n-x b=0 e=n while(b<e): m=b+e m//=2 if p<m: e=m ans=(ans*r)%1000000007 r-=1 n-=1 elif p>m: b=m+1 ans=(ans*l)%1000000007 l-=1 n-=1 else: b=m+1 for i in range(1,n): ans=(ans*i)%1000000007 print(ans) ```
instruction
0
56,585
12
113,170
Yes
output
1
56,585
12
113,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import math import os import sys from fractions import * from sys import * from io import BytesIO, IOBase from itertools import * from collections import * # sys.setrecursionlimit(10**5) if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip # sys.setrecursionlimit(10**6) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input def out(var): sys.stdout.write(str(var)) # for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) def fsep(): return map(float, inp().split()) def inpu(): return int(inp()) # ----------------------------------------------------------------- def regularbracket(t): p = 0 for i in t: if i == "(": p += 1 else: p -= 1 if p < 0: return False else: if p > 0: return False else: return True # ------------------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] <= key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # ------------------------------reverse string(pallindrome) def reverse1(string): pp = "" for i in string[::-1]: pp += i if pp == string: return True return False # --------------------------------reverse list(paindrome) def reverse2(list1): l = [] for i in list1[::-1]: l.append(i) if l == list1: return True return False def mex(list1): # list1 = sorted(list1) p = max(list1) + 1 for i in range(len(list1)): if list1[i] != i: p = i break return p def sumofdigits(n): n = str(n) s1 = 0 for i in n: s1 += int(i) return s1 def perfect_square(n): s = math.sqrt(n) if s == int(s): return True return False # -----------------------------roman def roman_number(x): if x > 15999: return value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] symbol = ["F", "MF", "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] roman = "" i = 0 while x > 0: div = x // value[i] x = x % value[i] while div: roman += symbol[i] div -= 1 i += 1 return roman def soretd(s): for i in range(1, len(s)): if s[i - 1] > s[i]: return False return True # print(soretd("1")) # --------------------------- def countRhombi(h, w): ct = 0 for i in range(2, h + 1, 2): for j in range(2, w + 1, 2): ct += (h - i + 1) * (w - j + 1) return ct def countrhombi2(h, w): return ((h * h) // 4) * ((w * w) // 4) # --------------------------------- def binpow(a, b): if b == 0: return 1 else: res = binpow(a, b // 2) if b % 2 != 0: return res * res * a else: return res * res # ------------------------------------------------------- def binpowmodulus(a, b, m): a %= m res = 1 while (b > 0): if (b & 1): res = res * a % m a = a * a % m b >>= 1 return res # ------------------------------------------------------------- def coprime_to_n(n): result = n i = 2 while (i * i <= n): if (n % i == 0): while (n % i == 0): n //= i result -= result // i i += 1 if (n > 1): result -= result // n return result # -------------------prime def prime(x): if x == 1: return False else: for i in range(2, int(math.sqrt(x)) + 1): if (x % i == 0): return False else: return True def luckynumwithequalnumberoffourandseven(x, n, a): if x >= n and str(x).count("4") == str(x).count("7"): a.append(x) else: if x < 1e12: luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a) luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a) return a def luckynuber(x, n, a): p = set(str(x)) if len(p) <= 2: a.append(x) if x < n: luckynuber(x + 1, n, a) return a #------------------------------------------------------interactive problems def interact(type, x): if type == "r": inp = input() return inp.strip() else: print(x, flush=True) #------------------------------------------------------------------zero at end of factorial of a number def findTrailingZeros(n): # Initialize result count = 0 # Keep dividing n by # 5 & update Count while (n >= 5): n //= 5 count += n return count #-----------------------------------------------merge sort # Python program for implementation of MergeSort def mergeSort(arr): if len(arr) > 1: # Finding the mid of the array mid = len(arr) // 2 # Dividing the array elements L = arr[:mid] # into 2 halves R = arr[mid:] # Sorting the first half mergeSort(L) # Sorting the second half mergeSort(R) i = j = k = 0 # Copy data to temp arrays L[] and R[] while i < len(L) and j < len(R): if L[i] < R[j]: arr[k] = L[i] i += 1 else: arr[k] = R[j] j += 1 k += 1 # Checking if any element was left while i < len(L): arr[k] = L[i] i += 1 k += 1 while j < len(R): arr[k] = R[j] j += 1 k += 1 #-----------------------------------------------lucky number with two lucky any digits res = set() def solve(p, l, a, b,n):#given number if p > n or l > 10: return if p > 0: res.add(p) solve(p * 10 + a, l + 1, a, b,n) solve(p * 10 + b, l + 1, a, b,n) # problem """ n = int(input()) for a in range(0, 10): for b in range(0, a): solve(0, 0) print(len(res)) """ #----------------------------------------------- # endregion------------------------------ """ def main(): n,m = sep() l=[] q=0 if m<=n: for i in range(min(n,m)): l.append([max(n,m)-i,i]) q = max(n,m)-i l.append([q-1,min(n,m)]) else: for i in range(min(m,n)): l.append([min(n,m)-i,i]) q=max(n,m)-i l.append([0,min(n,m)]) print(len(l)) for i in l: print(*i) if __name__ == '__main__': main() """ """ def search(n,x): left =0 right = n cnt=0 while(left<right): cnt+=1 #print(middle) middle = (left+right)//2 #print(middle,left,right) if middle<x: left = middle+1 else: right = middle if left==x or right==x: break return cnt """ def main(): n,x,poss = sep() less = x - 1 large = n - x s = 0 e = n ans = 1 while (s < e): mid = (s + e) // 2 if mid < poss: s = mid + 1 ans *= less less -= 1 elif mid > poss: e = mid ans *= large large -= 1 else: s = mid + 1 less += large if less > 0: for i in range(less, 0, -1): ans *= i print(ans % (10 ** (9) + 7)) if __name__ == '__main__': main() ```
instruction
0
56,586
12
113,172
Yes
output
1
56,586
12
113,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` if __name__ == "__main__": mod = 1000000007 n, x, pos = map(int, input().split()) ans = 1 left = 0 right = n toLeft = n-x toRight = x-1 failed = False c = 0 while left < right: middle = (left + right) // 2 if middle == pos: left = middle + 1 c += 1 elif middle > pos: if toLeft == 0: failed = True break else: ans *= toLeft ans %= mod toLeft -= 1 right = middle c += 1 else: if toRight == 0: failed = True break else: ans *= toRight ans %= mod toRight -= 1 left = middle + 1 c += 1 if failed: print(0) else: for i in range(n-c): ans *= (i+1) ans %= mod print(ans) ```
instruction
0
56,587
12
113,174
Yes
output
1
56,587
12
113,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` x, y, p = map(int, input().split()) sm = 0 bg = 0 hi = x lo = 0 while hi > lo: mid = (hi+lo)//2 if mid < p: sm += 1 lo = mid+1 elif mid > p: bg += 1 hi = mid else: break fac = [1] mod = (10**9)+7 for n in range(1, x+1): fac.append((fac[-1]*n) % mod) def bnp(bs, pw): res = 1 while pw: if pw & 1: res = (res*bs) % mod pw //= 2 bs = (bs*bs) % mod return res % mod def ncr(n, r): if n < r: return 0 return (((fac[n]*bnp(fac[r], mod-2)) % mod)*bnp(fac[n-r], mod-2)) % mod biig = x-y sml = y-1 a = (ncr(biig, bg)*fac[bg]) % mod b = (ncr(sml, sm)*fac[sm]) % mod c = fac[x-sm-bg-1] print((a*b*c) % mod) ```
instruction
0
56,588
12
113,176
No
output
1
56,588
12
113,177
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` factorial=[1,1,2] for i in range(3,1001): factorial.append(i*factorial[-1]) def comb(n,r): c=factorial[n]/(factorial[n-r]) return int(c) n,x,pos=map(int,input().split()) left=0 right=n smaller=0 equal=0 larger=0 while left!=right: mid=(left+right)//2 if pos<mid: larger+=1 right=mid elif pos>mid: smaller+=1 left=mid+1 elif pos==mid: equal+=1 left=mid+1 #print(larger,smaller,equal,x,n,x-1,n-x) if(larger>(n-x)): print(0) elif (smaller>x-1): print(0) else: s=comb(x-1,smaller) l=comb(n-x,larger) fact=factorial[n-smaller-larger-1] num=(s*l*fact) num%=1000000007 print(int(num)) #print(factorial[999]%1000000007) ```
instruction
0
56,589
12
113,178
No
output
1
56,589
12
113,179
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` import math def bins(a,x,pos): posl = [] fl = True left, right = 0, len(a) while left < right: middle = math.floor((left + right) / 2) if a[middle] <= x: left = middle + 1 if middle != pos and fl: posl.append('l') else: fl = False else: right = middle if middle != pos and fl: posl.append('r') else: fl = False return posl n,x,pos = list(map(int,input().split())) a = [0]*(pos) a.append(x) a.extend([x+1]*(n-pos-1)) b = bins(a,x,pos) r, l = b.count('r'), b.count('l') rcount = n-x lcount = x-1 count = n-1 res = 1 ##print('r',r,rcount,'l',l,lcount) for i in range(r): res *= rcount rcount -= 1 count -= 1 for i in range(l): res *= lcount lcount -= 1 count -= 1 for i in range(1,count+1): res *= i % 1000000007 if pos != n-1 and x != n: print(res % 1000000007) else: print(0) ```
instruction
0
56,590
12
113,180
No
output
1
56,590
12
113,181
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Andrey thinks he is truly a successful developer, but in reality he didn't know about the binary search algorithm until recently. After reading some literature Andrey understood that this algorithm allows to quickly find a certain number x in an array. For an array a indexed from zero, and an integer x the pseudocode of the algorithm is as follows: <image> Note that the elements of the array are indexed from zero, and the division is done in integers (rounding down). Andrey read that the algorithm only works if the array is sorted. However, he found this statement untrue, because there certainly exist unsorted arrays for which the algorithm find x! Andrey wants to write a letter to the book authors, but before doing that he must consider the permutations of size n such that the algorithm finds x in them. A permutation of size n is an array consisting of n distinct integers between 1 and n in arbitrary order. Help Andrey and find the number of permutations of size n which contain x at position pos and for which the given implementation of the binary search algorithm finds x (returns true). As the result may be extremely large, print the remainder of its division by 10^9+7. Input The only line of input contains integers n, x and pos (1 ≤ x ≤ n ≤ 1000, 0 ≤ pos ≤ n - 1) — the required length of the permutation, the number to search, and the required position of that number, respectively. Output Print a single number — the remainder of the division of the number of valid permutations by 10^9+7. Examples Input 4 1 2 Output 6 Input 123 42 24 Output 824071958 Note All possible permutations in the first test case: (2, 3, 1, 4), (2, 4, 1, 3), (3, 2, 1, 4), (3, 4, 1, 2), (4, 2, 1, 3), (4, 3, 1, 2). Submitted Solution: ``` import math n, x, p = [int(s) for s in input().split(' ')] lowers = 0 highers = 0 l = 0 h = n while l < h: print(l, h) m = (l + h) // 2 print(m) if m > p: highers += 1 h = m elif m < p: lowers += 1 l = m + 1 else: l = m + 1 #print(lowers, highers, n - 1 - lowers - highers) if lowers > x - 1: ans = 0 elif highers > n - x: ans = 0 else: ans = 1 for i in range(lowers): ans = (ans * (x - 1 - i)) % (10 ** 9 + 7) for i in range(highers): ans = (ans * (n - x - i)) % (10 ** 9 + 7) for i in range(n - 1 - lowers - highers): ans = (ans * (i + 1)) % (10 ** 9 + 7) print(ans) ```
instruction
0
56,591
12
113,182
No
output
1
56,591
12
113,183
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≤ n ≤ 2 ⋅ 10^5, -10^9 ≤ b_i ≤ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9) — the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 ⋅ 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,628
12
113,256
Tags: data structures, greedy, implementation Correct Solution: ``` def solve(n, a): prev = a[0] r = [10 ** 9]; l = [-r[0]] for i in range(1, n): if a[i] < prev: if a[i] < l[-1]: return False elif a[i] == l[-1]: l.pop() r.append(prev) elif a[i] > prev: if a[i] > r[-1]: return False elif a[i] == r[-1]: r.pop() l.append(prev) prev = a[i] return True def main(): t = int(input()) for _ in range(t): n = int(input()) a = list(map(int, input().split())) if solve(n, a): print("YES") else: print("NO") main() ```
output
1
56,628
12
113,257
Provide tags and a correct Python 3 solution for this coding contest problem. Uh oh! Ray lost his array yet again! However, Omkar might be able to help because he thinks he has found the OmkArray of Ray's array. The OmkArray of an array a with elements a_1, a_2, …, a_{2k-1}, is the array b with elements b_1, b_2, …, b_{k} such that b_i is equal to the median of a_1, a_2, …, a_{2i-1} for all i. Omkar has found an array b of size n (1 ≤ n ≤ 2 ⋅ 10^5, -10^9 ≤ b_i ≤ 10^9). Given this array b, Ray wants to test Omkar's claim and see if b actually is an OmkArray of some array a. Can you help Ray? The median of a set of numbers a_1, a_2, …, a_{2i-1} is the number c_{i} where c_{1}, c_{2}, …, c_{2i-1} represents a_1, a_2, …, a_{2i-1} sorted in nondecreasing order. Input Each test contains multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases. Description of the test cases follows. The first line of each test case contains an integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the array b. The second line contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9) — the elements of b. It is guaranteed the sum of n across all test cases does not exceed 2 ⋅ 10^5. Output For each test case, output one line containing YES if there exists an array a such that b_i is the median of a_1, a_2, ..., a_{2i-1} for all i, and NO otherwise. The case of letters in YES and NO do not matter (so yEs and No will also be accepted). Examples Input 5 4 6 2 1 3 1 4 5 4 -8 5 6 -7 2 3 3 4 2 1 2 3 Output NO YES NO YES YES Input 5 8 -8 2 -6 -5 -4 3 3 2 7 1 1 3 1 0 -2 -1 7 6 12 8 6 2 6 10 6 5 1 2 3 6 7 5 1 3 4 3 0 Output NO YES NO NO NO Note In the second case of the first sample, the array [4] will generate an OmkArray of [4], as the median of the first element is 4. In the fourth case of the first sample, the array [3, 2, 5] will generate an OmkArray of [3, 3], as the median of 3 is 3 and the median of 2, 3, 5 is 3. In the fifth case of the first sample, the array [2, 1, 0, 3, 4, 4, 3] will generate an OmkArray of [2, 1, 2, 3] as * the median of 2 is 2 * the median of 0, 1, 2 is 1 * the median of 0, 1, 2, 3, 4 is 2 * and the median of 0, 1, 2, 3, 3, 4, 4 is 3. In the second case of the second sample, the array [1, 0, 4, 3, 5, -2, -2, -2, -4, -3, -4, -1, 5] will generate an OmkArray of [1, 1, 3, 1, 0, -2, -1], as * the median of 1 is 1 * the median of 0, 1, 4 is 1 * the median of 0, 1, 3, 4, 5 is 3 * the median of -2, -2, 0, 1, 3, 4, 5 is 1 * the median of -4, -2, -2, -2, 0, 1, 3, 4, 5 is 0 * the median of -4, -4, -3, -2, -2, -2, 0, 1, 3, 4, 5 is -2 * and the median of -4, -4, -3, -2, -2, -2, -1, 0, 1, 3, 4, 5, 5 is -1 For all cases where the answer is NO, it can be proven that it is impossible to find an array a such that b is the OmkArray of a.
instruction
0
56,629
12
113,258
Tags: data structures, greedy, implementation Correct Solution: ``` for _ in range(int(input())): n = int(input()) b = list(map(int,input().split())) next = dict() prev = dict() curr = b[0] next[curr] = "!" prev[curr] = "!" fine = True for i in b: if i>curr: if next[curr] == "!": next[curr] = i prev[i] = curr next[i] = "!" elif next[curr]<i: fine = False break elif next[curr]>i: prev[next[curr]] = i next[i] = next[curr] next[curr] = i prev[i] = curr elif i<curr: if prev[curr] == "!": prev[curr] = i prev[i] = "!" next[i] = curr elif i<prev[curr]: fine = False break elif i>prev[curr]: next[prev[curr]] = i prev[i] = prev[curr] prev[curr] = i next[i] = curr curr = i if fine: print("YES") else: print("NO") ```
output
1
56,629
12
113,259