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.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,821 | 12 | 165,642 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
import os
import random
import sys
from collections import deque
from math import inf
random.seed(0)
input = sys.stdin.buffer.readline
DEBUG = False
def solve():
def debug(*args):
if not DEBUG:
return
sys.stderr.write("\033[0;31m")
print(*args, file=sys.stderr)
sys.stderr.write("\033[0m")
sys.stderr.flush()
def query(*args):
(arr,) = args
assert len(arr) == K
if DEBUG:
xor = 0
for i in arr:
xor ^= A[i]
debug("query(" + ", ".join(map(str, args)) + "):", xor)
return xor
os.write(1, b"? %s\n" % " ".join(str(i + 1) for i in arr).encode())
result = int(input())
return result
def answerBad():
os.write(1, b"-1\n")
def answer(ans):
if DEBUG:
xor = 0
for x in A:
xor ^= x
debug(ans, xor)
assert ans == xor
os.write(1, b"! %d\n" % (ans))
if DEBUG:
N = random.randint(1, 10)
K = random.randint(1, N)
A = [random.randint(1, 10) for i in range(N)]
debug(N, K, A)
else:
(N, K) = [int(x) for x in input().split()]
graph = [{} for i in range(N + 1)]
for u in range(N + 1):
# Given current number of flipped on, u
for numOff in range(min(u, K) + 1):
# Get next possible number of flipped on by flipping some off and some on
numOn = K - numOff
if u + numOn <= N:
v = u - numOff + numOn
assert 0 <= v <= N
graph[u][v] = numOff
dist = {0: 0}
parent = {}
q = deque([0])
while q:
u = q.popleft()
d = dist[u]
for v, w in graph[u].items():
if v not in dist:
dist[v] = d + 1
parent[v] = u
q.append(v)
if N not in dist:
answerBad()
return
path = [N]
while path[-1] in parent:
path.append(parent[path[-1]])
path = path[::-1]
ans = 0
off = list(range(N))
on = []
for u, v in zip(path, path[1:]):
numOff = graph[u][v]
turnOff = []
for i in range(numOff):
turnOff.append(on.pop())
turnOn = []
for i in range(K - numOff):
turnOn.append(off.pop())
on.extend(turnOn)
off.extend(turnOff)
ans ^= query(turnOff + turnOn)
answer(ans)
if __name__ == "__main__":
if DEBUG:
for i in range(10000):
solve()
else:
solve()
``` | output | 1 | 82,821 | 12 | 165,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,822 | 12 | 165,644 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
import sys
import collections
n, k = map(int,input().split())
if n%2 == 1 and k%2 == 0:
sys.stdout.flush()
print("-1")
else:
q = collections.deque()
node = n
fin = 0
prev = dict()
diffs = dict()
q.append(node)
vis = [False]*(n+1)
vis[node] = True
while len(q) > 0:
even = q.popleft()
if even == 0:
break
odd = n-even
for i in range(max(k-odd,0),min(even+1,k+1)):
if not vis[even-i + k-i]:
vis[even-i + k-i] = True
prev[even-i + k-i] = even
q.append(even-i + k-i)
diffs[even-i + k-i] = i
x = 0
nums = []
while x != n:
nums.append(x)
x = prev[x]
odds = collections.deque()
evens = collections.deque()
for i in range(n):
evens.append(i+1)
ans = 0
for c in nums[::-1]:
amount = diffs[c]
query = []
for _ in range(amount):
t = evens.popleft()
query.append(str(t))
odds.append(t)
for _ in range(k-amount):
t = odds.popleft()
query.append(str(t))
evens.append(t)
sys.stdout.flush()
print("? " + " ".join(query))
ans = ans^int(input())
sys.stdout.flush()
print("! "+str(ans))
``` | output | 1 | 82,822 | 12 | 165,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,823 | 12 | 165,646 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
from sys import stdout
def reverse(n, req):return [x for x in range(1, n + 1) if x not in req]
def solve():
n, k = (int(x) for x in input().split())
if n % 2 == 1 and k % 2 == 0:print(-1);stdout.flush();return
elif n % k == 0:
xor = 0;curr_idx = 1
while curr_idx <= n:next_idx = curr_idx + k;print('?', ' '.join(str(x) for x in range(curr_idx, next_idx)));stdout.flush();xor ^= int(input());curr_idx = next_idx
print('!', xor);stdout.flush();return
elif n%2 != k%2 and n < 2 * k:
xor = 0;curr_idx = 1;kk = n - k
while True:
next_idx = curr_idx + kk;curr_arr = reverse(n, set(range(curr_idx, next_idx)));print('?', ' '.join(str(x) for x in curr_arr));stdout.flush();xor ^= int(input());curr_idx = next_idx
if (n - curr_idx + 1) < 2 * kk and (n - curr_idx + 1) % 2 == 0:break
if curr_idx < n:
arr = list(range(1, kk+1));next_idx = curr_idx + (n - curr_idx + 1) // 2;curr_arr = list(range(curr_idx, next_idx)) + arr
curr_arr = reverse(n, set(curr_arr[:kk]));print('?', ' '.join(str(x) for x in curr_arr));stdout.flush();xor ^= int(input())
curr_arr = list(range(next_idx, n+1)) + arr;curr_arr = reverse(n, set(curr_arr[:kk]));print('?', ' '.join(str(x) for x in curr_arr));stdout.flush();xor ^= int(input())
print('!', xor);stdout.flush();return
else:
xor = 0;curr_idx = 1
while True:
next_idx = curr_idx + k;print('?', ' '.join(str(x) for x in range(curr_idx, next_idx)));stdout.flush();xor ^= int(input());curr_idx = next_idx
if (n - curr_idx + 1) < 2 * k and (n - curr_idx + 1) % 2 == 0:break
if curr_idx < n:
arr = list(range(1, k+1));next_idx = curr_idx + (n - curr_idx + 1) // 2;curr_arr = list(range(curr_idx, next_idx)) + arr
print('?', ' '.join(str(x) for x in curr_arr[:k]));stdout.flush();xor ^= int(input())
curr_arr = list(range(next_idx, n+1)) + arr;print('?', ' '.join(str(x) for x in curr_arr[:k]));stdout.flush();xor ^= int(input())
print('!', xor);stdout.flush();return
if __name__ == '__main__':solve()
``` | output | 1 | 82,823 | 12 | 165,647 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,824 | 12 | 165,648 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
from heapq import heappush, heappop
def chk(i):
return 1 + (i + N - 1) // N * 2
def arar(i):
A = [1] * N
j = 0
while i:
A[j] += 2
j = (j + 1) % N
i -= 1
return A
H = []
hpush = lambda x: heappush(H, -x)
hpop = lambda: -heappop(H)
hmax = lambda: -H[0]
mmm = (1 << 20) - 1
N, K = map(int, input().split())
ng = 1
for i in range(300000):
if (N + i * 2) % K == 0 and (N + i * 2) // K >= chk(i):
ng = 0
break
if ng:
print(-1)
else:
# print("i =", i)
A = arar(i)
# print("A =", A)
for i, a in enumerate(A):
hpush((a << 20) + i)
ans = 0
while H:
L = []
I = []
for _ in range(K):
ai = hpop()
a = ai >> 20
i = ai & mmm
I.append(i)
if a > 1:
L.append((a - 1 << 20) + i)
print("?", *sorted([a + 1 for a in I]))
ans ^= int(input())
for ai in L:
hpush(ai)
print("!", ans)
``` | output | 1 | 82,824 | 12 | 165,649 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,825 | 12 | 165,650 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
import sys
input = sys.stdin.readline
n, k = map(int, input().split())
if n % 2 == 1 and k % 2 == 0:
print(-1)
exit()
want = [1] * n
tot = n
curr = 0
while tot % k != 0 or want[0] * k > tot:
want[curr] += 2
tot += 2
curr = (curr + 1) % n
out = 0
while tot:
poss = [(want[i], i) for i in range(n)]
poss.sort(reverse = True)
quer = []
for j in range(k):
quer.append(poss[j][1] + 1)
want[poss[j][1]] -= 1
tot -= k
print('?',' '.join(map(str,quer)))
sys.stdout.flush()
out ^= int(input())
print('!', out)
``` | output | 1 | 82,825 | 12 | 165,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits. | instruction | 0 | 82,826 | 12 | 165,652 |
Tags: brute force, constructive algorithms, dp, flows, graphs, greedy, implementation, interactive, shortest paths
Correct Solution:
```
from sys import stdin, stdout
input = stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
def gcd(x,y):
while (y):
x,y = y, x % y
return x
ip = inlt()
n = ip[0]
k = ip[1]
t = n
max_n = 1
while t % k != 0 and max_n < 500:
max_n += 2
t = max(n*(max_n-2) + 2, max_n * k)
if (t + n) % 2 == 1:
t += 1
while t < max_n * n and t % k != 0:
t += 2
if max_n == 501:
print(-1)
exit(0)
a = [max_n - 2] * n
for i in range((t - (max_n - 2) * n) // 2):
a[i] += 2
a = [(i, a[i]) for i in range(len(a))]
ans = 0
for i in range(t // k):
a.sort(key = lambda x : x[1], reverse = True)
print("?", end = ' ')
for j in range(k):
print(a[j][0] + 1, end = ' ')
a[j] = (a[j][0], a[j][1] - 1)
print()
stdout.flush()
ans = ans ^ inp()
print(f"! {ans}")
``` | output | 1 | 82,826 | 12 | 165,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
import sys
sys.stderr = sys.stdout
from collections import deque
def queries(n, k):
D = {}
Q = deque()
p = (0, n)
D[p] = None, None
Q.append(p)
while Q:
a, b = q = Q.popleft()
if a == n:
break
for i in range(max(k-a, 0), min(k, b) + 1):
d = 2*i - k
p = a + d, b - d
if p not in D:
D[p] = (q, i)
Q.append(p)
else:
return None
p, i = D[n, 0]
L = []
while p:
L.append(i)
p, i = D[p]
L.reverse()
A = deque((), n)
B = deque(range(1, n+1), n)
Q = []
for i in L:
S = ['?']
for _ in range(i):
a = B.popleft()
A.append(a)
S.append(a)
for _ in range(i, k):
b = A.popleft()
B.append(b)
S.append(b)
Q.append(' '.join(map(str, S)))
assert len(A) == n
return Q
def main():
n, k = readinti()
Q = queries(n, k)
if Q:
# XXX: Would be faster to print all queries first, but could lead to
# deadlock depending on size of pipe buffer
x = 0
for q in Q:
print(q, flush=True)
x ^= readint()
print(f"! {x}")
else:
print('-1', flush=True)
##########
def readint():
return int(input())
def readinti():
return map(int, input().split())
def readintt():
return tuple(readinti())
def readintl():
return list(readinti())
def readinttl(k):
return [readintt() for _ in range(k)]
def readintll(k):
return [readintl() for _ in range(k)]
def log(*args, **kwargs):
print(*args, **kwargs, file=sys.__stderr__)
if __name__ == '__main__':
main()
``` | instruction | 0 | 82,827 | 12 | 165,654 |
Yes | output | 1 | 82,827 | 12 | 165,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from heapq import *
def ask(lst):
print("?", *lst, flush=True)
return int(input())
def main():
n, k = map(int, input().split())
i = 0
while 1:
if i > 10 ** 6:
print(-1)
return
i += 1
if i % 2 == 1:
max_ = i
else:
max_ = i - 1
if k * i < n or (k * i - n) % 2 == 1 or n * max_ < i * k:
continue
else:
break
cnt = [1] * n
z = k * i - n
if i % 2 == 1:
max_ = i
else:
max_ = i - 1
for i in range(n):
plus = min(z, max_ - 1)
cnt[i] += plus
z -= plus
hq = []
for i, c in enumerate(cnt, 1):
heappush(hq, (-c, i))
ans = 0
while hq:
q = []
add = []
for _ in range(k):
c, i = heappop(hq)
c += 1
q.append(i)
if c != 0:
add.append((c, i))
ans ^= ask(q)
for tmp in add:
heappush(hq, tmp)
print("!", ans)
for _ in range(1):
main()
``` | instruction | 0 | 82,828 | 12 | 165,656 |
Yes | output | 1 | 82,828 | 12 | 165,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
from sys import stdout
def reverse(n, req):return [x for x in range(1, n + 1) if x not in req]
def solve():
n, k = (int(x) for x in input().split())
if n % 2 == 1 and k % 2 == 0:print(-1);stdout.flush();return
elif n % k == 0:
xor = 0
curr_idx = 1
while curr_idx <= n:
next_idx = curr_idx + k
print('?', ' '.join(str(x) for x in range(curr_idx, next_idx)))
stdout.flush()
xor ^= int(input())
curr_idx = next_idx
print('!', xor)
stdout.flush()
return
elif n%2 != k%2 and n < 2 * k:
# solve like n, n-k but reverse
xor = 0
curr_idx = 1
kk = n - k
while True:
next_idx = curr_idx + kk
curr_arr = reverse(n, set(range(curr_idx, next_idx)))
print('?', ' '.join(str(x) for x in curr_arr))
stdout.flush()
xor ^= int(input())
curr_idx = next_idx
if (n - curr_idx + 1) < 2 * kk and (n - curr_idx + 1) % 2 == 0:
break
if curr_idx < n:
arr = list(range(1, kk+1))
next_idx = curr_idx + (n - curr_idx + 1) // 2
curr_arr = list(range(curr_idx, next_idx)) + arr
curr_arr = reverse(n, set(curr_arr[:kk]))
print('?', ' '.join(str(x) for x in curr_arr))
stdout.flush()
xor ^= int(input())
curr_arr = list(range(next_idx, n+1)) + arr
curr_arr = reverse(n, set(curr_arr[:kk]))
print('?', ' '.join(str(x) for x in curr_arr))
stdout.flush()
xor ^= int(input())
print('!', xor)
stdout.flush()
return
else:
xor = 0
curr_idx = 1
while True:
next_idx = curr_idx + k
print('?', ' '.join(str(x) for x in range(curr_idx, next_idx)))
stdout.flush()
xor ^= int(input())
curr_idx = next_idx
if (n - curr_idx + 1) < 2 * k and (n - curr_idx + 1) % 2 == 0:
break
if curr_idx < n:
arr = list(range(1, k+1))
next_idx = curr_idx + (n - curr_idx + 1) // 2
curr_arr = list(range(curr_idx, next_idx)) + arr
print('?', ' '.join(str(x) for x in curr_arr[:k]))
stdout.flush()
xor ^= int(input())
curr_arr = list(range(next_idx, n+1)) + arr
print('?', ' '.join(str(x) for x in curr_arr[:k]))
stdout.flush()
xor ^= int(input())
print('!', xor)
stdout.flush()
return
# long until 2x with tail
# 2x with tail or 1x with tail are even
# yay
if __name__ == '__main__':
solve()
``` | instruction | 0 | 82,829 | 12 | 165,658 |
Yes | output | 1 | 82,829 | 12 | 165,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
import sys, os
from queue import Queue
# SCRIPT STARTS HERE
class sim:
def __init__(self,A):
self.n=len(A)
self.A=[0]+A
def query(self,ix):
#print('?',*ix)
x=0
for i in ix:
x^=self.A[i]
print('?->',x)
return x
if os.environ['USERNAME']=='kissz':
#n=5;k=3;simulator=sim([2,1,7,5,6])
#n=3;k=2;simulator=sim([2,1,3])
#n=4;k=3;simulator=sim([2,1,5,6])
#n=1;k=1;simulator=sim([3])
#n=6;k=5;simulator=sim([3,43,4,4,3,0])
#n=2;k=1;simulator=sim([3,2])
n=500;k=499;simulator=sim([*range(500)])
inp=simulator.query
def debug(*args):
print(*args,file=sys.stderr)
else:
n,k=map(int,input().split())
def inp(ix):
print('?',*ix)
sys.stdout.flush()
return int(input())
def debug(*args):
pass
if n%2==1 and k%2==0:
print(-1)
else:
M=[(-1,-1)]*(n+1)
M[0]=(0,0) # nr on -> steps, nr on prev
Q=Queue()
Q.put(0)
while not Q.empty():
q=Q.get()
for i in range(max(0,q+k-n),min(q,k)+1):
qn=q+k-2*i
if M[qn][0]<0:
M[qn]=(M[q][0]+1,q)
Q.put(qn)
debug(M)
L=[]
on=n
while on!=0:
L.append(on)
on=M[on][1]
L.reverse()
debug(L)
X=[False]*(n+1)
on=0
x=0
for y in L:
o=(k-(y-on))//2
p=k-o
ix=[]
i=1
while p>0 or o>0:
if X[i]:
if o>0:
ix.append(i)
o-=1
else:
if p>0:
ix.append(i)
p-=1
i+=1
for i in ix:
X[i]=not X[i]
x^=inp(ix)
on=y
print('!',x)
``` | instruction | 0 | 82,830 | 12 | 165,660 |
Yes | output | 1 | 82,830 | 12 | 165,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
#!/usr/bin/env python3
# set vim: fdm=marker sw=4 ts=4 et
from collections import defaultdict
from collections import deque
from sys import stdout, exit
n, k = map(int, input().split())
valid = False
for i in range(0, k):
if (n - i) % (k - i) == 0 and ((n - i) // (k - i)) % 2 == 1:
valid = True
break
if not valid:
print(-1)
exit(0)
ans = 0
for i2 in range((n - i) // (k - i)):
a = []
for i3 in range(i):
a.append(i3 + 1)
for i3 in range(0, k - i):
a.append(i + i2 * (k - i) + i3 + 1)
print('?', ' '.join(map(str, a)))
stdout.flush()
ans = ans ^ int(input())
print('!', ans)
``` | instruction | 0 | 82,831 | 12 | 165,662 |
No | output | 1 | 82,831 | 12 | 165,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
import sys, os
# SCRIPT STARTS HERE
class sim:
def __init__(self,A):
self.n=len(A)
self.A=[0]+A
def query(self,ix):
print('?',*ix)
x=0
for i in ix:
x^=self.A[i]
return x
if os.environ['USERNAME']=='kissz':
n=5;k=3;simulator=sim([2,1,7,5,6])
#n=3;k=2;simulator=sim([2,1,3])
#n=4;k=3;simulator=sim([2,1,5,6])
inp=simulator.query
def debug(*args):
print(*args,file=sys.stderr)
else:
n,k=map(int,input().split())
def inp(ix):
print('?',*ix)
sys.stdout.flush()
return int(input())
def debug(*args):
pass
x=0
m=(n+k-1)//k
mk=m*k
r=mk-n
q=0
if r%2==1 and k%2==0:
print(-1)
else:
if r>0 and m<3:
r+=(3-m)*k
m=3
if r%2==1:
m+=1
mk=m*k
r+=k
Q=[(3,i) for i in range(1,r//2+1)]+[(1,i) for i in range(r//2+1,n+1)]
for _ in range(m):
ix=[]
while len(ix)<k:
Q.sort(reverse=True)
i=0
while Q[i][1] in ix:
i+=1
ix+=[Q[i][1]]
Q[i]=(Q[i][0]-1,Q[i][1])
x^=inp(ix)
print('!',x)
``` | instruction | 0 | 82,832 | 12 | 165,664 |
No | output | 1 | 82,832 | 12 | 165,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
n, k = map(int, input().split())
xor = 0
if n % k == 0:
for i in range(0, n, k):
print("?", *range(i + 1, i + k + 1))
xor = xor ^ int(input())
print("!", xor)
else:
if k % 2 == 0 and n % 2 != 0:
print(-1)
elif (n % k + k) % 2 == 0 and n // k > 1:
ans = n // k + 1
for i in range(0, n - 2 * k, k):
print("?", *range(i + 1, i + k + 1))
xor = xor ^ int(input())
m = n % k + k
print("?", *range(n - m + 1, n - m // 2 + 1), *range(1, k - m // 2 + 1))
xor = xor ^ int(input())
print("?", *range(n - m // 2 + 1, n + 1), *range(1, k - m // 2 + 1))
xor = xor ^ int(input())
print("!", xor)
elif n % k % 2 == 0:
ans = n // k + 2
for i in range(0, n - k, k):
print("?", *range(i + 1, i + k + 1))
xor = xor ^ int(input())
m = n % k
print("?", *range(n - m + 1, n - m // 2 + 1), *range(1, k - m // 2 + 1))
xor = xor ^ int(input())
print("?", *range(n - m // 2 + 1, n + 1), *range(1, k - m // 2 + 1))
xor = xor ^ int(input())
print("!", xor)
else:
print("?", *range(1, k + 1))
xor = xor ^ int(input())
print("?", *range(n - k + 1, n + 1))
xor = xor ^ int(input())
m = 2 * k - n
print("?", *range(1, n - k + m // 2 + 1), *range(n - m // 2 + 1, n + 1))
xor = xor ^ int(input())
print("?", *range(1, n - k + 1), *range(n - k + m // 2 + 1, k + 1), *range(n - m // 2 + 1, n + 1))
xor = xor ^ int(input())
print("!", xor)
``` | instruction | 0 | 82,833 | 12 | 165,666 |
No | output | 1 | 82,833 | 12 | 165,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
Note: the XOR-sum of an array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9) is defined as a_1 ⊕ a_2 ⊕ … ⊕ a_n, where ⊕ denotes the [bitwise XOR operation](https://en.wikipedia.org/wiki/Bitwise_operation#XOR).
Little Dormi received an array of n integers a_1, a_2, …, a_n for Christmas. However, while playing with it over the winter break, he accidentally dropped it into his XOR machine, and the array got lost.
The XOR machine is currently configured with a query size of k (which you cannot change), and allows you to perform the following type of query: by giving the machine k distinct indices x_1, x_2, …, x_k, it will output a_{x_1} ⊕ a_{x_2} ⊕ … ⊕ a_{x_k}.
As Little Dormi's older brother, you would like to help him recover the XOR-sum of his array a_1, a_2, …, a_n by querying the XOR machine.
Little Dormi isn't very patient, so to be as fast as possible, you must query the XOR machine the minimum number of times to find the XOR-sum of his array. Formally, let d be the minimum number of queries needed to find the XOR-sum of any array of length n with a query size of k. Your program will be accepted if you find the correct XOR-sum in at most d queries.
Lastly, you also noticed that with certain configurations of the machine k and values of n, it may not be possible to recover the XOR-sum of Little Dormi's lost array. If that is the case, you should report it as well.
The array a_1, a_2, …, a_n is fixed before you start querying the XOR machine and does not change with the queries.
Input
The only line of input contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n), the length of the lost array and the configured query size of the XOR machine.
Elements of the original array satisfy 1 ≤ a_i ≤ 10^9.
It can be proven that that if it is possible to recover the XOR sum under the given constraints, it can be done in at most 500 queries. That is, d ≤ 500.
After taking n and k, begin interaction.
Output
If it is impossible to recover the XOR-sum of the array, output -1 immediately after taking n and k. Do not begin interaction.
Otherwise, when your program finds the XOR-sum of the lost array a_1, a_2, …, a_n, report the answer in the following format: "! x", where x is the XOR sum of the array a_1, a_2, …, a_n, and terminate your program normally immediately after flushing the output stream.
Note that answering does not count as a query.
Interaction
Each query is made in the format "? b", where b is an array of exactly k distinct integers from 1 to n denoting the indices of the elements in the lost array that you want to query the XOR sum of.
You will then receive an integer x, the XOR sum of the queried elements. It can be proven that 0 ≤ x ≤ 2 ⋅ 10^9 will always be true.
After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If at any point you make an invalid query or try to make more than 500 queries (which is the hard limit), the interaction will terminate immediately and give you a Wrong Answer verdict. Note that if you exceed d queries, the interaction will continue normally unless you also exceed the 500 query hard limit, though you will still receive a Wrong Answer verdict either way.
Hacks
To hack a solution, use the following format.
The first line contains the integers n and k (1 ≤ n ≤ 500, 1 ≤ k ≤ n).
The second line contains the the array a_1, a_2, …, a_n (1 ≤ a_i ≤ 10^9).
Examples
Input
5 3
4
0
1
Output
? 1 2 3
? 2 3 5
? 4 1 5
! 7
Input
3 2
Output
-1
Note
In the first example interaction, the array a_1, a_2, …, a_n is 2, 1, 7, 5, 6 and its XOR-sum is 7.
The first query made asks for indices 1,2,3, so the response is a_1 ⊕ a_2 ⊕ a_3 = 2 ⊕ 1 ⊕ 7 = 4.
The second query made asks for indices 2,3,5, so the response is a_2 ⊕ a_3 ⊕ a_5 = 1 ⊕ 7 ⊕ 6 = 0.
The third query made asks for indices 4,1,5, so the response is a_4 ⊕ a_1 ⊕ a_5 = 5 ⊕ 2 ⊕ 6 = 1. Note that the indices may be output in any order.
Additionally, even though three queries were made in the example interaction, it is just meant to demonstrate the interaction format and does not necessarily represent an optimal strategy.
In the second example interaction, there is no way to recover the XOR-sum of Little Dormi's array no matter what is queried, so the program immediately outputs -1 and exits.
Submitted Solution:
```
#!/usr/bin/env python
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
def query(arr):
print('?', *arr, flush=True)
return int(input())
n, k = map(int, input().split())
rem = n % k
if rem % 2 == 1:
print(-1, flush=True)
return
sol = 0
for i in range(k, n + 1, k):
sol ^= query(range(i - k + 1, i + 1))
if rem:
sol ^= query([*range(1, k - (rem // 2) + 1), *range(n - rem + 1, n - (rem // 2) + 1)])
sol ^= query([*range(1, k - (rem // 2) + 1), *range(n - (rem // 2) + 1, n + 1)])
print('!', sol, flush=True)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
``` | instruction | 0 | 82,834 | 12 | 165,668 |
No | output | 1 | 82,834 | 12 | 165,669 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,942 | 12 | 165,884 |
Tags: brute force
Correct Solution:
```
from itertools import permutations
def f(l):
n = len(l)
res = 0
for i in range(n):
for j in range(i + 1, n + 1):
res += min(l[i:j])
return res
n, m = (int(x) for x in input().split())
res = 0
resl = []
for perm in permutations(range(1, n + 1)):
cur = f(perm)
# print(perm, cur)
if cur > res:
res = cur
resl = []
if cur == res:
resl.append(perm)
#print(res)
print(' '.join(str(x) for x in resl[m - 1]))
``` | output | 1 | 82,942 | 12 | 165,885 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,943 | 12 | 165,886 |
Tags: brute force
Correct Solution:
```
(n,m)=input().split()
(n,m)=(int(n),int(m)-1)
pow2=[]
u=1
for i in range(n):
pow2.append(u)
u*=2
r=[]
k=1
while k<n:
if m<pow2[n-k-1]:
r.append(k)
else:
m-=pow2[n-k-1]
k+=1
z=[]
for i in range(n):
if not (n-i in r):
z.append(n-i)
r+=z
r=[str(i) for i in r]
print(' '.join(r))
``` | output | 1 | 82,943 | 12 | 165,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,944 | 12 | 165,888 |
Tags: brute force
Correct Solution:
```
from itertools import permutations
n, m = [int(i) for i in input().split()]
maxsum = -1
ans = []
for per in permutations(range(1,n+1),n):
thissum = 0
for i in range(n):
for j in range(i,n):
thissum += min(per[i:j+1])
if thissum > maxsum:
maxsum = thissum
ans = [per]
elif thissum == maxsum:
ans.append(per)
print(' '.join([str(i) for i in ans[m-1]]))
``` | output | 1 | 82,944 | 12 | 165,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,945 | 12 | 165,890 |
Tags: brute force
Correct Solution:
```
#!/usr/bin/python3
def gen(n, start, t):
if n == 1:
return [start]
if t <= 2 ** (n - 2):
return [start] + gen(n - 1, start + 1, t)
else:
return gen(n - 1, start + 1, t - 2 ** (n - 2)) + [start]
n, t = map(int, input().split())
print(" ".join(map(str, gen(n, 1, t))))
``` | output | 1 | 82,945 | 12 | 165,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,946 | 12 | 165,892 |
Tags: brute force
Correct Solution:
```
n, m = [int(x) for x in input().split()]
best = 0
ans = []
def foo(p):
ans = 0
for i in range(n):
for j in range(i,n):
ans += min(p[i:j+1])
return ans
def eval(p):
global ans, best
val = foo(p)
if val > best:
ans = [p]
best = val
elif val == best:
ans.append(p)
def generate(l=[],remaining = list(range(1,n+1))):
if not remaining:
eval(l)
else:
for i, x in enumerate(remaining):
generate(l+[x],remaining[:i] + remaining[i+1:])
generate()
print(' '.join(str(x) for x in ans[m-1]))
``` | output | 1 | 82,946 | 12 | 165,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,947 | 12 | 165,894 |
Tags: brute force
Correct Solution:
```
import sys
f = sys.stdin
#f = open('H:\\Portable Python 3.2.5.1\\test_248B1.txt')
n, k = map(int, f.readline().strip().split())
import itertools
def sum_pr(p, n):
s = 0
#print(p)
for i in range(n):
for j in range(i,n):
s += min(p[i:j+1])
#print(i,j,p[i:j+1], min(p[i:j+1]))
return s
max_f = 0
l_pr = []
for pr in itertools.permutations( list(range(1, n+1)) ):
f = sum_pr(pr, n)
#print(pr, f, max_f)
if f>max_f:
max_f = f
l_pr = []
l_pr.append(pr)
elif f==max_f:
l_pr.append(pr)
def sortByL(p):
return sum([u*10**(10-i) for i, u in enumerate(p)])
l_pr.sort(key=sortByL)
r = [str(u) for u in l_pr[k-1]]
print(' '.join(r))
``` | output | 1 | 82,947 | 12 | 165,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,948 | 12 | 165,896 |
Tags: brute force
Correct Solution:
```
__author__ = 'yushchenko'
def countf(f):
sum = 0
for i in range(len(f)):
for j in range(len(f))[i:]:
# print(i, j)
# print(f[i:j + 1])
sum += min(f[i:j + 1])
return sum
import itertools
n,m = input().split()
n = int(n)
m = int(m)
if n == 1:
print(1)
exit()
maxcount = pow(2, n - 2)
t = 1
saved = []
result = []
for i in range (n):
# print(maxcount, m)
while m > maxcount:
m -= maxcount
if maxcount > 1:
maxcount /= 2
saved.append(t)
t += 1
else:
result.append(str(t))
if maxcount > 1:
maxcount /= 2
t += 1
if t > n: break
for x in reversed(saved):
result.append(str(x))
print(' '.join(result))
``` | output | 1 | 82,948 | 12 | 165,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order. | instruction | 0 | 82,949 | 12 | 165,898 |
Tags: brute force
Correct Solution:
```
n, m = map(int, input().split());
res = []
num = 0
x = n
for i in range(1, n):
if i not in res:
if pow(2, x - len(res) - 2) + num >= m:
res.append(i);
else:
num += pow(2, x - len(res) - 2);
x -= 1;
i = n;
while i > 0:
if i not in res:
res.append(i);
i -= 1;
for i in res:
print(i, end = " ");
print();
``` | output | 1 | 82,949 | 12 | 165,899 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
#!/usr/bin/env python3
import collections, itertools, fractions, functools, heapq, math, queue
def solve():
n, m = map(int, input().split())
found = []
maxf = 0
for p in itertools.permutations(list(range(1, n+1))):
p = list(p)
f = 0
for i in range(n):
M = p[i]
for j in range(i, n):
M = min(M, p[j])
f += M
if f > maxf:
maxf = f
found = [p]
elif f == maxf:
found.append(p)
found.sort()
return str.join(' ', map(str, found[m-1]))
if __name__ == '__main__':
print(solve())
``` | instruction | 0 | 82,950 | 12 | 165,900 |
Yes | output | 1 | 82,950 | 12 | 165,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
import math
n, m = tuple(int(x) for x in input().split())
perm = list(range(1,n+1))
changeSeq = [m]
while changeSeq[-1] > 1:
binLen = len(bin(changeSeq[-1])) - 2
power = 2**binLen if 2**(binLen - 1) != changeSeq[-1] else 2**(binLen - 1)
changeSeq.append(power - changeSeq[-1] + 1)
# print(changeSeq[-1])
for index in reversed(changeSeq):
power = int(math.ceil(math.log2(index))) + 1
perm[-power:] = reversed(perm[-power:])
print(" ".join(str(x) for x in perm))
``` | instruction | 0 | 82,951 | 12 | 165,902 |
Yes | output | 1 | 82,951 | 12 | 165,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
#file = open("", 'r')
#f = lambda:file.readline()
f= lambda: input()
n,m = map(int, f().split())
most = 0
p = []
for i in range(1, n+1):
p.append(i)
most += i * (n+1-i)
def next_perm():
i = len(p)-1
while i >0 and p[i-1] >= p[i]:
i-=1
if i <= 0:
return False
j = len(p)-1
while p[j]<= p[i-1]:
j-= 1
p[i-1],p[j] = p[j],p[i-1]
j = len(p)-1
while(i < j):
p[i],p[j] = p[j],p[i]
i += 1
j -= 1
return True
def fp():
s = 0
for i in range(1, n+1):
for j in range(i, n+1):
s += min(p[i-1:j])
return s
while(m > 0):
if (fp() == most):
m-= 1
if m == 0:
break
next_perm()
print(" ".join(str(e) for e in p))
``` | instruction | 0 | 82,952 | 12 | 165,904 |
Yes | output | 1 | 82,952 | 12 | 165,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
def rek(s,t):
global q,n
for x in range(t+1,n+1):
y=s[:n-x]+s[n-x:][::-1]
q.append(y)
rek(y,x)
n,m=map(int,input().split())
a=''.join(map(str,range(1,n+1)))
q=[a]
rek(a,1)
q.sort()
print(' '.join(q[m-1]))
``` | instruction | 0 | 82,953 | 12 | 165,906 |
Yes | output | 1 | 82,953 | 12 | 165,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
from itertools import permutations
n, m = 3, 2
base = list(range(1,n+1))
def foo():
count = 0
for perm in permutations(base):
if good(perm):
count += 1
if count == m:
return perm
def good(s):
for i in range(1,len(s)-1):
if abs(s[i]-s[i-1]) > 1 and abs(s[i] - s[i+1]) > 1:
return False
return True
print(' '.join(str(x) for x in foo()))
``` | instruction | 0 | 82,954 | 12 | 165,908 |
No | output | 1 | 82,954 | 12 | 165,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: kanari
# @Date: 2015-02-08 01:11:21
# @Last Modified by: kanari
# @Last Modified time: 2015-02-08 01:16:04
[n, m] = map(int, input().split())
a = [0 for i in range(0, n + 1)]
fac = [1]
for i in range(1, n + 1):
fac.append(fac[i - 1] * i)
def dfs(x, l, r, m):
if x > n:
return
elif m <= fac[n - x]:
a[l] = x
dfs(x + 1, l + 1, r, m)
else:
a[r] = x
dfs(x + 1, l, r - 1, m - fac[n - x])
dfs(1, 1, n, m)
for i in range(1, n + 1):
print(a[i], end = '')
if i == n:
print('\n', end = '')
else:
print(' ', end = '')
``` | instruction | 0 | 82,955 | 12 | 165,910 |
No | output | 1 | 82,955 | 12 | 165,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
sum1 = 0
def gen(used, pref, m):
global sum1
if len(pref) == n:
sum1 += 1
if sum1 == m:
print(' '.join(map(str, pref)))
exit()
else:
for i in range(1, n + 1):
if not used[i]:
used[i] = True
gen(used, pref + [i], m)
used[i] = False
n, m = map(int, input().split())
used = [False] * (n + 1)
gen(used, [], m)
``` | instruction | 0 | 82,956 | 12 | 165,912 |
No | output | 1 | 82,956 | 12 | 165,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a permutation p of numbers 1, 2, ..., n. Let's define f(p) as the following sum:
<image>
Find the lexicographically m-th permutation of length n in the set of permutations having the maximum possible value of f(p).
Input
The single line of input contains two integers n and m (1 ≤ m ≤ cntn), where cntn is the number of permutations of length n with maximum possible value of f(p).
The problem consists of two subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem B1 (3 points), the constraint 1 ≤ n ≤ 8 will hold.
* In subproblem B2 (4 points), the constraint 1 ≤ n ≤ 50 will hold.
Output
Output n number forming the required permutation.
Examples
Input
2 2
Output
2 1
Input
3 2
Output
1 3 2
Note
In the first example, both permutations of numbers {1, 2} yield maximum possible f(p) which is equal to 4. Among them, (2, 1) comes second in lexicographical order.
Submitted Solution:
```
(n,m)=input().split()
(n,m)=(int(n),int(m)-1)
u=[0 for i in range(n)]
for i in range(1,n+1):
u[-i]=m%(i)
m//=i
v=[i for i in range(1,n+1)]
for i in range(n):
v.sort()
t=v[u[i]]
u[i]=str(t)
v.remove(t)
print(' '.join(u))
``` | instruction | 0 | 82,957 | 12 | 165,914 |
No | output | 1 | 82,957 | 12 | 165,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!
Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.
Each query is processed in the following way:
1. Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment.
2. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down.
3. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value <image>, where <image> — operator of exclusive bitwise OR.
Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Input
The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array.
The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements.
The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries.
Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment.
Output
Print m non-negative integers — the answers for the queries in the order they appear in the input.
Examples
Input
3
3 7 8
1
1 3
Output
0
Input
7
1 2 1 3 3 2 3
5
4 7
4 5
1 3
1 7
1 5
Output
0
3
1
3
2
Note
In the second sample:
There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.
In the second query there is only integer 3 is presented even number of times — the answer is 3.
In the third query only integer 1 is written down — the answer is 1.
In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is <image>.
In the fifth query 1 and 3 are written down. The answer is <image>.
Submitted Solution:
```
from collections import defaultdict
def findXOR(l, r, arr):
wdict = defaultdict(int)
li = []
for i in range(l, r + 1):
wdict[arr[i]] += 1
for key, value in wdict.items():
if wdict[key] % 2 == 0:
li.append(wdict[key])
wdict.pop(key)
if len(li) == 0:
return
else:
result = li.pop()
while len(li) != 0:
result = result ^ li.pop()
return result
N = eval(input())
arr = list(map(eval, input().split()))
q = eval(input())
for i in range(q):
query = list(map(eval, input().split()))
print(findXOR(query[0] - 1, query[1] - 1, arr))
``` | instruction | 0 | 83,026 | 12 | 166,052 |
No | output | 1 | 83,026 | 12 | 166,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!
Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.
Each query is processed in the following way:
1. Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment.
2. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down.
3. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value <image>, where <image> — operator of exclusive bitwise OR.
Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Input
The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array.
The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements.
The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries.
Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment.
Output
Print m non-negative integers — the answers for the queries in the order they appear in the input.
Examples
Input
3
3 7 8
1
1 3
Output
0
Input
7
1 2 1 3 3 2 3
5
4 7
4 5
1 3
1 7
1 5
Output
0
3
1
3
2
Note
In the second sample:
There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.
In the second query there is only integer 3 is presented even number of times — the answer is 3.
In the third query only integer 1 is written down — the answer is 1.
In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is <image>.
In the fifth query 1 and 3 are written down. The answer is <image>.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
t=int(input())
while(t):
l,r=map(int,input().split())
f=[]
for i in range(l-1,r):
c=1
for j in range(l-1,r):
if(a[i]==a[j]):
c=c+1
f.append(c-1)
b=[]
for i in range(len(f)):
if(f[i]%2==0 and a[i] not in b):
b.append(a[i])
s=0
for i in range(len(b)):
s=s^b[i]
print(s)
t=t-1
``` | instruction | 0 | 83,027 | 12 | 166,054 |
No | output | 1 | 83,027 | 12 | 166,055 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!
Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.
Each query is processed in the following way:
1. Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment.
2. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down.
3. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value <image>, where <image> — operator of exclusive bitwise OR.
Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Input
The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array.
The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements.
The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries.
Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment.
Output
Print m non-negative integers — the answers for the queries in the order they appear in the input.
Examples
Input
3
3 7 8
1
1 3
Output
0
Input
7
1 2 1 3 3 2 3
5
4 7
4 5
1 3
1 7
1 5
Output
0
3
1
3
2
Note
In the second sample:
There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.
In the second query there is only integer 3 is presented even number of times — the answer is 3.
In the third query only integer 1 is written down — the answer is 1.
In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is <image>.
In the fifth query 1 and 3 are written down. The answer is <image>.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split(' ')))
b = [0] * n
b[0] = a[0]
for i in range(1, n):
b[i] = b[i - 1] ^ a[i]
class Ques(object):
def __init__(self, i, l, r):
self.i = i
self.l = l
self.r = r
q = int(input())
ans = [0] * q
ql = []
for i in range(q):
l, r = map(int, input().split(' '))
ans[i] ^= b[r - 1]
if l > 1:
ans[i] ^= b[l - 2]
ql.append(Ques(i, l - 1, r))
def f(l, r, q):
if not q:
return
k = 0
for i in set(a[l:r]):
k ^= i
for i in range(len(q) - 1, -1, -1):
if q[i].l <= l and r <= q[i].r:
ans[q[i].i] ^= k
q.pop(i)
if r - l <= 1:
return
m = (l + r) >> 1
f(l, m, [i for i in q if i.l < m])
f(m, r, [i for i in q if m < i.r])
f(0, n, ql)
for i in ans:
print(i)
``` | instruction | 0 | 83,028 | 12 | 166,056 |
No | output | 1 | 83,028 | 12 | 166,057 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Mishka enjoys programming. Since her birthday has just passed, her friends decided to present her with array of non-negative integers a1, a2, ..., an of n elements!
Mishka loved the array and she instantly decided to determine its beauty value, but she is too little and can't process large arrays. Right because of that she invited you to visit her and asked you to process m queries.
Each query is processed in the following way:
1. Two integers l and r (1 ≤ l ≤ r ≤ n) are specified — bounds of query segment.
2. Integers, presented in array segment [l, r] (in sequence of integers al, al + 1, ..., ar) even number of times, are written down.
3. XOR-sum of written down integers is calculated, and this value is the answer for a query. Formally, if integers written down in point 2 are x1, x2, ..., xk, then Mishka wants to know the value <image>, where <image> — operator of exclusive bitwise OR.
Since only the little bears know the definition of array beauty, all you are to do is to answer each of queries presented.
Input
The first line of the input contains single integer n (1 ≤ n ≤ 1 000 000) — the number of elements in the array.
The second line of the input contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109) — array elements.
The third line of the input contains single integer m (1 ≤ m ≤ 1 000 000) — the number of queries.
Each of the next m lines describes corresponding query by a pair of integers l and r (1 ≤ l ≤ r ≤ n) — the bounds of query segment.
Output
Print m non-negative integers — the answers for the queries in the order they appear in the input.
Examples
Input
3
3 7 8
1
1 3
Output
0
Input
7
1 2 1 3 3 2 3
5
4 7
4 5
1 3
1 7
1 5
Output
0
3
1
3
2
Note
In the second sample:
There is no integers in the segment of the first query, presented even number of times in the segment — the answer is 0.
In the second query there is only integer 3 is presented even number of times — the answer is 3.
In the third query only integer 1 is written down — the answer is 1.
In the fourth query all array elements are considered. Only 1 and 2 are presented there even number of times. The answer is <image>.
In the fifth query 1 and 3 are written down. The answer is <image>.
Submitted Solution:
```
from itertools import accumulate
n = int(input())
a = list(map(int, input().split(' ')))
o, s = [0] * n, set()
for i in range(n):
if a[i] in s:
o[i] = a[i]
else:
s.add(a[i])
o = list(accumulate(o, lambda x, y: x ^ y))
a.insert(0, 0)
o.insert(0, 0)
q = int(input())
qs = (map(int, input().split(' ')) for _ in range(q))
qs = sorted(zip(*zip(*qs), range(q)))
ans = [0] * q
i, m = 0, 0
for l, r, j in qs:
if i < l - 1:
i += 1
m ^= a[i]
ans[j] = o[r] ^ m
print('\n'.join(map(str, ans)))
``` | instruction | 0 | 83,029 | 12 | 166,058 |
No | output | 1 | 83,029 | 12 | 166,059 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array.
Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.
Output
Output single integer — number of right permutations modulo 109 + 7.
Examples
Input
3
1 2 4
Output
2
Input
7
5 2 4 2 4 1 1
Output
144
Note
For first example:
[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.
[1, 4, 2] — wrong permutation, because 4 is square of 2.
[2, 1, 4] — wrong permutation, because 4 is square of 2.
[2, 4, 1] — wrong permutation, because 4 is square of 2.
[4, 1, 2] — wrong permutation, because 4 is square of 2.
[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.
Submitted Solution:
```
from math import sqrt
from copy import deepcopy
primes = []
def isPrime(n):
s = sqrt(n)
for nn in primes:
if nn > s:
return True
if n % nn == 0:
return False
return True
for i in range(1000):
i += 2
if isPrime(i):
primes.append(i)
# sPrimes = set(map(lambda x: x**2, primes))
# sPrimes.add(1)
# print(sPrimes)
sPrimes = set(map(lambda x: (x+1)**2, range(1000)))
def decompose(n):
out = []
for i in primes:
if n % i == 0:
out.append(i)
n //= i
if n == 1:
break
else:
return out + decompose(n)
return out
def getNum(n):
n = int(n)
ns = decompose(n)
d = {}
for i in ns:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
out = set()
outt = set()
for k in d.keys():
if d[k] % 2 == 0:
out.add(k)
else:
outt.add(k)
return (out, outt, ns, n) # (2, 1, [], n)
input()
ns = list(map(int, input().split()))
print(list(map(getNum, ns)))
def compatible(a, b):
_, _, _, na = a
_, _, _, nb = b
if na*nb in sPrimes:
return False
else:
return True
# if len(a) == 0 and len(b) == 0:
# return True
# else:
# for ai in a:
# if not ai in b_:
# return False
# for ai_ in a_:
# if not ai_ in b_:
# return True
# for bi_ in b_:
# if not bi_ in a_:
# return True
# for bi in b:
# if not bi in a_:
# return False
# return True
def test(soFar, toDo):
out = 0
if len(soFar) == 0 and len(toDo) == 0:
return 1
elif len(toDo) == 0:
out += 1
else:
for k, i in enumerate(toDo):
if len(soFar) == 0 or not soFar[-1] * i in sPrimes:
foo = test(soFar + [i], toDo[:k] + toDo[k+1:])
out += foo
return out
print(test([], ns))
``` | instruction | 0 | 83,083 | 12 | 166,166 |
No | output | 1 | 83,083 | 12 | 166,167 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array.
Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.
Output
Output single integer — number of right permutations modulo 109 + 7.
Examples
Input
3
1 2 4
Output
2
Input
7
5 2 4 2 4 1 1
Output
144
Note
For first example:
[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.
[1, 4, 2] — wrong permutation, because 4 is square of 2.
[2, 1, 4] — wrong permutation, because 4 is square of 2.
[2, 4, 1] — wrong permutation, because 4 is square of 2.
[4, 1, 2] — wrong permutation, because 4 is square of 2.
[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().split()))
def rec(array):
result = []
if len(array) > 1:
for i in range(len(array)):
arr = rec(array[:i:] + array[i + 1::])
for j in arr:
x = []
x.append(array[i])
x.extend(j)
result.append(x)
return result
else:
return [array]
array = rec(arr)
ready_arr = []
for i in array:
if i not in ready_arr:
ready_arr.append(i)
print(ready_arr)
counter = len(ready_arr)
print(counter)
for i in ready_arr:
for j in range(n - 1):
print((i[j] * i[j + 1]))
if ((i[j] * i[j + 1]) ** 0.5) % 1 == 0:
counter -= 1
break
print(counter)
``` | instruction | 0 | 83,084 | 12 | 166,168 |
No | output | 1 | 83,084 | 12 | 166,169 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array.
Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.
Output
Output single integer — number of right permutations modulo 109 + 7.
Examples
Input
3
1 2 4
Output
2
Input
7
5 2 4 2 4 1 1
Output
144
Note
For first example:
[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.
[1, 4, 2] — wrong permutation, because 4 is square of 2.
[2, 1, 4] — wrong permutation, because 4 is square of 2.
[2, 4, 1] — wrong permutation, because 4 is square of 2.
[4, 1, 2] — wrong permutation, because 4 is square of 2.
[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.
Submitted Solution:
```
import sys
import math
fin = sys.stdin
# fin = open('a.in', 'r')
n = int(fin.readline())
array = list(map(int, fin.readline().split(' ')))
shuffles_count = math.factorial(n)
some = 0
def is_square(apositiveint):
if apositiveint == 1:
return True
x = apositiveint // 2
seen = set([x])
while x * x != apositiveint:
x = (x + (apositiveint // x)) // 2
if x in seen:
return False
seen.add(x)
return True
for i in range(n):
this_num = array[i]
for j in range(i + 1, n):
_this_numm = array[j]
if is_square(this_num * _this_numm):
some += 2
some = some * (n - 1)
# print(shuffles_count - some)
print((shuffles_count - some) % (10**9 + 7))
``` | instruction | 0 | 83,085 | 12 | 166,170 |
No | output | 1 | 83,085 | 12 | 166,171 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A year ago on the bench in public park Leha found an array of n numbers. Leha believes that permutation p is right if for all 1 ≤ i < n condition, that api·api + 1 is not perfect square, holds. Leha wants to find number of right permutations modulo 109 + 7.
Input
First line of input data contains single integer n (1 ≤ n ≤ 300) — length of the array.
Next line contains n integers a1, a2, ... , an (1 ≤ ai ≤ 109) — found array.
Output
Output single integer — number of right permutations modulo 109 + 7.
Examples
Input
3
1 2 4
Output
2
Input
7
5 2 4 2 4 1 1
Output
144
Note
For first example:
[1, 2, 4] — right permutation, because 2 and 8 are not perfect squares.
[1, 4, 2] — wrong permutation, because 4 is square of 2.
[2, 1, 4] — wrong permutation, because 4 is square of 2.
[2, 4, 1] — wrong permutation, because 4 is square of 2.
[4, 1, 2] — wrong permutation, because 4 is square of 2.
[4, 2, 1] — right permutation, because 8 and 2 are not perfect squares.
Submitted Solution:
```
n = int(input())
arr = list(map(int, input().split()))
def rec(array):
result = []
if len(array) > 1:
for i in range(len(array)):
arr = rec(array[:i:] + array[i + 1::])
for j in arr:
x = []
x.append(array[i])
x.extend(j)
result.append(x)
return result
else:
return [array]
array = rec(arr)
ready_arr = []
for i in array:
if i not in ready_arr:
ready_arr.append(i)
counter = len(ready_arr)
for i in ready_arr:
for j in range(n - 1):
if ((i[j] * i[j + 1]) ** 0.5) % 1 == 0:
counter -= 1
break
print(counter)
``` | instruction | 0 | 83,086 | 12 | 166,172 |
No | output | 1 | 83,086 | 12 | 166,173 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,396 | 12 | 166,792 |
Tags: dp, math, probabilities
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
if n==1:
return 0
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):#排他的論理和の階乗
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=None):
self.BIT=[0]*(n+1)
self.num=n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
mod = self.mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class Matrix():
mod=10**9+7
def set_mod(m):
Matrix.mod=m
def __init__(self,L):
self.row=len(L)
self.column=len(L[0])
self._matrix=L
for i in range(self.row):
for j in range(self.column):
self._matrix[i][j]%=Matrix.mod
def __getitem__(self,item):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
return self._matrix[i][j]
def __setitem__(self,item,val):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
self._matrix[i][j]=val
def __add__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]+other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __sub__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]-other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __mul__(self,other):
if type(other)!=int:
if self.column!=other.row:
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(other.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(other.column):
temp=0
for k in range(self.column):
temp+=self._matrix[i][k]*other._matrix[k][j]
res[i][j]=temp%Matrix.mod
return Matrix(res)
else:
n=other
res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
return Matrix(res)
def __pow__(self,m):
if self.column!=self.row:
raise MatrixPowError("the size of row must be the same as that of column")
n=self.row
res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
while m:
if m%2==1:
res=res*self
self=self*self
m//=2
return res
def __str__(self):
res=[]
for i in range(self.row):
for j in range(self.column):
res.append(str(self._matrix[i][j]))
res.append(" ")
res.append("\n")
res=res[:len(res)-1]
return "".join(res)
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
def cmb(n, r, mod):
if ( r<0 or r>n ):
return 0
r = min(r, n-r)
return (g1[n] * g2[r] % mod) * g2[n-r] % mod
mod = 998244353
N = 2*10**5
g1 = [1]*(N+1)
g2 = [1]*(N+1)
inverse = [1]*(N+1)
for i in range( 2, N + 1 ):
g1[i]=( ( g1[i-1] * i ) % mod )
inverse[i]=( ( -inverse[mod % i] * (mod//i) ) % mod )
g2[i]=( (g2[i-1] * inverse[i]) % mod )
inverse[0]=0
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.readline().rstrip()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n = int(input())
p = li()
val = set([p[i] for i in range(n)])
fw = BIT(n)
cnt = 0
for i in range(1,n+1):
if i not in val:
fw.update(i,1)
cnt += 1
res = 0
tmp = 0
for i in range(n):
if p[i]!=-1:
tmp += fw.query(p[i])
else:
res += tmp * inverse[cnt]
res %= mod
tmp = 0
for i in range(n-1,-1,-1):
if p[i]!=-1:
tmp += cnt - fw.query(p[i])
else:
res += tmp * inverse[cnt]
res %= mod
res += cnt*(cnt-1) * inverse[4]
res %= mod
fw = BIT(n)
cnt = 0
for i in range(n):
if p[i]!=-1:
res += cnt - fw.query(p[i])
cnt += 1
fw.update(p[i],1)
print(res%mod)
``` | output | 1 | 83,396 | 12 | 166,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,397 | 12 | 166,794 |
Tags: dp, math, probabilities
Correct Solution:
```
import sys
from array import array # noqa: F401
import typing as Tp # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
T = Tp.TypeVar('T')
class FenwickSum(Tp.Generic[T]):
__slots__ = ['nodes', 'size', 'unit']
def __init__(self, size: int, default: T, unit: T):
self.nodes = [default] * (size + 1)
self.size = size + 1
self.unit = unit
def add(self, index: int, value: T):
while index < self.size:
self.nodes[index] += value
index += index & -index
def sum(self, right: int) -> T:
result = self.unit
while right:
result += self.nodes[right]
right -= right & -right
return result
def main():
n = int(input())
a = list(map(int, input().split()))
b = [x for x in a if x != -1]
mod = 998244353
minus = n - len(b)
m_inv = pow(minus, mod - 2, mod)
ans = 0
bit = FenwickSum[int](n, 0, 0)
for x in reversed(b):
ans += bit.sum(x)
bit.add(x, 1)
ans += minus * (minus - 1) * pow(4, mod - 2, mod) % mod
acc_u, m = [0] * (n + 1), minus
for x in a:
if x == -1:
m -= 1
else:
acc_u[x] = m
for i in range(n - 1, 0, -1):
acc_u[i] += acc_u[i + 1]
if acc_u[i] >= mod:
acc_u[i] -= mod
acc_d, m = [0] * (n + 1), minus
for x in reversed(a):
if x == -1:
m -= 1
else:
acc_d[x] = m
for i in range(1, n + 1):
acc_d[i] += acc_d[i - 1]
if acc_d[i] >= mod:
acc_d[i] -= mod
for x in set(range(1, n + 1)) - set(b):
ans = (ans + (acc_u[x] + acc_d[x]) * m_inv) % mod
print(ans % mod)
if __name__ == '__main__':
main()
``` | output | 1 | 83,397 | 12 | 166,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,398 | 12 | 166,796 |
Tags: dp, math, probabilities
Correct Solution:
```
base=998244353;
def power(x, y):
if(y==0):
return 1
t=power(x, y//2)
t=(t*t)%base
if(y%2):
t=(t*x)%base
return t;
def inverse(x):
return power(x, base-2)
ft=[0]
for i in range(0, 200000):
ft.append(0)
def get(i):
res=0
while(i<=200000):
res+=ft[i]
i+=i&-i
return res
def update(i, x):
while(i):
ft[i]+=x
i-=i&-i
n=int(input())
a=[0]
a+=list(map(int, input().split()))
neg=[0]
non=[0]
for i in range(1, n+1):
non.append(0)
for i in range(1, n+1):
if(a[i]!=-1):
non[a[i]]+=1
for i in range(1, n+1):
non[i]+=non[i-1]
for i in range(1, n+1):
if(a[i]==-1):
neg.append(neg[i-1]+1)
else:
neg.append(neg[i-1])
m=neg[n]
ans=0
for i in range(1, n+1):
if(a[i]!=-1):
ans+=get(a[i])
update(a[i], 1)
fm=1
fs=fm
for i in range(1, m+1):
fs=fm
fm=(fm*i)%base
fs=(fs*inverse(fm))%base
for i in range(1, n+1):
if(a[i]!=-1):
less=a[i]-non[a[i]]
more=m-less
ans=(ans+neg[i]*more*fs)%base
ans=(ans+(m-neg[i])*less*fs)%base
ans=(ans+m*(m-1)*inverse(4))%base
print(ans)
``` | output | 1 | 83,398 | 12 | 166,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,399 | 12 | 166,798 |
Tags: dp, math, probabilities
Correct Solution:
```
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0]*(n+1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i+1] = T[i]
else:
T[i+1] = T[i]+1
def I(J):
if len(J) <= 1:
return J, 0
else:
a = J[:len(J)//2]
b = J[len(J)//2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += (len(a)-i)
c += a[i:]
c += b[j:]
return c, inversions
for i in range(1,n+1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
themostimportantsum = 0
for i in J:
low = 0
high = total-1
while high-low > 1:
guess = (high+low)//2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high+1
#D[i] is the position of i in the list
#T[D[i]] is how many -1s there are to the left of it
themostimportantsum += T[D[i]]*(total-smaller)+(total-T[D[i]])*(smaller)
num = themostimportantsum+total
denom = total
num =(denom*(((total)*(total-1))//2)+2*num)%998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1]%998244353)
else:
num += denom*I(J)[1]
print(((num-denom)*pow(denom%998244353,998244351,998244353))%998244353)
``` | output | 1 | 83,399 | 12 | 166,799 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,400 | 12 | 166,800 |
Tags: dp, math, probabilities
Correct Solution:
```
def merge(a,b):
inda=0
indb=0
lena=len(a)
lenb=len(b)
d=[a[-1]+b[-1]+1000]
a+=d
b+=d
c=[]
inversions=0
for i in range(lena+lenb):
if a[inda]<b[indb]:
c.append(a[inda])
inda+=1
else:
c.append(b[indb])
indb+=1
inversions+=lena-inda
return((c,inversions))
def mergesort(a):
if len(a)<=1:
return((a,0))
split=len(a)//2
b=a[:split]
c=a[split:]
d=mergesort(b)
e=mergesort(c)
f=merge(d[0],e[0])
return((f[0],f[1]+d[1]+e[1]))
n=int(input())
a=list(map(int,input().split()))
b=[]
for guy in a:
if guy!=-1:
b.append(guy)
invs=mergesort(b)[1]
negs=len(a)-len(b)
pairs=(negs*(negs-1))//2
used=[0]*n
for guy in a:
if guy!=-1:
used[guy-1]+=1
unused=[0]
for i in range(n-1):
unused.append(unused[-1]+1-used[i])
negsseen=0
mix=0
for i in range(n):
if a[i]==-1:
negsseen+=1
else:
mix+=unused[a[i]-1]*(negs-negsseen)+negsseen*(negs-unused[a[i]-1])
num=invs*2*negs+pairs*negs+mix*2
denom=2*negs
if negs==0:
print(invs%998244353)
else:
for i in range(denom):
if (998244353*i+1)%denom==0:
inv=(998244353*i+1)//denom
break
print((num*inv)%998244353)
``` | output | 1 | 83,400 | 12 | 166,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,401 | 12 | 166,802 |
Tags: dp, math, probabilities
Correct Solution:
```
K = 998244353
def mu(a, n):
if n == 0: return 1
q = mu(a, n // 2)
if n % 2 == 0: return q * q % K
return q * q % K * a % K
MAXN = 200005
dd = [0 for i in range(MAXN)]
p = [0 for i in range(MAXN)]
s = [0 for i in range(MAXN)]
a = [0 for i in range(MAXN)]
fen = [0 for i in range(MAXN)]
def add(u, v):
i = u
while (i <= 200000):
fen[i] += v
i += i & -i
def get(u):
res = 0
i = u
while (i > 0):
res += fen[i]
i -= i & -i
return res
n = int(input())
data = input().split()
cnt = 0
for i in range(1, n + 1):
p[i] = int(data[i - 1])
if (p[i] > 0): dd[p[i]] = 1
else: cnt += 1
for i in range(1, n + 1):
if (dd[i] == 0):
s[i] = s[i - 1] + 1
else:
s[i] = s[i - 1]
cnt1 = 0
P = 0
den = mu(cnt, K - 2)
for i in range(1, n + 1):
if (p[i] == -1):
cnt1 += 1
else:
u = cnt - cnt1
P = (P + u * s[p[i]] % K * den % K) % K
P = (P + cnt1 * (cnt - s[p[i]]) % K * den % K) % K
P = (P + cnt * (cnt - 1) * mu(4, K - 2)) % K
m = 0
for i in range(1, n + 1):
if p[i] > 0:
m += 1
a[m] = p[i]
P1 = 0
for i in range(m, 0, -1):
P1 = (P1 + get(a[i])) % K
add(a[i], 1)
P = (P + P1) % K
print(P)
``` | output | 1 | 83,401 | 12 | 166,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,402 | 12 | 166,804 |
Tags: dp, math, probabilities
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
P=list(map(int,input().split()))
mod=998244353
INV=[None]*(n+1)#1/aのリストを予め作っておく.
for i in range(1,n+1):
INV[i]=pow(i,mod-2,mod)
BLA=P.count(-1)
if BLA==0 or BLA==1:
ANS=0
else:
LEFT=BLA*(BLA-1)//2*INV[BLA]%mod#左側の個数の平均
AVEP=BLA*(BLA-1)//2*pow(BLA-1,mod-2,mod)#左側にあるものが自分より大きい確率の和
ANS=LEFT*AVEP%mod
#print(ANS,LEFT,AVEP)
y=1
for i in range(BLA):
y=y*(BLA-i)%mod
KOSUU=pow(y,mod-2,mod)
BLALIST=[1]*(n+1)
NONBLA=[]
BLANUM=[0]*n
for i in range(n):
if P[i]!=-1:
BLALIST[P[i]]=0
BLANUM[i]=BLANUM[i-1]
NONBLA.append(P[i])
else:
BLANUM[i]=BLANUM[i-1]+1
#print(BLALIST)
BLALIST[0]=0
for i in range(1,n+1):
BLALIST[i]=BLALIST[i-1]+BLALIST[i]
if BLA!=0:
for i in range(n):
if P[i]!=-1:
ANS=(ANS+(BLANUM[i]*(BLA-BLALIST[P[i]])+(BLA-BLANUM[i])*BLALIST[P[i]])*INV[BLA])%mod
#print(ANS)
A=NONBLA
if A==[]:
print(ANS)
sys.exit()
n=len(A)
MAXA=max(A)
MINA=min(A)
BIT=[0]*(MAXA-MINA+2)#出現回数をbit indexed treeの形でもっておく.
for i in range(n):#A[0],A[1],...とBITを更新
bitobje=A[i]-MINA+1
x=bitobje
while x!=0:
ANS=(ANS-BIT[x])%mod
x-=(x&(-x))
#print(ANS)
x2=MAXA-MINA+1
#print(x2)
while x2!=0:
#print(x2,BIT)
ANS=(ANS+BIT[x2])%mod
x2-=(x2&(-x2))
#print(ANS)
y=bitobje
while y<=MAXA-MINA+1:
BIT[y]+=1
y+=(y&(-y))
#print(ANS,BIT)
print(ANS)
``` | output | 1 | 83,402 | 12 | 166,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion. | instruction | 0 | 83,403 | 12 | 166,806 |
Tags: dp, math, probabilities
Correct Solution:
```
MOD = 998244353
def power(x, n) :
ans = 1
while (n) :
if ((n & 1) == 1) :
ans = ans * x % MOD
x = x * x % MOD
n = n // 2
return ans
n = int(input())
a = list(map(int, input().split()))
b = [0 for i in range(n + 1)]
def add(x, v) :
while (x <= n) :
b[x] = b[x] + v
x = x + (x & -x)
def get(x) :
ans = 0
while (x) :
ans = ans + b[x]
x = x - (x & -x)
return ans
anss = 0
for i in range(n) :
if (a[i] != -1) :
add(a[i], 1)
anss = anss + get(n) - get(a[i])
anss = anss % MOD
total = 0
sur = [0] + [1 for i in range(n)]
for i in range(n) :
if (a[i] == -1) :
total = total + 1
else :
sur[a[i]] = 0
if (total == 0) :
print(anss)
exit(0)
for i in range(1, n + 1) :
sur[i] = sur[i] + sur[i - 1]
dead = 0
ansa = 0
for i in range(n) :
if (a[i] != -1) :
ansa = ansa + sur[a[i]] * (total - dead) + (sur[n] - sur[a[i]]) * dead
else :
dead = dead + 1
ans = (ansa * 4 + anss * 4 * total + total * total * (total - 1)) % MOD
ans = (ans * power(4 * total, MOD - 2)) % MOD
print(ans)
``` | output | 1 | 83,403 | 12 | 166,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion.
Submitted Solution:
```
def merge(a,b):
inda=0
indb=0
lena=len(a)
lenb=len(b)
d=[a[-1]+b[-1]+1000]
a+=d
b+=d
c=[]
inversions=0
for i in range(lena+lenb):
if a[inda]<b[indb]:
c.append(a[inda])
inda+=1
else:
c.append(b[indb])
indb+=1
inversions+=lena-inda
return((c,inversions))
def mergesort(a):
if len(a)<=1:
return((a,0))
split=len(a)//2
b=a[:split]
c=a[split:]
d=mergesort(b)
e=mergesort(c)
f=merge(d[0],e[0])
return((f[0],f[1]+d[1]+e[1]))
n=int(input())
a=list(map(int,input().split()))
b=[]
for guy in a:
if guy!=-1:
b.append(guy)
invs=mergesort(b)[1]
negs=len(a)-len(b)
pairs=(negs*(negs-1))//2
used=[0]*n
for guy in a:
if guy!=-1:
used[guy-1]+=1
unused=[0]
for i in range(n-1):
unused.append(unused[-1]+1-used[i])
negsseen=0
mix=0
for i in range(n):
if a[i]==-1:
negsseen+=1
else:
mix+=unused[a[i]-1]*(negs-negsseen)+negsseen*(negs-unused[a[i]-1])
num=invs*2*negs+pairs*negs+mix*2
denom=2*negs
if negs==0:
print(invs)
else:
for i in range(denom):
if (998244353*i+1)%denom==0:
inv=(998244353*i+1)//denom
break
print((num*inv)%998244353)
``` | instruction | 0 | 83,404 | 12 | 166,808 |
No | output | 1 | 83,404 | 12 | 166,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
mod = 998244353
n = inp()
a = inpl()
fac = [1,1]
for i in range(2,n):
fac.append((fac[-1]*i)%mod)
k = a.count(-1)
b = []; d = {}
for i,x in enumerate(a):
if x == -1: continue
b.append(x); d[x] = i
sorb = sorted(b)
res = 0
for i,x in enumerate(sorb):
mi = x-i-1; r = n-1-d[x]
res += mi*r
res *= fac[-2]
res %= mod
cnt = (fac[-1]*k*(k-1))%mod
cnt *= pow(4,mod-2,mod)
res += cnt
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
# assert i > 0
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j=None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i)
# n = 6
# a = [1,2,3,4,5,6]
# bit = BIT(n)
# for i,e in enumerate(a):
# bit.add(i+1,e)
# print(bit.get(2,5)) #12 (3+4+5)
N = n-k
bit = BIT(N+10)
ans = 0
for i,x in enumerate(b):
# bit.add(p, 1)
ans += i - bit.sum(x+1)
bit.add(x+1,1)
res += ans
res %= mod
print(res*pow(fac[-1],mod-2,mod)%mod)
``` | instruction | 0 | 83,405 | 12 | 166,810 |
No | output | 1 | 83,405 | 12 | 166,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion.
Submitted Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
mod = 998244353
n = inp()
a = inpl()
k = a.count(-1)
fac = [1,1]
for i in range(2,k+1):
fac.append((fac[-1]*i)%mod)
b = []; d = {}; rev = [0]*n
for i,x in enumerate(a):
if x == -1: rev[i] = 1
else:
b.append(x); d[x] = i
rev = list(itertools.accumulate(rev))
sorb = sorted(b)
res = 0
for i,x in enumerate(sorb):
mi = x-i-1; r = k-rev[d[x]]
res += mi*r
res %= mod
res *= fac[-2]
res %= mod
cnt = (fac[-1]*k*(k-1))%mod
cnt *= pow(4,mod-2,mod)
res += cnt
class BIT:
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
self.el = [0]*(n+1)
def sum(self, i):
s = 0
while i > 0:
s += self.data[i]
i -= i & -i
return s
def add(self, i, x):
# assert i > 0
self.el[i] += x
while i <= self.n:
self.data[i] += x
i += i & -i
def get(self, i, j=None):
if j is None:
return self.el[i]
return self.sum(j) - self.sum(i)
# n = 6
# a = [1,2,3,4,5,6]
# bit = BIT(n)
# for i,e in enumerate(a):
# bit.add(i+1,e)
# print(bit.get(2,5)) #12 (3+4+5)
N = n-k
bit = BIT(N+10)
ans = 0
for i,x in enumerate(b):
# bit.add(p, 1)
ans += i - bit.sum(x+1)
bit.add(x+1,1)
res += ans
res %= mod
print(res*pow(fac[-1],mod-2,mod)%mod)
``` | instruction | 0 | 83,406 | 12 | 166,812 |
No | output | 1 | 83,406 | 12 | 166,813 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and a_i < a_j. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation p of size n. However, the numbers on some positions are replaced by -1. Let the valid permutation be such a replacement of -1 in this sequence back to numbers from 1 to n in such a way that the resulting sequence is a permutation of size n.
The given sequence was turned into a valid permutation randomly with the equal probability of getting each valid permutation.
Calculate the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Input
The first line contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of the sequence.
The second line contains n integers p_1, p_2, ..., p_n (-1 ≤ p_i ≤ n, p_i ≠ 0) — the initial sequence.
It is guaranteed that all elements not equal to -1 are pairwise distinct.
Output
Print a single integer — the expected total number of inversions in the resulting valid permutation.
It can be shown that it is in the form of P/Q where P and Q are non-negative integers and Q ≠ 0. Report the value of P ⋅ Q^{-1} \pmod {998244353}.
Examples
Input
3
3 -1 -1
Output
499122179
Input
2
1 2
Output
0
Input
2
-1 -1
Output
499122177
Note
In the first example two resulting valid permutations are possible:
* [3, 1, 2] — 2 inversions;
* [3, 2, 1] — 3 inversions.
The expected value is (2 ⋅ 1 + 3 ⋅ 1)/(2) = 2.5.
In the second example no -1 are present, thus the only valid permutation is possible — the given one. It has 0 inversions.
In the third example there are two resulting valid permutations — one with 0 inversions and one with 1 inversion.
Submitted Solution:
```
n = int(input())
L = [int(x) for x in input().split()]
D = {}
J = []
S = []
T = [0]*(n+1)
for i in range(n):
if L[i] > 0:
D[L[i]] = i
J.append(L[i])
T[i+1] = T[i]
else:
T[i+1] = T[i]+1
def I(J):
if len(J) <= 1:
return J, 0
else:
a = J[:len(J)//2]
b = J[len(J)//2:]
a, ai = I(a)
b, bi = I(b)
c = []
i = 0
j = 0
inversions = ai + bi
while i < len(a) and j < len(b):
if a[i] <= b[j]:
c.append(a[i])
i += 1
else:
c.append(b[j])
j += 1
inversions += (len(a)-i)
c += a[i:]
c += b[j:]
return c, inversions
for i in range(1,n+1):
if not i in D:
S.append(i)
total = len(S)
num = 1
denom = 1
if total > 0:
for i in J:
low = 0
high = total-1
while high-low > 1:
guess = (high+low)//2
if S[guess] > i:
high = guess
else:
low = guess
if S[low] > i:
smaller = low
elif S[high] > i:
smaller = high
else:
smaller = high+1
#D[i] is the position of i in the list
#T[D[i]] is how many -1s there are to the left of it
if T[D[i]] != 0 and T[D[i]] != total:
tempn = (total-smaller)*T[D[i]]+(smaller)*(total-T[D[i]])
tempd = T[D[i]]*(total-T[D[i]])
num = (num*tempd+tempn*denom)%998244353
denom *= tempd
denom = denom%998244353
elif T[D[i]] == 0:
tempn = (smaller)*(total-T[D[i]])
tempd = (total-T[D[i]])
num = (num*tempd+tempn*denom)%998244353
denom *= tempd
denom = denom%998244353
elif T[D[i]] == total:
tempn = (total-smaller)*T[D[i]]+(smaller)*(total-T[D[i]])
tempd = T[D[i]]
num = (num*tempd+tempn*denom)%998244353
denom *= tempd
denom = denom%998244353
num =(denom*(((total)*(total-1))//2)+2*num)%998244353
denom *= 2
if num == denom:
if I(J)[1] == 0:
print(0)
else:
print(I(J)[1]%998244353)
else:
num += denom*I(J)[1]
print(((num-denom)*pow(denom%998244353,998244351,998244353))%998244353)
``` | instruction | 0 | 83,407 | 12 | 166,814 |
No | output | 1 | 83,407 | 12 | 166,815 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.