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.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 98,747 | 12 | 197,494 |
Tags: brute force, greedy, math
Correct Solution:
```
"""
Satwik_Tiwari ;) .
20 june , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
import bisect
from heapq import *
from math import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # 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
#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
#==============================================================================================
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")
#===============================================================================================
#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 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 p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(a,b):
ans = 1
while(b>0):
if(b%2==1):
ans*=a
a*=a
b//=2
return ans
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) : # Check Prime Number or not
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
#===============================================================================================
# code here ;))
def bs(a,l,h,x):
while(l<h):
# print(l,h)
mid = (l+h)//2
if(a[mid] == x):
return mid
if(a[mid] < x):
l = mid+1
else:
h = mid
return l
def sieve(a): #O(n loglogn) nearly linear
#all odd mark 1
for i in range(3,((10**6)+1),2):
a[i] = 1
#marking multiples of i form i*i 0. they are nt prime
for i in range(3,((10**6)+1),2):
for j in range(i*i,((10**6)+1),i):
a[j] = 0
a[2] = 1 #special left case
return (a)
def solve():
n = int(inp())
a = lis()
s = '1'*32
if(n==1):
print(a[0])
return
l = []
for i in range(0,n):
if(i==0):
l.append(~a[i])
continue
l.append(l[i-1]&(~a[i]))
r = [0]*(n)
for i in range(n-1,-1,-1):
if(i==n-1):
r[i] = (~a[i])
continue
r[i] = r[i+1] & (~a[i])
ans = -1
ind = -1
for i in range(0,n):
if(i==0):
if(ans < a[i]&(r[i+1])):
ind = i
ans = max(ans,a[i]&(r[i+1]))
continue
if(i==n-1):
if(ans < a[i]&l[i-1]):
ind = i
ans = max(ans,a[i]&l[i-1])
continue
if(ans < l[i-1]&a[i]&r[i+1]):
ind = i
ans =max(ans,l[i-1]&a[i]&r[i+1])
# print(ind)
print(*([a[ind]] + a[:ind] + a[ind+1:]))
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 98,747 | 12 | 197,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 98,748 | 12 | 197,496 |
Tags: brute force, greedy, math
Correct Solution:
```
n = int(input())
s = list(map(int, input().split()))
for i in range(30,-1,-1):
if sum(1 for x in s if x&(1<<i)) == 1:
s.sort(key = lambda x: -(x & (1<<i)))
break
print(*s)
``` | output | 1 | 98,748 | 12 | 197,497 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer. | instruction | 0 | 98,749 | 12 | 197,498 |
Tags: brute force, greedy, math
Correct Solution:
```
from math import log,ceil
def bitnot(n):
if n == 0:
return (1 << 31) - 1
return (1 << 31) - 1 - n
#print(bitnot(4))
n = int(input())
l = [int(i) for i in input().split()]
f = bitnot(l[0])
prefix = []
for i in l:
f &= bitnot(i)
prefix.append(f)
f = bitnot(l[-1])
sufix = []
for i in l[::-1]:
f &= bitnot(i)
sufix.append(f)
#print(l)
#print(prefix)
#print(sufix)
m = [-1,-1]
for i in range(n):
first = l[i]
p = s = 2**31 - 1
if i > 0:
p = prefix[i-1]
if i < n-1:
s = sufix[n-i-2]
#print(p,s)
r = (p & s)
#print('ands:', r)
ans = first & r
#print('ans:', first, ans)
if ans > m[0]:
m[0] = ans
m[1] = i
l[m[1]],l[0] = l[0], l[m[1]]
print(*l)
``` | output | 1 | 98,749 | 12 | 197,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
R = lambda: list(map(int, input().split()))
n = int(input())
a = R()
first = 0
for i in range(30, -1, -1):
cnt = 0
for j in range(n):
if a[j] & 1 << i:
cnt += 1
first = j
if cnt == 1:
break
print(a[first], *(a[:first]), *(a[first + 1:]))
``` | instruction | 0 | 98,750 | 12 | 197,500 |
Yes | output | 1 | 98,750 | 12 | 197,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
A = list(map(int,input().split()))
B = [[0] * 33 for i in range(n)]
C = [0] * 33
for i in range(n):
t = A[i]
j = 0
while t > 0:
B[i][j] += t%2
C[j] += B[i][j]
t//=2
j += 1
M2 = [1]
for i in range(40):
M2.append(M2[-1]*2)
S = [0] * n
for i in range(n):
for j in range(33):
if B[i][j] == 1:
if C[j] == 1:
S[i] += M2[j]
ind = S.index(max(S))
ANS = [A[ind]]
for i in range(n):
if i != ind:
ANS.append(A[i])
print(" ".join([str(i) for i in ANS]))
``` | instruction | 0 | 98,751 | 12 | 197,502 |
Yes | output | 1 | 98,751 | 12 | 197,503 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
# import sys
n = int(input())
a = [int(c) for c in input().split()]
only_1 = (1 << 40) - 1
left = [only_1]
right = [only_1]
L = only_1
for i in range(n - 1):
L = L & ~a[i]
left.append(L)
R = only_1
for i in range(n - 1):
R = R & ~a[n - 1 - i]
# right.insert(0, R)
right.append(R)
# print(left, right)
res = 0
res_i = 0
for i in range(n):
r = a[i] & left[i] & right[n - 1 - i]
if r > res:
res_i = i
res = r
b = [a[res_i]] + [a[j] for j in range(n) if j != res_i]
# print('done', file=sys.stderr)
print(*b)
``` | instruction | 0 | 98,752 | 12 | 197,504 |
Yes | output | 1 | 98,752 | 12 | 197,505 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
import sys
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().split()))
if N == 1:
ans = A
else:
dp1 = [0]*N
bit = 0
for i, a in enumerate(A):
bit |= a
dp1[i] = bit
dp2 = [0]*N
bit = 0
for i in reversed(range(N)):
bit |= A[i]
dp2[i] = bit
score = -1
ind = -1
for i in range(N):
if i == 0:
tmp = dp2[1]
elif i == N-1:
tmp = dp1[N-2]
else:
tmp = dp1[i-1]|dp2[i+1]
if (A[i]|tmp)-tmp > score:
score = (A[i]|tmp)-tmp
ind = i
ans = [A[ind]]
for i, a in enumerate(A):
if i != ind:
ans.append(a)
print(*ans, sep=" ")
``` | instruction | 0 | 98,753 | 12 | 197,506 |
Yes | output | 1 | 98,753 | 12 | 197,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
from sys import stdin
input=stdin.buffer.readline
n=int(input())
arr=[int(x) for x in input().split()]
arr.sort(reverse=True)
print(*arr)
``` | instruction | 0 | 98,754 | 12 | 197,508 |
No | output | 1 | 98,754 | 12 | 197,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
arr = [int(x) for x in input().split()]
for x in arr:
print(x, end=' ')
``` | instruction | 0 | 98,755 | 12 | 197,510 |
No | output | 1 | 98,755 | 12 | 197,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
t=1
while t>0:
t-=1
n=int(input())
a=[int(x) for x in input().split()]
d={}
l=[0 for i in range(70)]
for i in range(n):
u=bin(a[i])[2:]
#print(a[i],"0"*(40-len(u))+u)
for k in range(len(u)):
if u[k]=='1':
l[len(u)-k-1]+=1
if a[i] in d:
d[a[i]]+=1
else:
d[a[i]]=1
a.sort(reverse=True)
maxi=-1
for k in range(len(u)-1,-1,-1):
for i in range(n):
u=bin(a[i])[2:]
u="0"*(70-len(u))+bin(a[i])[2:]
if u[k]=='1' and l[len(u)-k-1]==1:
maxi=a[i]
break
if maxi!=-1:
break
if maxi==-1:
maxi=a[0]
a.remove(maxi)
print(maxi,*a)
``` | instruction | 0 | 98,756 | 12 | 197,512 |
No | output | 1 | 98,756 | 12 | 197,513 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Anu has created her own function f: f(x, y) = (x | y) - y where | denotes the [bitwise OR operation](https://en.wikipedia.org/wiki/Bitwise_operation#OR). For example, f(11, 6) = (11|6) - 6 = 15 - 6 = 9. It can be proved that for any nonnegative numbers x and y value of f(x, y) is also nonnegative.
She would like to research more about this function and has created multiple problems for herself. But she isn't able to solve all of them and needs your help. Here is one of these problems.
A value of an array [a_1, a_2, ..., a_n] is defined as f(f(... f(f(a_1, a_2), a_3), ... a_{n-1}), a_n) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?
Input
The first line contains a single integer n (1 ≤ n ≤ 10^5).
The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9). Elements of the array are not guaranteed to be different.
Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
Input
4
4 0 11 6
Output
11 6 4 0
Input
1
13
Output
13
Note
In the first testcase, value of the array [11, 6, 4, 0] is f(f(f(11, 6), 4), 0) = f(f(9, 4), 0) = f(9, 0) = 9.
[11, 4, 0, 6] is also a valid answer.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
m = [[0, 0] for _ in range(n)]
for i in range(n):
bin_str = format(l[i], 'b')
p = 0
for j in range(len(bin_str)):
if bin_str[j] == '1':
p += 1
m[i][0] = l[i]
m[i][1] = p
m_ = sorted(m, key=lambda x:(x[0],x[1]), reverse=True)
#print(m_)
l_ = [str(c[0]) for c in m_]
print(' '.join(l_))
``` | instruction | 0 | 98,757 | 12 | 197,514 |
No | output | 1 | 98,757 | 12 | 197,515 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,774 | 12 | 197,548 |
Tags: dp, greedy, two pointers
Correct Solution:
```
def fun(n,l):
prev=l[0]
sum=[]
for i in range(1,n):
if prev>0 and l[i]<0:
sum.append(prev)
prev=l[i]
elif prev<0 and l[i]>0:
sum.append(prev)
prev = l[i]
elif prev<l[i]:
prev=l[i]
if i==n-1:
sum.append(prev)
suma=0
for i in sum:
suma+=i
print(suma)
for T in range(int(input())):
n=int(input())
l=list(map(int,input().split()))
if n>1:
fun(n,l)
else:
print(l[0])
``` | output | 1 | 98,774 | 12 | 197,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,775 | 12 | 197,550 |
Tags: dp, greedy, two pointers
Correct Solution:
```
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
for _ in range(int(input())):
n=int(input())
count_even=0
count_odd=0
li=[int(x) for x in input().split()]
ans=0
i=0
while(True):
if(i==n):
break
if(li[i]>0):
var=0
while(li[i]>0 and i<n):
var=max(var,li[i])
i+=1
if(i==n):
break
ans+=var
else:
var=-1e18
if(i==n):
break
while(li[i]<0 and i<n):
var=max(var,li[i])
i+=1
if(i==n):
break
ans+=var
if(i==n):
break
print(ans)
``` | output | 1 | 98,775 | 12 | 197,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,776 | 12 | 197,552 |
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
data = list(map(int, input().split()))
result = 0
if data[0] > 0:
sign = 1
else:
sign = -1
array = []
for x in data:
if sign == 1 and x > 0:
array.append(x)
if sign == 1 and x < 0:
sign = -1
result += max(array)
array = [x]
if sign == -1 and x < 0:
array.append(x)
if sign == -1 and x > 0:
sign = 1
result += max(array)
array = [x]
result += max(array)
print(result)
``` | output | 1 | 98,776 | 12 | 197,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,777 | 12 | 197,554 |
Tags: dp, greedy, two pointers
Correct Solution:
```
import math
import sys
from collections import defaultdict
from collections import Counter
from collections import deque
import bisect
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda: map(int,input().split())
alele = lambda: list(map(int, input().split()))
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
for _ in range(int(input())):
N = int(input())
A = alele()
i = 0;B = [];temp = [];pos = -1
while i<len(A):
if len(temp) == 0:
if A[i] < 0:
pos = 0
temp.append(A[i])
else:
pos = 1
temp.append(A[i])
else:
if pos == 1:
if A[i] > 0:
temp.append(A[i])
else:
pos = 0
B.append(max(temp))
temp = []
temp.append(A[i])
else:
if A[i] < 0:
temp.append(A[i])
else:
pos = 1
B.append(max(temp))
temp = []
temp.append(A[i])
i+=1
if len(temp) != 0:
if temp[0]<0:
B.append(max(temp))
else:
B.append(max(temp))
#print(B)
print(sum(B))
``` | output | 1 | 98,777 | 12 | 197,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,778 | 12 | 197,556 |
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
ar=list(map(int,input().split()))
if(ar[0]>0):
ty='p'
else:
ty='n'
li=[]
ans=0
for i in range(n):
if(ar[i]>0):
if(ty=='p'):
li.append(ar[i])
else:
ans+=max(li)
li=[ar[i]]
ty='p'
if(ar[i]<0):
if(ty=='n'):
li.append(ar[i])
else:
ans+=max(li)
li=[ar[i]]
ty='n'
ans+=max(li)
print(ans)
``` | output | 1 | 98,778 | 12 | 197,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,779 | 12 | 197,558 |
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
lst = list(map(int,input().split()))
i = 0
ans = 0
while(i<n):
if(lst[i]>0):
j = i+1
maxPos = lst[i]
while(j<n and lst[j]>0):
maxPos = max(maxPos,lst[j])
j+=1
ans+=maxPos
i = j
else:
j =i+1
maxNeg = lst[i]
while(j<n and lst[j]<0):
maxNeg = max(maxNeg,lst[j])
j+=1
ans+=maxNeg
i = j
print(ans)
``` | output | 1 | 98,779 | 12 | 197,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,780 | 12 | 197,560 |
Tags: dp, greedy, two pointers
Correct Solution:
```
for _ in range(int(input())):
m=int(input())
l=list(map(int,input().split()))
q=[]
p=[]
i=0
res=0
while(i<m):
while(i<m and l[i]>0):
q.append(l[i])
i=i+1
#print(q)
while(i<m and l[i]<0):
p.append(l[i])
i+=1
#print(p)
if(len(q)==0):
y=0
else:
y=max(q)
if(len(p)==0):
x=0
else:
x=max(p)
#print(";;;x",x)
#print("////y",y)
res=res+x+y
#print("res",res)
p=[]
q=[]
print(res)
``` | output | 1 | 98,780 | 12 | 197,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}]. | instruction | 0 | 98,781 | 12 | 197,562 |
Tags: dp, greedy, two pointers
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
a = list(map(int, input().split()))
ans = 0
pos = True if a[0] > 0 else False
mini = a[0]
for i in range(n):
if (a[i] > 0 and pos) or (a[i] < 0 and not pos):
mini = max(mini, a[i])
else:
ans += mini
mini = a[i]
pos = not pos
ans += mini
print(ans)
``` | output | 1 | 98,781 | 12 | 197,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
def solve(n, arr):
seg = -math.inf
neg = arr[0] < 0
total = 0
for a in arr:
if a < 0 and neg:
seg = max(seg, a)
elif a > 0 and not neg:
seg = max(seg, a)
else:
if (a < 0 and not neg) or (a > 0 and neg):
total += seg
seg = a
neg = a < 0
return total + seg
if __name__ == "__main__":
t = int(input())
for i in range(t):
n = int(input())
arr = list(map(int,input().split()))
print(solve(n, arr))
``` | instruction | 0 | 98,782 | 12 | 197,564 |
Yes | output | 1 | 98,782 | 12 | 197,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t = int(input())
for i in range(t):
n = int(input())
a = list(map(int,input().split()))
if (a[0]>0):
pos = a[0]
flag=True
ans_sum = a[0]
elif (a[0]<0):
neg = a[0]
flag=False
ans_sum = a[0]
for j in range(1,n):
if ((a[j]>0)):
if ((flag==True)):
if ((a[j]>pos)):
ans_sum = ans_sum - pos
pos = a[j]
ans_sum = ans_sum + a[j]
else:
pos = a[j]
ans_sum = ans_sum + a[j]
flag=True
else:
if ((flag==False)):
if ((a[j]>neg)):
ans_sum = ans_sum - neg
neg = a[j]
ans_sum = ans_sum + a[j]
else:
neg = a[j]
ans_sum = ans_sum + a[j]
flag=False
print(ans_sum)
``` | instruction | 0 | 98,783 | 12 | 197,566 |
Yes | output | 1 | 98,783 | 12 | 197,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t= int(input())
for i in range(0,t):
n=int(input())
a=list(map(int,input().split()))
count=0
max=0
max1=0
m=0
s=0
for j in range(0,n):
if(a[j]>0):
count=count+max
max=0
if(s==0):
max1=a[j]
s=1
m=0
if(a[j]>max1):
max1=a[j]
else:
count=count+max1
max1=0
if(m==0):
max=a[j]
m=1
s=0
if(max<a[j]):
max=a[j]
if(a[n-1]>0):
count=count+max1
else:
count=count+max
print(count)
``` | instruction | 0 | 98,784 | 12 | 197,568 |
Yes | output | 1 | 98,784 | 12 | 197,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t = int(input())
while(t>0):
n= int(input())
arr =[int(i) for i in input().split()]
l= 0
r= 0
r= 1
if arr[l]>0:
flag =1
else:
flag= 0
out= []
while(r<n):
if arr[r]>0 and flag == 1:
r+=1
continue
elif arr[r]<0 and flag ==0:
r+=1
continue
elif flag==1:
out.append(max(arr[l:r]))
l= r
flag= 0
elif flag==0:
out.append(max(arr[l:r]))
l= r
flag= 1
r+=1
if flag==1:
out.append(max(arr[l:r]))
l= r
flag= 0
else:
out.append(max(arr[l:r]))
l= r
flag= 1
print(sum(out))
t-=1
``` | instruction | 0 | 98,785 | 12 | 197,570 |
Yes | output | 1 | 98,785 | 12 | 197,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
def ans(a):
count = 0
s = ''
temp_l = [[a[0]]]
arr = []
for i in range(1,len(a)):
if (a[i]>0 and a[i-1]<0) or (a[i]<0 and a[i-1]>0):
temp_l[-1].append(a[i])
else:
temp_l.append([a[i]])
print(temp_l)
q = -1
w = [min(a)] #ans
for i in temp_l:
e = len(i)
f = sum(i)
if e>=q:
if f>sum(w):
w = i
q = e
t = sum(w)
return(t)
q = int(input())
for i in range(q):
b = input()
a = input().split()
s = []
for i in a:
s.append(int(i))
print(ans(s))
``` | instruction | 0 | 98,786 | 12 | 197,572 |
No | output | 1 | 98,786 | 12 | 197,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
arr=list(map(int,input().split()))
prev=arr[0]
maxpo=arr[0]
maxne=min(arr)
sum1=0
for i in range(1,n):
if(arr[i]>0):
if(prev>0):
if(maxpo<arr[i]):
maxpo=arr[i]
prev=arr[i]
else:
sum1=sum1+prev
maxpo=arr[i]
prev=arr[i]
elif(arr[i]<0):
if(prev<0):
if(maxne<arr[i]):
maxne=arr[i]
prev=arr[i]
else:
sum1=sum1+prev
maxne=arr[i]
prev=arr[i]
sum1=sum1+prev
print(sum1)
``` | instruction | 0 | 98,787 | 12 | 197,574 |
No | output | 1 | 98,787 | 12 | 197,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
while(t):
n=int(input())
a=list(map(int,input().rstrip().split()))
c=0
T1=T2=False
ans=0
for i in range(n):
if a[i]>0:
T1=True
if T2:
ans+=c
T2=False
c=a[i]
else:
c=max(c,a[i])
else:
T2=True
if T1:
ans+=c
T1=False
c=a[i]
else:
c=max(c,a[i])
print(ans)
t-=1
``` | instruction | 0 | 98,788 | 12 | 197,576 |
No | output | 1 | 98,788 | 12 | 197,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Recall that the sequence b is a a subsequence of the sequence a if b can be derived from a by removing zero or more elements without changing the order of the remaining elements. For example, if a=[1, 2, 1, 3, 1, 2, 1], then possible subsequences are: [1, 1, 1, 1], [3] and [1, 2, 1, 3, 1, 2, 1], but not [3, 2, 3] and [1, 1, 1, 1, 2].
You are given a sequence a consisting of n positive and negative elements (there is no zeros in the sequence).
Your task is to choose maximum by size (length) alternating subsequence of the given sequence (i.e. the sign of each next element is the opposite from the sign of the current element, like positive-negative-positive and so on or negative-positive-negative and so on). Among all such subsequences, you have to choose one which has the maximum sum of elements.
In other words, if the maximum length of alternating subsequence is k then your task is to find the maximum sum of elements of some alternating subsequence of length k.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the number of elements in a. The second line of the test case contains n integers a_1, a_2, ..., a_n (-10^9 ≤ a_i ≤ 10^9, a_i ≠ 0), where a_i is the i-th element of a.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5 (∑ n ≤ 2 ⋅ 10^5).
Output
For each test case, print the answer — the maximum sum of the maximum by size (length) alternating subsequence of a.
Example
Input
4
5
1 2 3 -1 -2
4
-1 -2 -1 -3
10
-2 8 3 8 -4 -15 5 -2 -3 1
6
1 -1000000000 1 -1000000000 1 -1000000000
Output
2
-1
6
-2999999997
Note
In the first test case of the example, one of the possible answers is [1, 2, \underline{3}, \underline{-1}, -2].
In the second test case of the example, one of the possible answers is [-1, -2, \underline{-1}, -3].
In the third test case of the example, one of the possible answers is [\underline{-2}, 8, 3, \underline{8}, \underline{-4}, -15, \underline{5}, \underline{-2}, -3, \underline{1}].
In the fourth test case of the example, one of the possible answers is [\underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}, \underline{1}, \underline{-1000000000}].
Submitted Solution:
```
t=int(input())
for i in range(t):
n=int(input())
a=list(map(int,input().split()))
s=0
t=a[0]
temp=a[0]
for i in range(1,n):
if t>0 and a[i]>0:
temp=max(temp,a[i])
elif t>0 and a[i]<0:
s+=temp
temp=a[i]
t=a[i]
elif t<0 and a[i]<0:
temp=max(a[i],temp)
elif t<0 and a[i]>0:
s+=temp
temp=a[i]
t=a[i]
print(s)
``` | instruction | 0 | 98,789 | 12 | 197,578 |
No | output | 1 | 98,789 | 12 | 197,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p;
* if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p.
For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].
Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.
For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d.
The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard.
The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9).
Output
Print two integers:
* the first integer should be equal to the length of the longest increasing subsequence of p;
* the second should be equal to the number of them modulo 998244353.
You should print only the second number modulo 998244353.
Examples
Input
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
Note
The first test case was explained in the statement.
In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].
In the third test case p = [1, 2, …, 2000000000]. | instruction | 0 | 98,843 | 12 | 197,686 |
Tags: dp, math, matrices
Correct Solution:
```
import sys, io, os
if os.environ['USERNAME']=='kissz':
inp=open('in55.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
def mexp(size,power):
A=[]
for i in range(size):
A.append([int(j<=(i//2)*2) for j in range(size)])
powers={1: A}
p=1
while p*2<=power:
powers[p*2]=mmmult(powers[p],powers[p])
p*=2
A=powers[p]
power-=p
while power>0:
p=p//2
if p<=power:
A=mmmult(A,powers[p])
power-=p
return A
def mvmult(A,V):
res=[]
for i in range(len(A)):
res.append(sum(a*v for a,v in zip(A[i],V)) % 998244353 )
return res
def mmmult(A,B):
res=[]
for i in range(len(A)):
res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))])
return res
def get_rep(corners):
corners[0]-=1
corners[-1]+=1
bps=sorted(list(set(corners)))
m=len(bps)
X=[1]
active=[1]
for i in range(1,m):
x,y=bps[i-1],bps[i]
d=y-x
A=mexp(len(active),d)
X=mvmult(A,X)
#debug(active,X)
#debug(A)
if i<m-1:
for j,c in enumerate(corners):
if c==y:
if j%2: # top: j and j+1 in active
idx=active.index(j)
X[idx+2]+=X[idx]
active.pop(idx)
active.pop(idx)
X.pop(idx)
X.pop(idx)
else: # bottom
active+=[j,j+1]
active.sort()
idx=active.index(j)
X=X[:idx]+[0,X[idx-1]]+X[idx:]
else:
return X[0]
n=int(inp())
inp()
d,*D=map(int,inp().split())
if d==0 and all(dd==0 for dd in D):
print(1,1)
else:
while d==0: d,*D=D
up=(d>=0)
corners=[0,d]
for d in D:
x=corners[-1]+d
if up==(d>=0):
corners[-1]=x
if up!=(d>=0):
up=(d>=0)
corners.append(x)
debug(corners)
cands=[(-1,0,0)]
low=(0,0)
maxdiff=(0,0,0)
for i,corner in enumerate(corners):
if corner<low[0]: low=(corner,i)
if corner-low[0]>=cands[0][0]:
if corner-low[0]==cands[0][0] and low[1]>cands[0][1]:
cands+=[(corner-low[0],low[1],i)]
else:
cands=[(corner-low[0],low[1],i)]
L=cands[0][0]+1
if L>1:
X=0
debug(cands)
for _, starti, endi in cands:
#debug(corners[starti:endi+1])
X+=get_rep(corners[starti:endi+1])
else:
X=1-corners[-1]
print(L,X % 998244353)
``` | output | 1 | 98,843 | 12 | 197,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p;
* if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p.
For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].
Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.
For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d.
The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard.
The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9).
Output
Print two integers:
* the first integer should be equal to the length of the longest increasing subsequence of p;
* the second should be equal to the number of them modulo 998244353.
You should print only the second number modulo 998244353.
Examples
Input
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
Note
The first test case was explained in the statement.
In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].
In the third test case p = [1, 2, …, 2000000000].
Submitted Solution:
```
print("atulpandey")
``` | instruction | 0 | 98,844 | 12 | 197,688 |
No | output | 1 | 98,844 | 12 | 197,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p;
* if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p.
For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].
Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.
For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d.
The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard.
The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9).
Output
Print two integers:
* the first integer should be equal to the length of the longest increasing subsequence of p;
* the second should be equal to the number of them modulo 998244353.
You should print only the second number modulo 998244353.
Examples
Input
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
Note
The first test case was explained in the statement.
In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].
In the third test case p = [1, 2, …, 2000000000].
Submitted Solution:
```
import sys, io, os
if os.environ['USERNAME']=='kissz':
inp=open('in4.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
def mexp(size,power):
A=[]
for i in range(size):
A.append([int(j<=(i//2)*2) for j in range(size)])
powers={1: A}
p=1
while p*2<=power:
powers[p*2]=mmmult(powers[p],powers[p])
p*=2
A=powers[p]
power-=p
while power>0:
p=p//2
if p<=power:
A=mmmult(A,powers[p])
power-=p
return A
def mvmult(A,V):
res=[]
for i in range(len(A)):
res.append(sum(a*v for a,v in zip(A[i],V)))
return res
def mmmult(A,B):
res=[]
for i in range(len(A)):
res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))])
return res
n=int(inp())
inp()
d,*D=map(int,inp().split())
while d==0: d,*D=D
up=(d>=0)
corners=[0,d]
for d in D:
x=corners[-1]+d
if up==(d>=0):
corners[-1]=x
if up!=(d>=0):
up=(d>=0)
corners.append(x)
low=(0,0)
maxdiff=(0,0,0)
for i,corner in enumerate(corners):
if corner<low[0]: low=(corner,i)
if corner-low[0]>=maxdiff[0]:
maxdiff=(corner-low[0],low[1],i)
debug(maxdiff)
corners=corners[maxdiff[1]:maxdiff[2]+1]
debug(corners)
L=maxdiff[0]+1
corners[0]-=1
corners[-1]+=1
bps=sorted(list(set(corners)))
m=len(bps)
X=[1]
active=[1]
for i in range(1,m):
x,y=bps[i-1],bps[i]
d=y-x
A=mexp(len(active),d)
X=mvmult(A,X)
debug(active,X)
debug(A)
if i<m-1:
for j,c in enumerate(corners):
if c==y:
if j%2: # top: j and j+1 in active
idx=active.index(j)
X[idx+2]+=X[idx]
active.pop(idx)
active.pop(idx)
X.pop(idx)
X.pop(idx)
else: # bottom
active+=[j,j+1]
active.sort()
idx=active.index(j)
X=X[:idx]+[0,X[idx-1]]+X[idx:]
else:
print(L,X[0])
``` | instruction | 0 | 98,845 | 12 | 197,690 |
No | output | 1 | 98,845 | 12 | 197,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p;
* if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p.
For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].
Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.
For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d.
The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard.
The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9).
Output
Print two integers:
* the first integer should be equal to the length of the longest increasing subsequence of p;
* the second should be equal to the number of them modulo 998244353.
You should print only the second number modulo 998244353.
Examples
Input
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
Note
The first test case was explained in the statement.
In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].
In the third test case p = [1, 2, …, 2000000000].
Submitted Solution:
```
import sys, io, os
if os.environ['USERNAME']=='kissz':
inp=open('in4.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
def mexp(size,power):
A=[]
for i in range(size):
A.append([int(j<=(i//2)*2) for j in range(size)])
powers={1: A}
p=1
while p*2<=power:
powers[p*2]=mmmult(powers[p],powers[p])
p*=2
A=powers[p]
power-=p
while power>0:
p=p//2
if p<=power:
A=mmmult(A,powers[p])
power-=p
return A
def mvmult(A,V):
res=[]
for i in range(len(A)):
res.append(sum(a*v for a,v in zip(A[i],V)) % 998244353 )
return res
def mmmult(A,B):
res=[]
for i in range(len(A)):
res.append([sum(a*B[j][k] for j,a in enumerate(A[i])) for k in range(len(B[0]))])
return res
def get_rep(corners):
corners[0]-=1
corners[-1]+=1
bps=sorted(list(set(corners)))
m=len(bps)
X=[1]
active=[1]
for i in range(1,m):
x,y=bps[i-1],bps[i]
d=y-x
A=mexp(len(active),d)
X=mvmult(A,X)
debug(active,X)
debug(A)
if i<m-1:
for j,c in enumerate(corners):
if c==y:
if j%2: # top: j and j+1 in active
idx=active.index(j)
X[idx+2]+=X[idx]
active.pop(idx)
active.pop(idx)
X.pop(idx)
X.pop(idx)
else: # bottom
active+=[j,j+1]
active.sort()
idx=active.index(j)
X=X[:idx]+[0,X[idx-1]]+X[idx:]
else:
return X[0]
n=int(inp())
inp()
d,*D=map(int,inp().split())
while d==0: d,*D=D
up=(d>=0)
corners=[0,d]
for d in D:
x=corners[-1]+d
if up==(d>=0):
corners[-1]=x
if up!=(d>=0):
up=(d>=0)
corners.append(x)
debug(corners)
cands=[(-1,0,0)]
low=(0,0)
maxdiff=(0,0,0)
for i,corner in enumerate(corners):
if corner<low[0]: low=(corner,i)
if corner-low[0]>cands[0][0]:
cands=[(corner-low[0],low[1],i)]
elif corner-low[0]==cands[0][0]:
cands+=[(corner-low[0],low[1],i)]
L=cands[0][0]+1
if L>1:
X=0
debug(cands)
for _, starti, endi in cands:
debug(corners[starti:endi+1])
X+=get_rep(corners[starti:endi+1])
else:
X=1-corners[-1]
print(L,X)
``` | instruction | 0 | 98,846 | 12 | 197,692 |
No | output | 1 | 98,846 | 12 | 197,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Igor had a sequence d_1, d_2, ..., d_n of integers. When Igor entered the classroom there was an integer x written on the blackboard.
Igor generated sequence p using the following algorithm:
1. initially, p = [x];
2. for each 1 ≤ i ≤ n he did the following operation |d_i| times:
* if d_i ≥ 0, then he looked at the last element of p (let it be y) and appended y + 1 to the end of p;
* if d_i < 0, then he looked at the last element of p (let it be y) and appended y - 1 to the end of p.
For example, if x = 3, and d = [1, -1, 2], p will be equal [3, 4, 3, 4, 5].
Igor decided to calculate the length of the longest increasing subsequence of p and the number of them.
A sequence a is a subsequence of a sequence b if a can be obtained from b by deletion of several (possibly, zero or all) elements.
A sequence a is an increasing sequence if each element of a (except the first one) is strictly greater than the previous element.
For p = [3, 4, 3, 4, 5], the length of longest increasing subsequence is 3 and there are 3 of them: [\underline{3}, \underline{4}, 3, 4, \underline{5}], [\underline{3}, 4, 3, \underline{4}, \underline{5}], [3, 4, \underline{3}, \underline{4}, \underline{5}].
Input
The first line contains a single integer n (1 ≤ n ≤ 50) — the length of the sequence d.
The second line contains a single integer x (-10^9 ≤ x ≤ 10^9) — the integer on the blackboard.
The third line contains n integers d_1, d_2, …, d_n (-10^9 ≤ d_i ≤ 10^9).
Output
Print two integers:
* the first integer should be equal to the length of the longest increasing subsequence of p;
* the second should be equal to the number of them modulo 998244353.
You should print only the second number modulo 998244353.
Examples
Input
3
3
1 -1 2
Output
3 3
Input
3
100
5 -3 6
Output
9 7
Input
3
1
999999999 0 1000000000
Output
2000000000 1
Input
5
34
1337 -146 42 -69 228
Output
1393 3876
Note
The first test case was explained in the statement.
In the second test case p = [100, 101, 102, 103, 104, 105, 104, 103, 102, 103, 104, 105, 106, 107, 108].
In the third test case p = [1, 2, …, 2000000000].
Submitted Solution:
```
import sys, io, os
if os.environ['USERNAME']=='kissz':
inp=open('in3.txt','r').readline
def debug(*args):
print(*args,file=sys.stderr)
else:
inp=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def debug(*args):
pass
# SCRIPT STARTS
def polyadd(poly1,poly2):
poly=[0]*max(len(poly1),len(poly2))
for i,p in enumerate(poly1):
poly[i]+=p
for i,p in enumerate(poly2):
poly[i]+=p
return poly
def polysub(poly1,poly2):
poly=[0]*max(len(poly1),len(poly2))
for i,p in enumerate(poly1):
poly[i]+=p
for i,p in enumerate(poly2):
poly[i]-=p
return poly
def polymult(poly1,poly2):
poly=[0]*(len(poly1)+len(poly2)-1)
for i,pi in enumerate(poly1):
for j,pj in enumerate(poly2):
poly[i+j]+=pi*pj % 998244353
return poly
ex=[1]
N=[ex]
ndiv=[1]
div=1
for i in range(50):
div*=(i+1)
ex=polymult(ex,[i,1])
ndiv.append(div)
N.append(ex)
class multipoly():
def __init__(self,min_element,max_element):
self.ranges=[min_element-1,min_element,min_element+1] # keep sorted!
self.poly={min_element-1: [1], min_element:[1], min_element+1:[0]}
self.pos=min_element
def set_poly(self,rmin,poly,caller_name=None):
self.poly[rmin]=poly
if rmin not in self.ranges:
self.ranges.append(rmin)
self.ranges.sort()
if caller_name:
debug(caller_name,rmin,poly)
def find_range(self,x): # brute
for rmin in reversed(self.ranges):
if rmin<=x: return rmin
def rebase_poly(self,poly,rmin,x):
if x>rmin:
rebase=x-rmin
ex=[1]
new_poly=[0]*len(poly)
for p in poly:
for i,e in enumerate(ex):
new_poly[i]+=e*p
ex=polymult(ex, [rebase,1])
return new_poly
else:
return poly
def get_poly(self,x):
rmin=self.find_range(x)
poly=self.poly[rmin]
return self.rebase_poly(poly,rmin,x)
def convert_poly(self,poly):
series=[0]*len(poly)
while any(p!=0 for p in poly):
while not poly[-1]: poly.pop()
n=len(poly)-1
serie=N[n]
d=poly[-1]*ndiv[n]//serie[-1]
series[n]=d
poly=polysub(poly,polymult(serie,[d//ndiv[n]]))
return series
def convert_series(self,series):
poly=[0]
for i,s in enumerate(series):
poly=polyadd(poly,polymult(N[i],[s//ndiv[i]]))
return poly
def integrate_series(self,series):
return [0]+series
def x_eval(self,x):
rmin=self.find_range(x)
poly=self.poly[rmin]
return sum(p*((x-rmin+1)**i) for i,p in enumerate(poly)) % 998244353
def integrate(self,low):
poly=self.get_poly(low)
series=self.convert_poly(poly)
series=self.integrate_series(series)
new_poly=self.convert_series(series)
base=self.x_eval(low-1)
new_poly[0]+=base
self.set_poly(low,new_poly)
def up(self,low,high):
self.set_poly(high+1,self.get_poly(high+1))
self.integrate(low)
for rmin in self.ranges:
if low<rmin<=high:
self.integrate(rmin)
def downsum(self,low):
poly1=self.get_poly(low)
poly2=self.get_poly(low-1)
poly=polyadd(poly1,poly2)
self.set_poly(low,poly)
def down(self,high,low):
self.set_poly(high+1,self.get_poly(high+1))
checked=[]
for rmin in reversed(self.ranges):
if low<=rmin<=high:
if rmin<high and rmin+1 not in checked:
self.downsum(rmin+1)
checked.append(rmin+1)
if rmin not in checked:
self.downsum(rmin)
checked.append(rmin)
if low not in checked:
self.downsum(low)
def move(self,to):
if to>self.pos:
self.up(self.pos+1,to)
else:
self.down(self.pos-1,to)
self.pos=to
debug('arrive',to)
n=int(inp())
inp()
d,*D=map(int,inp().split())
while d==0: d,*D=D
up=(d>=0)
corners=[0,d]
for d in D:
x=corners[-1]+d
if up==(d>=0):
corners[-1]=x
if up!=(d>=0):
up=(d>=0)
corners.append(x)
low=(0,0)
maxdiff=(0,0,0)
for i,corner in enumerate(corners):
if corner<low[0]: low=(corner,i)
if corner-low[0]>=maxdiff[0]:
maxdiff=(corner-low[0],low[1],i)
corners=corners[maxdiff[1]:maxdiff[2]+1]
MP=multipoly(corners[0],corners[-1])
for target in corners[1:]:
MP.move(target)
print(maxdiff[0]+1,MP.x_eval(corners[-1]))
``` | instruction | 0 | 98,847 | 12 | 197,694 |
No | output | 1 | 98,847 | 12 | 197,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,928 | 12 | 197,856 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
if n < 3 * k: print(-1)
else:
d = n // k - 1
t = list(str(i) + ' ' for i in range(1, k + 1))
print(''.join(t) + ''.join(i * d for i in t) + t[-1] * (n - (d + 1) * k))
``` | output | 1 | 98,928 | 12 | 197,857 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,929 | 12 | 197,858 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
if n // k < 3:
print(-1)
else:
v = [0] * n
for i in range(k):
v[2 * i] = v[2 * i + 1] = i + 1
for i in range(2 * k, n):
v[i] = (i - 2 * k) % k + 1
print(' '.join(map(str, v)))
``` | output | 1 | 98,929 | 12 | 197,859 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,930 | 12 | 197,860 |
Tags: constructive algorithms, implementation
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
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")
# ------------------- fast io --------------------
n, k = map(int, input().split())
if n < 3*k:
print(-1)
quit()
ans = [1]*n
start = 0
for i in range(k):
ans[start] = ans[start+1] = i+1
start += 2
f = 0
for i in range(start, n):
ans[i] = f+1
f += 1
if f == k: f = 0
print(" ".join(str(k) for k in ans))
``` | output | 1 | 98,930 | 12 | 197,861 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,931 | 12 | 197,862 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n,k=map(int,input().split())
if n//k <3:
print("-1")
exit()
ans=list()
for i in range(n):
if i<2*k:
ans.append(i // 2 + 1)
elif (i//k)%2==0:
ans.append(i%k+1)
else :
ans.append(k-i%k)
print(*ans)
``` | output | 1 | 98,931 | 12 | 197,863 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,932 | 12 | 197,864 |
Tags: constructive algorithms, implementation
Correct Solution:
```
n, m = map(int, input().split())
if n // m < 3:
print(-1)
exit()
res = []
for i in range(m):
res.append(i+1)
res.append(i+1)
for i in range(m):
res.append(i+1)
print(' '.join(map(str, res)), '1 ' * (n - 3*m))
``` | output | 1 | 98,932 | 12 | 197,865 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,933 | 12 | 197,866 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import sys
n, k = map(int, input().split())
if k * 3 > n:
print(-1)
exit(0)
ans = [1] * n
if n == k * 3 and n % 2 == 1:
if n == 3:
print(-1)
exit(0)
l = n - (n % 6) - 6
l = max(0, l)
filled = 0
f, s = 1, 2
for i in range(l):
if f > k:
f = 1
if s > k:
s = 1
if filled == k:
break
j = i % 6
r = [f, f, s, f, s, s][j]
ans[i] = r
if j == 5:
f, s = f + 2, s + 2
filled += 1
if j == 3:
filled += 1
tail = [k - 2, k - 2, k, k - 2, k - 1, k - 1, k, k, k - 1]
for i in range(9):
ans[l + i] = tail[i]
else:
filled = 0
f, s = 1, 2
for i in range(n):
if f > k:
f = 1
if s > k:
s = 1
if filled == k:
break
j = i % 6
r = [f, f, s, f, s, s][j]
ans[i] = r
if j == 5:
f, s = f + 2, s + 2
filled += 1
if j == 3:
filled += 1
s = ' '.join(map(str, ans))
sys.stdout.write(s)
``` | output | 1 | 98,933 | 12 | 197,867 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,934 | 12 | 197,868 |
Tags: constructive algorithms, implementation
Correct Solution:
```
#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import*
from io import BytesIO, IOBase
def vsInput():
sys.stdin = open('input.txt', 'r')
sys.stdout = open('output.txt', 'w')
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 value():return tuple(map(int,input().split()))
def array():return [int(i) for i in input().split()]
def Int():return int(input())
def Str():return input()
def arrayS():return [i for i in input().split()]
#-------------------------code---------------------------#
#vsInput()
n,k=value()
if(n<3*k or k==1):
print(-1)
else:
c=0
j=0
while(j<n%(2*k)):
print(c+1,end=" ")
c=(c+1)%k
j+=1
c=0
temp=-1
for i in range(j,n):
print(c+1,end=" ")
temp+=1
if(temp%2): c=(c+1)%k
``` | output | 1 | 98,934 | 12 | 197,869 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Greatest Secret Ever consists of n words, indexed by positive integers from 1 to n. The secret needs dividing between k Keepers (let's index them by positive integers from 1 to k), the i-th Keeper gets a non-empty set of words with numbers from the set Ui = (ui, 1, ui, 2, ..., ui, |Ui|). Here and below we'll presuppose that the set elements are written in the increasing order.
We'll say that the secret is safe if the following conditions are hold:
* for any two indexes i, j (1 ≤ i < j ≤ k) the intersection of sets Ui and Uj is an empty set;
* the union of sets U1, U2, ..., Uk is set (1, 2, ..., n);
* in each set Ui, its elements ui, 1, ui, 2, ..., ui, |Ui| do not form an arithmetic progression (in particular, |Ui| ≥ 3 should hold).
Let us remind you that the elements of set (u1, u2, ..., us) form an arithmetic progression if there is such number d, that for all i (1 ≤ i < s) fulfills ui + d = ui + 1. For example, the elements of sets (5), (1, 10) and (1, 5, 9) form arithmetic progressions and the elements of sets (1, 2, 4) and (3, 6, 8) don't.
Your task is to find any partition of the set of words into subsets U1, U2, ..., Uk so that the secret is safe. Otherwise indicate that there's no such partition.
Input
The input consists of a single line which contains two integers n and k (2 ≤ k ≤ n ≤ 106) — the number of words in the secret and the number of the Keepers. The numbers are separated by a single space.
Output
If there is no way to keep the secret safe, print a single integer "-1" (without the quotes). Otherwise, print n integers, the i-th of them representing the number of the Keeper who's got the i-th word of the secret.
If there are multiple solutions, print any of them.
Examples
Input
11 3
Output
3 1 2 1 1 2 3 2 2 3 1
Input
5 2
Output
-1 | instruction | 0 | 98,935 | 12 | 197,870 |
Tags: constructive algorithms, implementation
Correct Solution:
```
import sys
n ,k = map(int, input().split())
if n // k < 3 or k == 1:
print(-1)
exit()
num = 1
output = []
for i in range(k):
for j in range(2):
output.append(str(i+1))
num = num + 1
l = num + k
for i in range(k):
output.append(str(i+1))
num = num + 1
while num < n+1:
output.append("1")
num = num + 1
print(" ".join(output))
``` | output | 1 | 98,935 | 12 | 197,871 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S:
* its elements were distinct integers from 1 to limit;
* the value of <image> was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation).
Can you help Picks and find any set S, that satisfies all the above conditions?
Input
The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105).
Output
In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.
If it's impossible to find a suitable set, print -1.
Examples
Input
5 5
Output
2
4 5
Input
4 3
Output
3
2 3 1
Input
5 1
Output
-1
Note
In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.
In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4. | instruction | 0 | 99,007 | 12 | 198,014 |
Tags: bitmasks, greedy, implementation, sortings
Correct Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br #c++ upperbound br(array,element)
def lbit(x):
return x&-x
def main():
n,s=map(int,input().split(" "))
ans=[]
for x in range(s,0,-1):
#print(n)
if n-(lbit(x))>=0:
ans.append(x)
n=n-(lbit(x))
#print(ans)
if n==0:
print(len(ans))
print(*ans)
else:
print(-1)
#-----------------------------BOSS-------------------------------------!
# 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")
# endregion
if __name__ == "__main__":
main()
``` | output | 1 | 99,007 | 12 | 198,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
At the children's day, the child came to Picks's house, and messed his house up. Picks was angry at him. A lot of important things were lost, in particular the favorite set of Picks.
Fortunately, Picks remembers something about his set S:
* its elements were distinct integers from 1 to limit;
* the value of <image> was equal to sum; here lowbit(x) equals 2k where k is the position of the first one in the binary representation of x. For example, lowbit(100102) = 102, lowbit(100012) = 12, lowbit(100002) = 100002 (binary representation).
Can you help Picks and find any set S, that satisfies all the above conditions?
Input
The first line contains two integers: sum, limit (1 ≤ sum, limit ≤ 105).
Output
In the first line print an integer n (1 ≤ n ≤ 105), denoting the size of S. Then print the elements of set S in any order. If there are multiple answers, print any of them.
If it's impossible to find a suitable set, print -1.
Examples
Input
5 5
Output
2
4 5
Input
4 3
Output
3
2 3 1
Input
5 1
Output
-1
Note
In sample test 1: lowbit(4) = 4, lowbit(5) = 1, 4 + 1 = 5.
In sample test 2: lowbit(1) = 1, lowbit(2) = 2, lowbit(3) = 1, 1 + 2 + 1 = 4. | instruction | 0 | 99,012 | 12 | 198,024 |
Tags: bitmasks, greedy, implementation, sortings
Correct Solution:
```
s,t = map(int,input().split())
c = {}
arr = []
for i in range(t,0,-1):
l = 0
tmp = i
while tmp%2==0:
tmp /= 2
l += 1
if 2**l<=s:
s -= 2**l
arr.append(i)
if s==0:
print(len(arr))
print(*arr)
else:
print(-1)
``` | output | 1 | 99,012 | 12 | 198,025 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,255 | 12 | 198,510 |
"Correct Solution:
```
class BIT: #0-indexed
__slots__ = ["size", "tree","depth","n0"]
def __init__(self, n):
self.size = n
self.tree = [0]*(n+1)
self.depth = n.bit_length()
self.n0 = 1<<self.depth
def get_sum(self, i): #a_0 + ... + a_{i} #閉区間
s = 0; i += 1
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def range_sum(self,l,r): #a_l + ... + a_r 閉区間
return self.get_sum(r) - self.get_sum(l-1)
def add(self, i, x):
i += 1
while i <= self.size:
self.tree[i] += x
i += i & -i
def bisect_left(self,w):
#和が w 以上になる最小の index
#w が存在しない場合 self.size を返す
if w <= 0: return 0
x,k = 0,self.n0
for _ in range(self.depth):
k >>= 1
if x+k <= self.size and self.tree[x+k] < w:
w -= self.tree[x+k]
x += k
return x
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read
n,k = map(int,readline().split())
*p, = map(int,readline().split())
b = BIT(n)
num = BIT(n)
MOD = 998244353
inv2 = (MOD+1)//2
for i in range(k):
b.add(p[i]-1,inv2)
num.add(p[i]-1,1)
ans = k*(k-1)//2%MOD*inv2%MOD
prob = (k-1)*pow(k,MOD-2,MOD)%MOD #(k-1/k)
pinv = pow(prob,MOD-2,MOD)
val = pinv*inv2%MOD #(k-1)/k/2: これを bit に足していく
rate = prob #倍率
for j in range(k,n):
# p_i < p_j
pj = p[j]-1
v = b.get_sum(pj)
ans += v*rate%MOD
ans %= MOD
# p_i > p_j
w = b.get_sum(n-1)-v
ans += (j - num.get_sum(pj)) - w*rate%MOD
ans %= MOD
b.add(pj,val)
num.add(pj,1)
val = val*pinv%MOD
rate = rate*prob%MOD
print(ans%MOD)
``` | output | 1 | 99,255 | 12 | 198,511 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,256 | 12 | 198,512 |
"Correct Solution:
```
class SegmentTree():
def __init__(self, init, unit, f):
self.unit = unit
self.f = f
if type(init) == int:
self.n = init
# self.n = 1 << (self.n - 1).bit_length()
self.X = [unit] * (self.n * 2)
else:
self.n = len(init)
# self.n = 1 << (self.n - 1).bit_length()
self.X = [unit] * self.n + init + [unit] * (self.n - len(init))
for i in range(self.n-1, 0, -1):
self.X[i] = self.f(self.X[i*2], self.X[i*2|1])
def getvalue(self, i):
i += self.n
return self.X[i]
def update(self, i, x):
i += self.n
self.X[i] = x
i >>= 1
while i:
self.X[i] = self.f(self.X[i*2], self.X[i*2|1])
i >>= 1
def add(self, i, x):
i += self.n
self.X[i] = (self.X[i] + x) % mod
i >>= 1
while i:
self.X[i] = self.f(self.X[i*2], self.X[i*2|1])
i >>= 1
def getrange(self, l, r):
l += self.n
r += self.n
al = self.unit
ar = self.unit
while l < r:
if l & 1:
al = self.f(al, self.X[l])
l += 1
if r & 1:
r -= 1
ar = self.f(self.X[r], ar)
l >>= 1
r >>= 1
return self.f(al, ar)
def debug(self):
de = []
a, b = self.n, self.n * 2
while b:
de.append(self.X[a:b])
a, b = a//2, a
print("--- debug ---")
for d in de[::-1]:
print(d)
print("--- ---")
def r(a):
for i in range(1, 10001):
if i and a * i % mod <= 10000:
return str(a*i%mod) + "/" + str(i)
if i and -a * i % mod <= 10000:
return str(-(-a*i%mod)) + "/" + str(i)
return a
mod = 998244353
N, K = map(int, input().split())
P = [int(a) - 1 for a in input().split()]
f = lambda a, b: (a + b) % mod
p1 = (K - 1) * (K - 2) * pow(4, mod - 2, mod) % mod
p2 = K * (K - 1) * pow(4, mod - 2, mod) % mod
m = (K - 1) * pow(K, mod - 2, mod) % mod
invm = K * pow(K - 1, mod - 2, mod) % mod
st1 = SegmentTree(N, 0, f)
st2 = SegmentTree(N, 0, f)
ans = p2
for i, x in enumerate(P):
if i >= K:
ans = (ans + st1.getrange(x, N)) % mod
st1.add(x, 1)
s = 1
invs = 1
st = SegmentTree(N, 0, f)
for i, x in enumerate(P[:K]):
st.add(x, 1)
for i in range(K, N):
s = s * m % mod
invs = invs * invm % mod
x = P[i]
a = st.getrange(x, N) * s % mod
ans = (ans + p2 - p1 - a) % mod
st.add(x, invs % mod)
print(ans)
``` | output | 1 | 99,256 | 12 | 198,513 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,257 | 12 | 198,514 |
"Correct Solution:
```
class BIT: #0-indexed
__slots__ = ["size", "tree","depth","n0"]
def __init__(self, n):
self.size = n
self.tree = [0]*(n+1)
self.depth = n.bit_length()
self.n0 = 1<<self.depth
def get_sum(self, i): #a_0 + ... + a_{i} #閉区間
s = 0; i += 1
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def range_sum(self,l,r): #a_l + ... + a_r 閉区間
return self.get_sum(r) - self.get_sum(l-1)
def add(self, i, x):
i += 1
while i <= self.size:
self.tree[i] += x
i += i & -i
def bisect_left(self,w):
#和が w 以上になる最小の index
#w が存在しない場合 self.size を返す
if w <= 0: return 0
x,k = 0,self.n0
for _ in range(self.depth):
k >>= 1
if x+k <= self.size and self.tree[x+k] < w:
w -= self.tree[x+k]
x += k
return x
# coding: utf-8
# Your code here!
import sys
readline = sys.stdin.readline
read = sys.stdin.read
n,k = map(int,readline().split())
*p, = map(int,readline().split())
b = BIT(n)
num = BIT(n)
MOD = 998244353
inv = (MOD+1)//2
for i in range(k):
b.add(p[i]-1,1)
num.add(p[i]-1,1)
ans = k*(k-1)//2%MOD*inv%MOD
tot = k
rate = (k-1)*pow(k,MOD-2,MOD)%MOD
rateinv = pow(rate,MOD-2,MOD)
bunbo = rate
hosei = rateinv
for i in range(k,n):
pi = p[i]-1
v = b.get_sum(pi)
#print(v*inv%MOD*bunbo%MOD,v*inv%MOD*bunbo%MOD*4%MOD,"v")
ans += v*inv%MOD*bunbo%MOD
ans %= MOD
x = i - num.get_sum(pi)
w = x - (tot-v)*inv%MOD*bunbo%MOD
#print(x,tot,v)
#print(w,w*4%MOD,"w")
ans += w
ans %= MOD
b.add(pi,hosei)
num.add(pi,1)
tot += hosei
hosei = hosei*rateinv%MOD
bunbo = bunbo*rate%MOD
print(ans%MOD)
#print(ans*8%MOD)
``` | output | 1 | 99,257 | 12 | 198,515 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,258 | 12 | 198,516 |
"Correct Solution:
```
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
n, k = map(int, input().split())
p = list(map(lambda x: int(x) - 1, input().split()))
out = 0
mod = 998244353
mult_r = (k-1) * modinv(k, mod)
mult_inv = modinv(mult_r, mod)
mult = 1
inv = 1
seg = SegmentTree([0] * n, func = lambda x,y: x+y)
seg2 = SegmentTree([0] * n, func = lambda x,y: x+y)
for i in range(n):
if i >= k:
mult *= mult_r
mult %= mod
inv *= mult_inv
inv %= mod
expected_above = (seg.query(p[i], n) * mult) % mod
expected_below = (seg.query(0,p[i]) * mult) % mod
tot_above = seg2.query(p[i], n)
#tot_below = seg2.query(0, p[i])
out += tot_above - modinv(2, mod) * (expected_above)
out += modinv(2, mod) * (expected_below)
out %= mod
seg[p[i]] = inv
seg2[p[i]] = 1
print(out)
#print((modinv(2, mod) * dout) % mod)
``` | output | 1 | 99,258 | 12 | 198,517 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,259 | 12 | 198,518 |
"Correct Solution:
```
import sys
readline = sys.stdin.buffer.readline
mod=998244353
class BIT:
def __init__(self,n):
self.n=n
self.buf=[0]*n
def add(self,i,v):
buf=self.buf
while i<n:
buf[i]+=v
if buf[i]>=mod:
buf[i]-=mod
i+=(i+1)&(-i-1)
def get(self,i):
buf=self.buf
res=0
while i>=0:
res+=buf[i]
if res>=mod:
res-=mod
i-=(i+1)&(-i-1)
return res
def rng(self,b,e):
res=self.get(e-1)-self.get(b)
if res<0:
res+=mod
return res
n,k=map(int,readline().split())
p=list(map(int,readline().split()))
for i in range(n):
p[i]-=1
ans=0
bit=BIT(n)
for i in range(n):
ans+=i-bit.get(p[i])
bit.add(p[i],1)
z=pow(2,mod-2,mod);
w=1
winv=1
rem=(k-1)*pow(k,mod-2,mod)%mod
reminv=pow(rem,mod-2,mod)
bit=BIT(n)
for i in range(n):
lw=bit.get(p[i])
up=bit.rng(p[i],n)
dif=(lw-up+mod)%mod
ans=(ans+dif*w*z)%mod
bit.add(p[i],winv)
if i>=k-1:
w=w*rem%mod
winv=winv*reminv%mod
print(ans)
``` | output | 1 | 99,259 | 12 | 198,519 |
Provide a correct Python 3 solution for this coding contest problem.
Given are a permutation p_1, p_2, \dots, p_N of (1, 2, ..., N) and an integer K. Maroon performs the following operation for i = 1, 2, \dots, N - K + 1 in this order:
* Shuffle p_i, p_{i + 1}, \dots, p_{i + K - 1} uniformly randomly.
Find the expected value of the inversion number of the sequence after all the operations are performed, and print it modulo 998244353.
More specifically, from the constraints of this problem, it can be proved that the expected value is always a rational number, which can be represented as an irreducible fraction \frac{P}{Q}, and that the integer R that satisfies R \times Q \equiv P \pmod{998244353}, 0 \leq R < 998244353 is uniquely determined. Print this R.
Here, the inversion number of a sequence a_1, a_2, \dots, a_N is defined to be the number of ordered pairs (i, j) that satisfy i < j, a_i > a_j.
Constraints
* 2 \leq N \leq 200,000
* 2 \leq K \leq N
* (p_1, p_2, \dots, p_N) is a permutation of (1, 2, \dots, N).
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
p_1 p_2 ... p_N
Output
Print the expected value modulo 998244353.
Examples
Input
3 2
1 2 3
Output
1
Input
10 3
1 8 4 9 2 3 7 10 5 6
Output
164091855 | instruction | 0 | 99,260 | 12 | 198,520 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
class BIT:
#1-indexed
def __init__(self, n):
self.size = n
self.tree = [0] * (n + 1)
self.p = 2**(n.bit_length() - 1)
self.dep = n.bit_length()
def get(self, i):
s = 0
while i > 0:
s += self.tree[i]
i -= i & -i
return s
def add(self, i, x):
while i <= self.size:
self.tree[i] += x
i += i & -i
def bl(self, v):
if v <= 0:
return -1
s = 0
k = self.p
for _ in range(self.dep):
if s + k <= self.size and self.tree[s+k] < v:
s += k
v -= self.tree[s+k]
k //= 2
return s + 1
N, K = map(int, readline().split())
MOD = 998244353
P = list(map(int, readline().split()))
r = (K-1)*pow(K, MOD-2, MOD)
L = [pow(r, max(0, i-K+1), MOD) for i in range(N)]
Linv = [pow(l, MOD-2, MOD) for l in L]
T1 = BIT(N)
T2 = BIT(N)
ans = 0
asum = 0
ti = (MOD+1)//2
for i in range(N):
ans += i - T2.get(P[i])
g1 = T1.get(P[i])
ans = (ans + ti*L[i]*(2*g1-asum))%MOD
T2.add(P[i], 1)
T1.add(P[i], Linv[i])
asum = (asum + Linv[i]) % MOD
print(ans)
``` | output | 1 | 99,260 | 12 | 198,521 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d).
For example, the following sequences are good:
* [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum is a power of two. Similarly, such an element can be found for a_2 and a_3),
* [1, 1, 1, 1023],
* [7, 39, 89, 25, 89],
* [].
Note that, by definition, an empty sequence (with a length of 0) is good.
For example, the following sequences are not good:
* [16] (for a_1=16, it is impossible to find another element a_j such that their sum is a power of two),
* [4, 16] (for a_1=4, it is impossible to find another element a_j such that their sum is a power of two),
* [1, 3, 2, 8, 8, 8] (for a_3=2, it is impossible to find another element a_j such that their sum is a power of two).
You are given a sequence a_1, a_2, ..., a_n. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.
Input
The first line contains the integer n (1 ≤ n ≤ 120000) — the length of the given sequence.
The second line contains the sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
Output
Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all n elements, make it empty, and thus get a good sequence.
Examples
Input
6
4 7 1 5 4 9
Output
1
Input
5
1 2 3 4 5
Output
2
Input
1
16
Output
1
Input
4
1 1 1 1023
Output
0
Note
In the first example, it is enough to delete one element a_4=5. The remaining elements form the sequence [4, 7, 1, 4, 9], which is good. | instruction | 0 | 99,460 | 12 | 198,920 |
Tags: brute force, greedy, implementation
Correct Solution:
```
import sys, heapq
def binary(num):
left = 0
right = n
while left < right:
mid = (left + right) // 2
if arr[mid] < num:
left = mid + 1
elif arr[mid] > num:
right = mid
else:
return True
return False
n = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().split()))
arr.sort()
cnt = dict().fromkeys(set(arr), 0)
ans = 0
for i in arr:
cnt[i] += 1
for i in range(n):
now = arr[i]
can = False
for j in range(31):
target = pow(2, j) - now
if binary(target):
if target == now:
if cnt[now] >= 2:
can = True
break
else:
can = True
break
if not can:
ans += 1
print(ans)
``` | output | 1 | 99,460 | 12 | 198,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A sequence a_1, a_2, ..., a_n is called good if, for each element a_i, there exists an element a_j (i ≠ j) such that a_i+a_j is a power of two (that is, 2^d for some non-negative integer d).
For example, the following sequences are good:
* [5, 3, 11] (for example, for a_1=5 we can choose a_2=3. Note that their sum is a power of two. Similarly, such an element can be found for a_2 and a_3),
* [1, 1, 1, 1023],
* [7, 39, 89, 25, 89],
* [].
Note that, by definition, an empty sequence (with a length of 0) is good.
For example, the following sequences are not good:
* [16] (for a_1=16, it is impossible to find another element a_j such that their sum is a power of two),
* [4, 16] (for a_1=4, it is impossible to find another element a_j such that their sum is a power of two),
* [1, 3, 2, 8, 8, 8] (for a_3=2, it is impossible to find another element a_j such that their sum is a power of two).
You are given a sequence a_1, a_2, ..., a_n. What is the minimum number of elements you need to remove to make it good? You can delete an arbitrary set of elements.
Input
The first line contains the integer n (1 ≤ n ≤ 120000) — the length of the given sequence.
The second line contains the sequence of integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^9).
Output
Print the minimum number of elements needed to be removed from the given sequence in order to make it good. It is possible that you need to delete all n elements, make it empty, and thus get a good sequence.
Examples
Input
6
4 7 1 5 4 9
Output
1
Input
5
1 2 3 4 5
Output
2
Input
1
16
Output
1
Input
4
1 1 1 1023
Output
0
Note
In the first example, it is enough to delete one element a_4=5. The remaining elements form the sequence [4, 7, 1, 4, 9], which is good. | instruction | 0 | 99,461 | 12 | 198,922 |
Tags: brute force, greedy, implementation
Correct Solution:
```
import collections
int(input())
values = [int(i) for i in input().split()]
li = [2**i for i in range(30, 0, -1)]
ss = collections.Counter(values)
count = 0
for value in values:
options = []
for item in li:
diff = item - value
if diff < 0:
break
options.append(diff)
for option in options:
if option in ss and (option != value or ss.get(value, 0) > 1):
break
else:
count += 1
print(count)
``` | output | 1 | 99,461 | 12 | 198,923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.