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 | 47,211 | 12 | 94,422 |
Tags: combinatorics, data structures, dsu, greedy, implementation
Correct Solution:
```
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.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 = self.os.read(self._fd, max(self.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:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 998244353
"""
Segment tree. How do we determine next lex
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
1 4 2 3
1 4 3 2
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 1 3
2 4 3 1
What is the qth permutation
"""
def solve():
ans = 1
N, K = getInts()
A = getInts()
C = []
for i, a in enumerate(A):
C.append((a,i))
C.sort()
B = getInts()
to_use = set(B)
#print(C)
for b in B:
ind = C[b-1][1]
ops = [ind+1,ind-1]
tot = 0
for op in ops:
if op < 0 or op > N-1:
continue
if A[op] not in to_use:
tot += 1
if not tot:
return 0
ans *= tot
ans %= MOD
to_use.remove(b)
#print(ans)
return ans
for _ in range(getInt()):
print(solve())
``` | output | 1 | 47,211 | 12 | 94,423 |
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 | 47,212 | 12 | 94,424 |
Tags: combinatorics, data structures, dsu, greedy, implementation
Correct Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
###########################
# Sorted list
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def 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()))
``` | output | 1 | 47,212 | 12 | 94,425 |
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
input = sys.stdin.readline
def pi():
return(int(input()))
def pl():
return(int(input(), 16))
def ti():
return(list(map(int,input().split())))
def ts():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def main():
B();
nMap = [0 for i in range(200005)];
indexMap = [[] for i in range(200005)];
mod = 998244353;
def B():
t = pi();
while t:
t -= 1;
[n,k] = ti();
a = ti();
b = ti();
mx = 0;
for i in range(n):
mx = max(mx, a[i]);
for i in range(mx+1):
nMap[i] = 0;
indexMap[i].clear();
for i in range(k):
nMap[b[i]] += 1;
for i in range(n):
indexMap[a[i]].append(i);
res = 1;
for i in range(k):
nMap[b[i]] = 0;
l = indexMap[b[i]];
temp = 0;
for j in range(len(l)):
if l[j]-1 >= 0:
if nMap[a[l[j]-1]] == 0: temp += 1;
if l[j]+1 < n:
if nMap[a[l[j]+1]] == 0: temp += 1;
res *= temp;
print(res % mod);
main();
``` | instruction | 0 | 47,213 | 12 | 94,426 |
Yes | output | 1 | 47,213 | 12 | 94,427 |
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
input = stdin.readline
def main():
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()))
where = [0] * n
for i in range(n):
where[a[i] - 1] = i
for i in range(k):
b[i] = where[b[i] - 1]
sp = [-1] * n
for i in range(k):
sp[b[i]] = i
def solve(sp):
res = [0] * k
mx = n
for i in reversed(range(0, n)):
if sp[i] == -1:
mx = -1
else:
res[sp[i]] = 1 if mx < sp[i] else 0
mx = max(mx, sp[i])
return res
ans1 = solve(sp)
sp.reverse()
ans2 = solve(sp)
ans = 1
for i in range(k):
ans *= ans1[i] + ans2[i]
ans %= MOD
print(ans)
main()
``` | instruction | 0 | 47,214 | 12 | 94,428 |
Yes | output | 1 | 47,214 | 12 | 94,429 |
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.buffer.readline
T = int(input())
for _ in range(T):
n, k = map(int, input().split())
al, bl = list(map(int, input().split())), list(map(int, input().split()))
am, bm = dict([]), set(bl)
for i in range(n):
left = 0 if i == 0 else al[i-1]
right = 0 if i == n-1 else al[i+1]
am[al[i]] = (left, right)
cc, MOD = 1, 998244353
for u in bl:
left, right = am[u]
lcc = (left > 0 and left not in bm) + (right > 0 and right not in bm)
cc = (cc*lcc)%MOD
if cc == 0: break
am.pop(u)
bm.remove(u)
if left > 0: (l, r) = am[left]; am[left] = (l, right)
if right > 0: (l, r) = am[right]; am[right] = (left, r)
print(cc)
``` | instruction | 0 | 47,215 | 12 | 94,430 |
Yes | output | 1 | 47,215 | 12 | 94,431 |
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:
```
"""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)
``` | instruction | 0 | 47,216 | 12 | 94,432 |
Yes | output | 1 | 47,216 | 12 | 94,433 |
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 | 47,217 | 12 | 94,434 |
No | output | 1 | 47,217 | 12 | 94,435 |
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 | 47,218 | 12 | 94,436 |
No | output | 1 | 47,218 | 12 | 94,437 |
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 | 47,219 | 12 | 94,438 |
No | output | 1 | 47,219 | 12 | 94,439 |
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, stdout, setrecursionlimit
from collections import defaultdict as dd
from collections import deque
from math import gcd
# setrecursionlimit(int(1e7))
input = stdin.readline
flush = stdout.flush
p = 998244353
tc = 1
tc = int(input())
for _ in range(tc):
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
remb = set(b)
inA = {}
for i in range(n):
inA[a[i]] = i
before = [i-1 for i in range(n)]
after = [i+1 for i in range(n)]
after[n-1] = -1
ans = 1
for i in b:
index = inA[i]
before_i = before[index]
before_e = a[before_i]
after_i = after[index]
after_e = a[after_i]
if (before_e in remb) and (after_e in remb):
ans = 0
break
elif (after_e in remb):
before_before_i = before[before_i]
after[before_before_i] = index
before[index] = before_before_i
elif (before_e in remb):
after_after_i = after[after_i]
before[after_after_i] = index
after[index] = after_after_i
else:
ans = (ans * 2) % p
remb.remove(i)
print(ans)
``` | instruction | 0 | 47,220 | 12 | 94,440 |
No | output | 1 | 47,220 | 12 | 94,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,675 | 12 | 95,350 |
Tags: brute force, implementation, math
Correct Solution:
```
n, k = map(int, input().split())
A = list(map(int, input().split()))
from itertools import accumulate
C = [0]+A
C = list(accumulate(C))
A = [0]+A
P = [0]*(n+1)
x = 0
# P[i]: iの直前にある2以上の項のindex
for i in range(1, n+1):
P[i] = x
if A[i] > 1:
x = i
INF = 2*10**18+1
ans = 0
for i in range(1, n+1):
p = 1
j = i
while j:
if p*A[j] < INF:
s = C[i]-C[j-1]
p *= A[j]
if p%k == 0:
d = p//k-s
# j-P[j]-1: P[j]とjの間にある1の個数
if 0 <= d <= j-P[j]-1:
ans += 1
else:
break
j = P[j]
print(ans)
``` | output | 1 | 47,675 | 12 | 95,351 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,676 | 12 | 95,352 |
Tags: brute force, implementation, math
Correct Solution:
```
n,k = map(int,input().split())
A = list(map(int,input().split()))
A = [0]+A;
x = 0
prev = [0 for i in range(n+1)]
sm = [0 for i in range(n+1)]
for i in range(1,n+1):
prev[i] = x
if A[i]>1:
x = i
sm[i] = A[i]+sm[i-1]
lim = int(2*(10**18))
ans = 0
for i in range(1,n+1):
p = 1
j = i
while j:
if lim//A[j]>p:
s = sm[i]-sm[j-1]
p *= A[j]
sx = s+j-1-prev[j]
if p%k == 0 and p>=k*s and p<=k*sx:
ans += 1
else:
break
j = prev[j]
print(ans)
``` | output | 1 | 47,676 | 12 | 95,353 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,677 | 12 | 95,354 |
Tags: brute force, implementation, math
Correct Solution:
```
# https://codeforces.com/problemset/problem/992/D
n, k = map(int, input().split())
a = list(map(int, input().split()))
max_ = 10 ** 13 + 1
def get(l, r, x):
min_ = min(l,r)
max_ = max(l,r)
if x <= min_:
return x + 1
if x <= max_:
return min_ + 1
return l+r+1-x
def solve(a, k):
cnt = 0
arr = [i for i, x in enumerate(a) if x>1]
n_ = len(arr)
for i in range(n_-1):
curS = 0
curP = 1
l = arr[i] if i == 0 else arr[i] - arr[i-1] - 1
for j in range(i, n_):
ind = arr[j]
curS += a[ind]
curP *= a[ind]
if curP > max_:
break
if curP % curS == 0:
if curP // curS == k:
#print(arr[i], arr[j], curP, curS)
cnt+=1
r = arr[j+1] - arr[j] - 1
x = curP // k - curS
if curP % k == 0 and x > 0 and x <= l + r:
#print(arr[i], arr[j], curP, curS)
cnt+=get(l, r, x)
curS += r
if k==1:
cnt+=len(a)-n_
return cnt
ans=0
a.append(max_)
ans += solve(a, k)
print(ans)
``` | output | 1 | 47,677 | 12 | 95,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,678 | 12 | 95,356 |
Tags: brute force, implementation, math
Correct Solution:
```
n, k = map(int, input().split())
flag = [0 for i in range(0, n)]
a = list(map(int, input().split()))
r = [-1 for i in range(0, n)]
i = 0
while i < n:
if a[i] != 1:
i = i + 1
continue
j = i
while j < n and a[j] == 1:
j = j + 1
while i < j:
r[i] = j - 1
i = i + 1
ans = 0
maxn = 2 ** 63 - 1
for i in range(0, n):
p = 1
s = 0
j = i
while j < n:
if a[j] != 1:
p = p * a[j]
s = s + a[j]
if p % s == 0 and p // s == k:
ans = ans + 1
#print(1)
#print('p =', p, 's =', s)
#print('i =', i, 'j =', j)
j = j + 1
else:
if p % k == 0 and (p // k - s > 0 and (p // k - s) <= (r[j] - j + 1)):
ans = ans + 1
#print(2)
#print('p =', p, 's =', s)
#print('i =', i, 'j =', j)
s = s + r[j] - j + 1
j = r[j] + 1
if p >= maxn:
break
print(ans)
``` | output | 1 | 47,678 | 12 | 95,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,679 | 12 | 95,358 |
Tags: brute force, implementation, math
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
ones_ser_ie = [0 for _ in range(n)]
cur_ones_ser_ie = 0
ones_in_tail_i = 0
for i in reversed(range(n)):
if a[i] == 1:
ones_in_tail_i += 1
cur_ones_ser_ie += 1
else:
cur_ones_ser_ie = 0
ones_ser_ie[i] = cur_ones_ser_ie
res = 0
for i in range(n):
p = 1
s = 0
j = i
ones_in_tail_j = ones_in_tail_i
while j < n:
if a[j] == 1:
cur_ones_ser_ie = ones_ser_ie[j]
if p % k == 0 and 1 <= p//k-s <= cur_ones_ser_ie:
res += 1
ones_in_tail_j -= cur_ones_ser_ie
s += cur_ones_ser_ie
j += cur_ones_ser_ie
else:
p *= a[j]
s += a[j]
if p == s * k:
res += 1
elif p > (s + ones_in_tail_j) * k:
break
j += 1
if a[i] == 1:
ones_in_tail_i -= 1
print(res)
``` | output | 1 | 47,679 | 12 | 95,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,680 | 12 | 95,360 |
Tags: brute force, implementation, math
Correct Solution:
```
n,k = map(int,input().split())
A = list(map(int,input().split()))
A = [0]+A;
x = 0
prev = [0 for i in range(n+1)]
sm = [0 for i in range(n+1)]
for i in range(1,n+1):
prev[i] = x
if A[i]>1:
x = i
sm[i] = A[i]+sm[i-1]
lim = int(2*(10**18))
ans = 0
for i in range(1,n+1):
p = 1
j = i
while j:
if lim//A[j]>p:
s = sm[i]-sm[j-1]
p *= A[j]
if p%k == 0 and p//k>=s and j-1-prev[j]>=p/k-s:
ans += 1
else:
break
j = prev[j]
print(ans)
``` | output | 1 | 47,680 | 12 | 95,361 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,681 | 12 | 95,362 |
Tags: brute force, implementation, math
Correct Solution:
```
n,k=map(int, input().split())
v=list(map(int, input().split()))
pos, pref=[-1], []
ans=0
for i in range(n):
if v[i]!=1:
pos.append(i)
if v[i]==1 and k==1:
ans+=1
if i:
pref.append(pref[-1]+v[i])
else:
pref.append(v[i])
pos.append(n)
m=len(pos)
#print("m",m)
inf=int(2e18+10)
for i in range(1,m-1):
p=1
for j in range(i, m-1):
p=p*v[pos[j]]
if p>inf:
break
s = pref[pos[j]];
if pos[i]:
s-=pref[pos[i]-1]
if s*k==p:
ans+=1
d=p-s*k
if d>0 and d%k==0:
w= d//k
f=min(pos[i]-pos[i-1]-1,w)
b=min(pos[j+1]-pos[j]-1, w)
if f+b<w:
continue
ans+=f+b-w+1
#print(v[pos[i]], v[pos[j]])
print(ans)
``` | output | 1 | 47,681 | 12 | 95,363 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>. | instruction | 0 | 47,682 | 12 | 95,364 |
Tags: brute force, implementation, math
Correct Solution:
```
#!/usr/bin/env python3
[n, k] = map(int, input().strip().split())
ais = list(map(int, input().strip().split()))
n1 = ais.count(1)
one_serie = [0 for _ in range(n)]
for i in reversed(range(n)):
if ais[i] == 1:
one_serie[i] = (0 if i == n - 1 else one_serie[i + 1]) + 1
n1_head = 0
count = 0
for i in range(n):
p = 1
s = 0
if i > 0 and ais[i - 1] == 1:
n1_head += 1
n1_tail = n1 - n1_head
j = i
while j < n:
if ais[j] == 1:
if p % k == 0 and 1 <= p // k - s <= one_serie[j]:
count += 1
n1_tail -= one_serie[j]
s += one_serie[j]
j += one_serie[j]
else:
p *= ais[j]
s += ais[j]
if p == s * k:
count += 1
elif p > (s + n1_tail) * k:
break
j += 1
print (count)
``` | output | 1 | 47,682 | 12 | 95,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>.
Submitted Solution:
```
from sys import stdin
import math
# stdin = open('in')
n, k = map(int, stdin.readline().split())
a = [int(x) for x in stdin.readline().split()]
nxt = [-1]*n
pref = []
f, s = -1, 0
for i in range(n):
s += a[i]
pref.append(s)
nxt[n-1-i] = f
if a[n-1-i] != 1:
f = n-1-i
ans = 0
for i in range(n):
pos, cur = i, 0
prod = 1
while 1:
if prod > 1e18:
break
prod *= a[pos]
cur += a[pos]
if prod == k*cur:
ans += 1
nt = nxt[pos]
if nt == -1:
ones = n-1-pos
if k*cur < prod and k*(cur+ones) >= prod:
ans += 1
break
ones = nt - pos - 1
if k*cur < prod and k*(cur+ones) >= prod and prod%k == 0:
ans += 1
cur += ones
pos = nt
print(ans)
``` | instruction | 0 | 47,683 | 12 | 95,366 |
Yes | output | 1 | 47,683 | 12 | 95,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>.
Submitted Solution:
```
from itertools import combinations,permutations
from collections import defaultdict
import math
import sys
import os
def solution(n,k,arr):
tica=[0]*200007
for i in range(n-1,-1,-1):
if arr[i]==1:
tica[i]=tica[i+1]+1
else:
tica[i]=0
ans=0
i=0
while i<n:
mult=1
sm=0
for j in range(i,n):
if arr[j]!=1:
mult*=arr[j]
sm+=arr[j]
if k*sm==mult:
ans+=1
else:
if mult > k*sm:
diff=mult-k*sm
if diff%k==0:
if tica[j] >= diff//k:
ans+=1
sm+=tica[j]
i+=tica[j]-1
i+=1
return ans
def main():
n,k=map(int,input().strip().split())
a=list(map(int,input().strip().split()))
print(solution(n,k,a))
if __name__ == '__main__':
main()
"""
1 1
1
4 2
6 3 8 1
"""
``` | instruction | 0 | 47,684 | 12 | 95,368 |
No | output | 1 | 47,684 | 12 | 95,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>.
Submitted Solution:
```
n,k=map(int, input().split())
v=list(map(int, input().split()))
pos, pref=[], []
ans=0
for i in range(n):
if v[i]!=1:
pos.append(i)
else:
ans+=1
if i:
pref.append(pref[-1]+v[i])
else:
pref.append(v[i])
m=len(pos)
inf=int(2e18+10)
for i in range(m):
p=1
for j in range(i, m):
p=p*v[pos[j]]
if p>inf:
break
s = pref[pos[j]];
if pos[i]:
s-=pref[pos[i]-1]
if s*k==p:
ans+=1
d=p-s*k
if d>0 and d%k==0:
f, b, w=0,0, d//k
if i:
f=pos[i]-pos[i-1]-1
if j!=m-1:
b=pos[j+1]-pos[j]
if f+b<w:
continue
if f>=w:
ans+=1
if b>=w:
ans+=1
ans+=min(min(f, b), w)
print(ans)
``` | instruction | 0 | 47,685 | 12 | 95,370 |
No | output | 1 | 47,685 | 12 | 95,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>.
Submitted Solution:
```
n,k = map(int,input().split())
A = list(map(int,input().split()))
A = [0]+A;
x = 0
prev = [0 for i in range(n+1)]
sm = [0 for i in range(n+1)]
for i in range(1,n+1):
prev[i] = x
if A[i]>1:
x = i
sm[i] = A[i]+sm[i-1]
lim = int(2*(10**18))
ans = 0
for i in range(1,n+1):
p = 1
j = i
while j:
if lim//A[j]>p:
s = sm[i]-sm[j-1]
p *= A[j]
if p%k == 0 and p/k>=s and s>=p/(k+j-1-prev[j]):
ans += 1
else:
break
j = prev[j]
print(ans)
``` | instruction | 0 | 47,686 | 12 | 95,372 |
No | output | 1 | 47,686 | 12 | 95,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nastya received one more array on her birthday, this array can be used to play a traditional Byteland game on it. However, to play the game the players should first select such a subsegment of the array that <image>, where p is the product of all integers on the given array, s is their sum, and k is a given constant for all subsegments.
Nastya wonders how many subsegments of the array fit the described conditions. A subsegment of an array is several consecutive integers of the array.
Input
The first line contains two integers n and k (1 ≤ n ≤ 2·105, 1 ≤ k ≤ 105), where n is the length of the array and k is the constant described above.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 108) — the elements of the array.
Output
In the only line print the number of subsegments such that the ratio between the product and the sum on them is equal to k.
Examples
Input
1 1
1
Output
1
Input
4 2
6 3 8 1
Output
2
Note
In the first example the only subsegment is [1]. The sum equals 1, the product equals 1, so it suits us because <image>.
There are two suitable subsegments in the second example — [6, 3] and [3, 8, 1]. Subsegment [6, 3] has sum 9 and product 18, so it suits us because <image>. Subsegment [3, 8, 1] has sum 12 and product 24, so it suits us because <image>.
Submitted Solution:
```
n,k = map(int,input().split(' '))
a = list(map(int,input().split(' ')))
#prod
p = 1
for i in range(0,n):
p = p*a[i]
p1 = p
p2 = p
s = sum(a)
s1 = s
s2 = s
c = 0
#print(s)
#print(s)
if p/s == k:
c = c+1
for i in range(0,n):
p1 = p1/a[i]
s1 = s1-a[i]
if s1!=0 and p1!=1 and p1/s1 == k:
c = c+1
p2 = p2/a[n-1-i]
s2 = s2-a[n-1-i]
if s2!=0 and p2!=1 and p2/s2 == k:
c = c+1
print(c)
``` | instruction | 0 | 47,687 | 12 | 95,374 |
No | output | 1 | 47,687 | 12 | 95,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,936 | 12 | 95,872 |
Tags: constructive algorithms, greedy
Correct Solution:
```
import math
n = int(input())
step = math.ceil(n ** (1/2) )
k = n
i = 1
ans = []
while k > 0:
tt = list(range(i, min(i + step, n + 1)))[::-1]
ans += tt
k -= step
i += step
print(*ans)
``` | output | 1 | 47,936 | 12 | 95,873 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,937 | 12 | 95,874 |
Tags: constructive algorithms, greedy
Correct Solution:
```
from math import ceil, floor
n = int(input())
k = floor(n ** .5)
tmp = [[j for j in range(i, min(k + i, n + 1))] for i in range(k * (n // k) + 1, 0, -k)]
answer = []
for item in tmp:
answer += item
print(' '.join(str(item) for item in answer))
``` | output | 1 | 47,937 | 12 | 95,875 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,938 | 12 | 95,876 |
Tags: constructive algorithms, greedy
Correct Solution:
```
from math import sqrt
n = int(input())
r = int(sqrt(n))
ans = []
if n == 1:
print("1")
elif n == 2:
print("1 2")
elif n == 3:
print("1 3 2")
elif r ** 2 == n:
for i in range(r):
ans += [str((r - i - 1) * r + j) for j in range(1, r + 1)]
print(" ".join(ans))
else:
if n <= r * (r + 1):
segment = r
element = r + 1
else:
segment = r + 1
element = r + 1
for i in range(segment - 1):
ans += [str(n - element * i - j) for j in range(element - 1, -1, -1)]
ans += [str(j) for j in range(1, n - element * (segment - 1) + 1)]
print(" ".join(ans))
``` | output | 1 | 47,938 | 12 | 95,877 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,939 | 12 | 95,878 |
Tags: constructive algorithms, greedy
Correct Solution:
```
import sys, os, io
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math,datetime,functools,itertools,operator,bisect,fractions,statistics
from collections import deque,defaultdict,OrderedDict,Counter
from fractions import Fraction
from decimal import Decimal
from sys import stdout
from heapq import heappush, heappop, heapify ,_heapify_max,_heappop_max,nsmallest,nlargest
def main():
# mod=1000000007
# InverseofNumber(mod)
# InverseofFactorial(mod)
# factorial(mod)
starttime=datetime.datetime.now()
if(os.path.exists('input.txt')):
sys.stdin = open("input.txt","r")
sys.stdout = open("output.txt","w")
tc=1
for _ in range(tc):
n=ri()
ans=[]
i=1
k=1
t=0
while True:
k=i*i
if k<=n:
t=i
else:
break
i+=1
a=[]
z=[]
for i in range(n):
z+=[i+1]
if len(z)==t:
a=z+a
z=[]
a=z+a
wia(a)
#<--Solving Area Ends
endtime=datetime.datetime.now()
time=(endtime-starttime).total_seconds()*1000
if(os.path.exists('input.txt')):
print("Time:",time,"ms")
class FastReader(io.IOBase):
newlines = 0
def __init__(self, fd, chunk_size=1024 * 8):
self._fd = fd
self._chunk_size = chunk_size
self.buffer = io.BytesIO()
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
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, size=-1):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
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()
class FastWriter(io.IOBase):
def __init__(self, fd):
self._fd = fd
self.buffer = io.BytesIO()
self.write = self.buffer.write
def flush(self):
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class FastStdin(io.IOBase):
def __init__(self, fd=0):
self.buffer = FastReader(fd)
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
class FastStdout(io.IOBase):
def __init__(self, fd=1):
self.buffer = FastWriter(fd)
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.flush = self.buffer.flush
if __name__ == '__main__':
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()
``` | output | 1 | 47,939 | 12 | 95,879 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,940 | 12 | 95,880 |
Tags: constructive algorithms, greedy
Correct Solution:
```
import sys
import math as mt
I=lambda:list(map(int,input().split()))
n,=I()
x=int((n)**0.5)
ans=[]
t=mt.ceil(n/x)
st=1
for i in range(t):
if st+x<=n:
ans.append(list(range(st,st+x)))
else:
ans.append(list(range(st,n+1)))
st+=x
ans=ans[::-1]
for i in ans:
print(*i,end=' ')
``` | output | 1 | 47,940 | 12 | 95,881 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,941 | 12 | 95,882 |
Tags: constructive algorithms, greedy
Correct Solution:
```
import math
n = int(input())
A = [i + 1 for i in range(n)]
x = int(math.sqrt(n))
X = [A[i:i + x] for i in range(0, len(A), x)]
X = X[::-1]
f = [item for sublist in X for item in sublist]
print(*f)
``` | output | 1 | 47,941 | 12 | 95,883 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,942 | 12 | 95,884 |
Tags: constructive algorithms, greedy
Correct Solution:
```
n=int(input())
f=int(n**(1/2))
for i in range(f,n+f,f):
for j in range(min(n,i),i-f,-1):
print(j,end=' ')
``` | output | 1 | 47,942 | 12 | 95,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid. | instruction | 0 | 47,943 | 12 | 95,886 |
Tags: constructive algorithms, greedy
Correct Solution:
```
n = int(input())
L = int(n ** 0.5)
i = 1
k = n
a = [0] * 100005
while i <= n:
j = min(i + L - 1, n)
while j >= i:
a[j] = k
j -= 1
k -= 1
i += L
print(" ".join(map(str, a[1:n + 1])))
``` | output | 1 | 47,943 | 12 | 95,887 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
n=int(input())
t=n+10
for i in range(1,n+1):
p=n//i
if(p!=n/i):
p=p+1
if t>(i+p):
t=(i+p)
j=i
#print(j,t-j)
t=t-j
p=[]
for i in range(j):
z=n-t*(i+1)
for k in range(t):
z=z+1
if z>0:
p.append(z)
print(*p)
``` | instruction | 0 | 47,944 | 12 | 95,888 |
Yes | output | 1 | 47,944 | 12 | 95,889 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
import math
n = int(input())
width = int(math.sqrt(n))
start = n - width + 1
ans = list()
while True:
stop = False
for v in range(start, start + width):
if v > 0:
ans.append(v)
if v < 1:
stop = True
start -= width
if stop:
break
print(*ans)
``` | instruction | 0 | 47,945 | 12 | 95,890 |
Yes | output | 1 | 47,945 | 12 | 95,891 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
from math import sqrt
n=int(input())
k=int(sqrt(n))
while(n):
if n>k-1:
for i in range(n-k+1,n+1):
print(i,end=' ')
n-=k
if n!=0 and n<k:
for i in range(1,n+1):
print(i,end=' ')
n=0
``` | instruction | 0 | 47,946 | 12 | 95,892 |
Yes | output | 1 | 47,946 | 12 | 95,893 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
n = int(input())
sqr = n**(0.5)
sqr = int(sqr)
ind = []
rem = 0
while n>sqr:
ind.extend([int(x) for x in range(n+1-sqr,n+1)])
n = n - sqr
ind.extend([int(x) for x in range(1,n+1)])
print(*ind,sep=" ")
``` | instruction | 0 | 47,947 | 12 | 95,894 |
Yes | output | 1 | 47,947 | 12 | 95,895 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
t=int(input(''))
a=[]
b=[]
for i in range(1,t+1):
a.append(i)
while len(a)!=0:
b.append(a[0])
del a[0]
if len(a)==0:
break
b.append(a[-1])
del a[-1]
for j in range(t):
print(b[j],end=" ")
``` | instruction | 0 | 47,948 | 12 | 95,896 |
No | output | 1 | 47,948 | 12 | 95,897 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
n = int(input())
a = n
b = 1
for i in range(n):
if i % 2 == 0:
print(a, end = ' ')
a -= 1
else:
print(b, end = ' ')
b += 1
``` | instruction | 0 | 47,949 | 12 | 95,898 |
No | output | 1 | 47,949 | 12 | 95,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
n=int(input())
ma=0
ans=[1,n]
for i in range(2,int(n**0.5)+1):
j=i
k=n//i
if (j+k)>=ma:
ans=[j,k]
ma=j+k
fi=[[0 for j in range(ans[1]) ]for i in range(ans[0])]
t=1
#print(ans,fi)
for i in range(ans[0]):
for j in range(ans[1]):
fi[i][j]=t
t+=1
for i in range(ans[0]-1,-1,-1):
print(*fi[i],sep=" ",end=" ")
``` | instruction | 0 | 47,950 | 12 | 95,900 |
No | output | 1 | 47,950 | 12 | 95,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mrs. Smith is trying to contact her husband, John Smith, but she forgot the secret phone number!
The only thing Mrs. Smith remembered was that any permutation of n can be a secret phone number. Only those permutations that minimize secret value might be the phone of her husband.
The sequence of n integers is called a permutation if it contains all integers from 1 to n exactly once.
The secret value of a phone number is defined as the sum of the length of the longest increasing subsequence (LIS) and length of the longest decreasing subsequence (LDS).
A subsequence a_{i_1}, a_{i_2}, …, a_{i_k} where 1≤ i_1 < i_2 < … < i_k≤ n is called increasing if a_{i_1} < a_{i_2} < a_{i_3} < … < a_{i_k}. If a_{i_1} > a_{i_2} > a_{i_3} > … > a_{i_k}, a subsequence is called decreasing. An increasing/decreasing subsequence is called longest if it has maximum length among all increasing/decreasing subsequences.
For example, if there is a permutation [6, 4, 1, 7, 2, 3, 5], LIS of this permutation will be [1, 2, 3, 5], so the length of LIS is equal to 4. LDS can be [6, 4, 1], [6, 4, 2], or [6, 4, 3], so the length of LDS is 3.
Note, the lengths of LIS and LDS can be different.
So please help Mrs. Smith to find a permutation that gives a minimum sum of lengths of LIS and LDS.
Input
The only line contains one integer n (1 ≤ n ≤ 10^5) — the length of permutation that you need to build.
Output
Print a permutation that gives a minimum sum of lengths of LIS and LDS.
If there are multiple answers, print any.
Examples
Input
4
Output
3 4 1 2
Input
2
Output
2 1
Note
In the first sample, you can build a permutation [3, 4, 1, 2]. LIS is [3, 4] (or [1, 2]), so the length of LIS is equal to 2. LDS can be ony of [3, 1], [4, 2], [3, 2], or [4, 1]. The length of LDS is also equal to 2. The sum is equal to 4. Note that [3, 4, 1, 2] is not the only permutation that is valid.
In the second sample, you can build a permutation [2, 1]. LIS is [1] (or [2]), so the length of LIS is equal to 1. LDS is [2, 1], so the length of LDS is equal to 2. The sum is equal to 3. Note that permutation [1, 2] is also valid.
Submitted Solution:
```
n = int(input())
a = []
a.append((n+1)//2)
for i in range(0,n-1):
if i %2 == 0:
a.append(n-i//2)
else:
a.append(i//2 + 1)
a = map(str,a)
a = ' '.join(a)
print(a)
``` | instruction | 0 | 47,951 | 12 | 95,902 |
No | output | 1 | 47,951 | 12 | 95,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,020 | 12 | 96,040 |
Tags: brute force, dp
Correct Solution:
```
n = int(input())
v = list(map(int,input().split()))
a = [0]*(n+1)
a[0] = 1;
for i in range(1,n):
if v[i] <= v[i-1]:
a[i] = 1
else:
a[i] = a[i-1]+1
ans = [1]
i = 1
while i < n-1:
if a[i] == 1:
if v[i-1] < v[i+1]:
j = a[i-1]
k = i+1
while a[k] > 1:
j = j+1
i = k
k = k+1
if k == n:
break
ans.append(j)
elif i > 1:
if v[i-2] < v[i]:
j = a[i-2]+1
k = i
if k < n-1:
while v[k]<v[k+1]:
j = j+1
i = k
k = k+1
if k >=n-1:
break
ans.append(j)
i = i+1
if i >=n:
break
f = [max(ans),max(a)]
print(max(f))
``` | output | 1 | 48,020 | 12 | 96,041 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,021 | 12 | 96,042 |
Tags: brute force, dp
Correct Solution:
```
n = int(input())
num = [int(x) for x in input().split()]
f = []
for i in range(n):
f.append([1, 0, 0])
for i in range(1, n):
if (num[i] > num[i-1]):
f[i][0] = f[i-1][0] + 1
f[i][1] = f[i-1][0]
f[i][2] = f[i-1][2] + 1
if (i >= 2 and num[i] > num[i-2]):
f[i][2] = max(f[i][2], f[i-1][1] + 1)
else:
f[i][0] = 1
f[i][1] = f[i-1][0]
if (i >= 2 and num[i] > num[i-2]):
f[i][2] = max(f[i][2], f[i-1][1] + 1)
ans = 0
for i in range(0, n):
ans = max(ans, max(f[i][0], max(f[i][1], f[i][2])))
print(ans)
``` | output | 1 | 48,021 | 12 | 96,043 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,022 | 12 | 96,044 |
Tags: brute force, dp
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
l,r=[1]*n,[1]*n
for i in range(1,n):
if a[i]>a[i-1]:l[i]+=l[i-1]
for i in range(n-2,-1,-1):
if a[i]<a[i+1]:r[i]+=r[i+1]
ans=max(l)
for i in range(1,n-1):
if a[i+1]>a[i-1] and r[i+1]+l[i-1]>ans:ans=r[i+1]+l[i-1]
print(ans)
``` | output | 1 | 48,022 | 12 | 96,045 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,023 | 12 | 96,046 |
Tags: brute force, dp
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
dpl = [0]*n
dpl[0] = 1
for i in range(1, n):
if a[i-1]<a[i]:
dpl[i] = dpl[i-1]+1
else:
dpl[i] = 1
dpr = [0]*n
dpr[-1] = 1
for i in range(n-2, -1, -1):
if a[i]<a[i+1]:
dpr[i] = dpr[i+1]+1
else:
dpr[i] = 1
ans = 0
for i in range(n):
ans = max(ans, dpl[i]+dpr[i]-1)
if 1<=i<=n-2 and a[i-1]<a[i+1]:
ans = max(ans, dpl[i-1]+dpr[i+1])
print(ans)
``` | output | 1 | 48,023 | 12 | 96,047 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,024 | 12 | 96,048 |
Tags: brute force, dp
Correct Solution:
```
n = int(input())
ar = list(map(int,input().split()))
l = [1]*n
r = [1]*n
ans = 0
for i in range(n-1):
if ar[i] < ar[i+1]:
l[i+1] = l[i] + 1
for j in range(n-1,0,-1):
if ar[j] > ar[j-1]:
r[j-1] = r[j] +1
for k in range(n-2):
if ar[k]< ar[k+2] :
ans = max(ans, l[k] + r[k+2])
for m in range(n):
ans = max(ans, l[m])
print(ans)
``` | output | 1 | 48,024 | 12 | 96,049 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,025 | 12 | 96,050 |
Tags: brute force, dp
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
pf = [1]*n
sf = [1]*n
for i in range(1, n):
if a[i] > a[i-1]:
pf[i] = pf[i-1]+1
for i in range(n-2, -1, -1):
if a[i] < a[i+1]:
sf[i] = sf[i+1]+1
if pf[-1] == n:
print(n)
else:
m = max(pf)
for i in range(1, n-1):
if a[i-1] < a[i+1]:
m = max(m, pf[i-1] + sf[i+1])
else:
m = max(m, pf[i-1], sf[i+1])
print(max(m, pf[-1], sf[0], sf[-1], pf[0]))
``` | output | 1 | 48,025 | 12 | 96,051 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,026 | 12 | 96,052 |
Tags: brute force, dp
Correct Solution:
```
n = int(input())
l = list(map(int, input().split(' ')))
lefts = []
leftsc = []
rights = []
rightsc = []
b = 0
for i in range(0, n - 1):
if b == 0:
if l[i] < l[i + 1]:
b = 1
lefts.append(l[i])
leftsc.append(i)
else:
lefts.append(l[i])
leftsc.append(i)
rights.append(l[i])
rightsc.append(i)
if l[i] >= l[i + 1] and b == 1:
b = 0
rights.append(l[i])
rightsc.append(i)
if l[n-2] < l[n - 1]:
rights.append(l[n - 1])
rightsc.append(n - 1)
else:
lefts.append(l[n-1])
leftsc.append(n-1)
rights.append(l[n - 1])
rightsc.append(n - 1)
maxl = 0
for i in range(len(lefts)):
maxl = max(maxl, rightsc[i] - leftsc[i] + 1)
if len(lefts) == 1:
print(rightsc[0] - leftsc[0] + 1)
exit(0)
for i in range(len(lefts) - 1):
if rights[i] >= lefts[i + 1]:
if rightsc[i] - 1 >= 0:
if l[rightsc[i] - 1] < lefts[i + 1]:
if maxl < rightsc[i + 1] - leftsc[i]:
maxl = rightsc[i + 1] - leftsc[i]
if rightsc[i] + 1 < n:
if leftsc[i + 1] + 1 < n:
if l[rightsc[i]] < l[leftsc[i + 1] + 1]:
if maxl < rightsc[i + 1] - leftsc[i]:
maxl = rightsc[i + 1] - leftsc[i]
print(maxl)
``` | output | 1 | 48,026 | 12 | 96,053 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4. | instruction | 0 | 48,027 | 12 | 96,054 |
Tags: brute force, dp
Correct Solution:
```
n = int (input ())
a = list (map (int, input ().split ()))
f = [[1, 0] for i in range (200002)]
use = [False for i in range (200002)]
ans = 1
if (a[1] > a[0]) :
f[1][0] = 2
ans = 2
for i in range (2, len (a)) :
u1 = 0
u2 = 0
v1 = 0
if (a[i] > a[i - 1]) :
u1 = f[i - 1][0]
u2 = f[i - 1][1]
if (a[i] > a[i - 2]) :
v1 = f[i - 2][0]
f[i][0] += u1
f[i][1] = 1 + max (u2, v1)
if (f[i][1] == 1) :
f[i][1] = 0
ans = max (f[i][0], f[i][1], ans)
print (ans)
``` | output | 1 | 48,027 | 12 | 96,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4.
Submitted Solution:
```
n = int(input())
a = [int(x) for x in input().split()]
ac = [1]
for a1, a2 in zip(a, a[1:]):
if a1 < a2:
ac.append(ac[-1] + 1)
else:
ac.append(1)
ds = [1]
for a1, a2 in zip(a[:-1][::-1], a[1:][::-1]):
if a1 < a2:
ds.append(ds[-1] + 1)
else:
ds.append(1)
ds = ds[::-1]
mx = [1] * n
for i in range(n):
if i == 0:
mx[i] = ds[i - 1]
elif i == n - 1:
mx[i] = ds[i - 1]
elif a[i + 1] > a[i - 1]:
mx[i] = ac[i - 1] + ds[i + 1]
print(max(mx + ac))
``` | instruction | 0 | 48,028 | 12 | 96,056 |
Yes | output | 1 | 48,028 | 12 | 96,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
d=[1]*n
d2=[1]*n
for i in range(1,n):
if(a[i]>a[i-1]):
d[i]=d[i-1]+1
d2[i]=d2[i-1]+1
if i>=2 and a[i]>a[i-2]:
d2[i]=max(d2[i],d[i-2]+1)
print(max(d2))
``` | instruction | 0 | 48,029 | 12 | 96,058 |
Yes | output | 1 | 48,029 | 12 | 96,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a consisting of n integers.
You can remove at most one element from this array. Thus, the final length of the array is n-1 or n.
Your task is to calculate the maximum possible length of the strictly increasing contiguous subarray of the remaining array.
Recall that the contiguous subarray a with indices from l to r is a[l ... r] = a_l, a_{l + 1}, ..., a_r. The subarray a[l ... r] is called strictly increasing if a_l < a_{l+1} < ... < a_r.
Input
The first line of the input contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9), where a_i is the i-th element of a.
Output
Print one integer — the maximum possible length of the strictly increasing contiguous subarray of the array a after removing at most one element.
Examples
Input
5
1 2 5 3 4
Output
4
Input
2
1 2
Output
2
Input
7
6 5 4 3 2 4 3
Output
2
Note
In the first example, you can delete a_3=5. Then the resulting array will be equal to [1, 2, 3, 4] and the length of its largest increasing subarray will be equal to 4.
Submitted Solution:
```
from sys import stdin
input = stdin.readline
from heapq import heapify,heappush,heappop,heappushpop
from collections import defaultdict as dd, deque as dq,Counter as C
from math import factorial as f ,ceil,gcd,sqrt,log
from bisect import bisect_left as bl ,bisect_right as br
from itertools import combinations as c,permutations as p
from math import factorial as f ,ceil,gcd,sqrt,log
mp = lambda : map(int,input().split())
it = lambda: int(input())
ls = lambda : list(input().strip())
mt = lambda r : [ list(mp()) for _ in range(r)]
lcm = lambda a,b : (a*b)//gcd(a,b)
def fibo_n(n):
return (((1+sqrt(5))/2)**n)/sqrt(5)
mod = 1000000007
a = it()
b = list(mp())
v1 =[1]*a
mx =0
for i in range(1,a):
if b[i]>b[i-1]:
v1[i] = v1[i-1] +1
mx = max(v1[i],mx)
v2 = [1]*a
for j in range(a-2,-1,-1):
if b[j]<b[j+1]:
v2[j]= v2[j+1]+1
mx = max(v2[j],mx)
for k in range(2,a-1):
if b[k-1]<b[k+1]:
mx = max(mx,v1[k-1]+ v2[k+1])
print(mx)
``` | instruction | 0 | 48,030 | 12 | 96,060 |
Yes | output | 1 | 48,030 | 12 | 96,061 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.