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 |
|---|---|---|---|---|---|
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_1, p_2, …, p_n.
Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.
For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A.
For each i from 1 to n:
* Add p_i to A.
* If the i-th position contains a bomb, remove the largest element in A.
After the process is completed, A will be non-empty. The cost of the configuration of bombs equals the largest element in A.
You are given another permutation, q_1, q_2, …, q_n.
For each 1 ≤ i ≤ n, find the cost of a configuration of bombs such that there exists a bomb in positions q_1, q_2, …, q_{i-1}.
For example, for i=1, you need to find the cost of a configuration without bombs, and for i=n, you need to find the cost of a configuration with bombs in positions q_1, q_2, …, q_{n-1}.
Input
The first line contains a single integer, n (2 ≤ n ≤ 300 000).
The second line contains n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n).
The third line contains n distinct integers q_1, q_2, …, q_n (1 ≤ q_i ≤ n).
Output
Print n space-separated integers, such that the i-th of them equals the cost of a configuration of bombs in positions q_1, q_2, …, q_{i-1}.
Examples
Input
3
3 2 1
1 2 3
Output
3 2 1
Input
6
2 3 6 1 5 4
5 2 1 4 6 3
Output
6 5 5 5 4 1
Note
In the first test:
* If there are no bombs, A is equal to \{1, 2, 3\} at the end of the process, so the cost of the configuration is 3.
* If there is one bomb in position 1, A is equal to \{1, 2\} at the end of the process, so the cost of the configuration is 2;
* If there are two bombs in positions 1 and 2, A is equal to \{1\} at the end of the process, so the cost of the configuration is 1.
In the second test:
Let's consider the process for i = 4. There are three bombs on positions q_1 = 5, q_2 = 2, and q_3 = 1.
At the beginning, A = \{\}.
* Operation 1: Add p_1 = 2 to A, so A is equal to \{2\}. There exists a bomb in position 1, so we should delete the largest element from A. A is equal to \{\}.
* Operation 2: Add p_2 = 3 to A, so A is equal to \{3\}. There exists a bomb in position 2, so we should delete the largest element from A. A is equal to \{\}.
* Operation 3: Add p_3 = 6 to A, so A is equal to \{6\}. There is no bomb in position 3, so we do nothing.
* Operation 4: Add p_4 = 1 to A, so A is equal to \{1, 6\}. There is no bomb in position 4, so we do nothing.
* Operation 5: Add p_5 = 5 to A, so A is equal to \{1, 5, 6\}. There exists a bomb in position 5, so we delete the largest element from A. Now, A is equal to \{1, 5\}.
* Operation 6: Add p_6 = 4 to A, so A is equal to \{1, 4, 5\}. There is no bomb in position 6, so we do nothing.
In the end, we have A = \{1, 4, 5\}, so the cost of the configuration is equal to 5.
Submitted Solution:
```
class Dual():
def __init__(self, n):
self.update_cnt = 0
self.n = n
self.size = 1
INF = 2**32 - 1
while self.size < n:
self.size *= 2
self.node = [(self.update_cnt, INF) for i in range(2*self.size - 1)]
def update(self, begin, end, val):
self.update_cnt += 1
begin += (self.size - 1)
end += (self.size - 1)
while begin < end:
if (end - 1) & 1:
end -= 1
self.node[end] = (self.update_cnt, val)
if (begin - 1) & 1:
self.node[begin] = (self.update_cnt, val)
begin += 1
begin = (begin - 1) // 2
end = (end - 1) // 2
def get_val(self, i):
i += (self.size - 1)
val = self.node[i]
while i > 0:
i = (i - 1) // 2
val = max(val, self.node[i])
return val[1]
class SegmentTree():
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def built(self, array):
for i in range(self.n):
self.node[self.size + i] = array[i]
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def update(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def get_val(self, l, r):
l, r = l + self.size, r + self.size
res = self.e
while l < r:
if l & 1:
res = self.op(self.node[l], res)
l += 1
if r & 1:
r -= 1
res = self.op(self.node[r], res)
l, r = l >> 1, r >> 1
return res
n = int(input())
p = list(map(int, input().split()))
q = list(map(int, input().split()))
st = SegmentTree(n, max, 0)
st.built(p)
dst = Dual(n)
for i in range(n):
dst.update(i, i + 1, i + 1)
memo = {p[i]: i for i in range(n)}
ans = [None] * n
for i in range(n):
ans[i] = st.get_val(0, n)
r = dst.get_val(q[i] - 1)
#print(r, "r")
val = st.get_val(0, r)
st.update(memo[val], 0)
dst.update(memo[val], q[i], r)
#print([dst.get_val(i) for i in range(n)])
print(*ans)
``` | instruction | 0 | 36,971 | 12 | 73,942 |
No | output | 1 | 36,971 | 12 | 73,943 |
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_1, p_2, …, p_n.
Imagine that some positions of the permutation contain bombs, such that there exists at least one position without a bomb.
For some fixed configuration of bombs, consider the following process. Initially, there is an empty set, A.
For each i from 1 to n:
* Add p_i to A.
* If the i-th position contains a bomb, remove the largest element in A.
After the process is completed, A will be non-empty. The cost of the configuration of bombs equals the largest element in A.
You are given another permutation, q_1, q_2, …, q_n.
For each 1 ≤ i ≤ n, find the cost of a configuration of bombs such that there exists a bomb in positions q_1, q_2, …, q_{i-1}.
For example, for i=1, you need to find the cost of a configuration without bombs, and for i=n, you need to find the cost of a configuration with bombs in positions q_1, q_2, …, q_{n-1}.
Input
The first line contains a single integer, n (2 ≤ n ≤ 300 000).
The second line contains n distinct integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n).
The third line contains n distinct integers q_1, q_2, …, q_n (1 ≤ q_i ≤ n).
Output
Print n space-separated integers, such that the i-th of them equals the cost of a configuration of bombs in positions q_1, q_2, …, q_{i-1}.
Examples
Input
3
3 2 1
1 2 3
Output
3 2 1
Input
6
2 3 6 1 5 4
5 2 1 4 6 3
Output
6 5 5 5 4 1
Note
In the first test:
* If there are no bombs, A is equal to \{1, 2, 3\} at the end of the process, so the cost of the configuration is 3.
* If there is one bomb in position 1, A is equal to \{1, 2\} at the end of the process, so the cost of the configuration is 2;
* If there are two bombs in positions 1 and 2, A is equal to \{1\} at the end of the process, so the cost of the configuration is 1.
In the second test:
Let's consider the process for i = 4. There are three bombs on positions q_1 = 5, q_2 = 2, and q_3 = 1.
At the beginning, A = \{\}.
* Operation 1: Add p_1 = 2 to A, so A is equal to \{2\}. There exists a bomb in position 1, so we should delete the largest element from A. A is equal to \{\}.
* Operation 2: Add p_2 = 3 to A, so A is equal to \{3\}. There exists a bomb in position 2, so we should delete the largest element from A. A is equal to \{\}.
* Operation 3: Add p_3 = 6 to A, so A is equal to \{6\}. There is no bomb in position 3, so we do nothing.
* Operation 4: Add p_4 = 1 to A, so A is equal to \{1, 6\}. There is no bomb in position 4, so we do nothing.
* Operation 5: Add p_5 = 5 to A, so A is equal to \{1, 5, 6\}. There exists a bomb in position 5, so we delete the largest element from A. Now, A is equal to \{1, 5\}.
* Operation 6: Add p_6 = 4 to A, so A is equal to \{1, 4, 5\}. There is no bomb in position 6, so we do nothing.
In the end, we have A = \{1, 4, 5\}, so the cost of the configuration is equal to 5.
Submitted Solution:
```
n=int(input())
p=list(map(int,input().split()))
q=list(map(int,input().split()))
for i in range(1,n+1) :
j=0
a=p[0:len(p)]
#print(a,i,p)
while j<i-1 :
mx=max(a[0:q[j]])
a.remove(mx)
print(a)
j+=1
print(max(a))
``` | instruction | 0 | 36,972 | 12 | 73,944 |
No | output | 1 | 36,972 | 12 | 73,945 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 36,995 | 12 | 73,990 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
from collections import defaultdict
import sys
input=sys.stdin.readline
n=int(input())
a=[int(i) for i in input().split() if i!='\n']
b=[int(i) for i in input().split() if i!='\n']
visited=[0]*(n+1)
graph=defaultdict(list)
for i in range(n):
if b[i]!=-1:
graph[b[i]].append(i+1)
else:
graph[i+1]=[]
OBSERVE = 0
CHECK = 1
topsort=[]
for i in range(1,n+1):
if visited[i]==0:
stack = [(OBSERVE, i, 0)]
while len(stack):
state, vertex, parent = stack.pop()
visited[vertex]=1
if state == OBSERVE:
stack.append((CHECK, vertex, parent))
for child in graph[vertex]:
if visited[child]!=1:
stack.append((OBSERVE, child, vertex))
else:
topsort.append(vertex)
ans,path=0,[]
visited=[0]*(n+1)
neg=[]
for i in range(n):
if visited[i]==0:
if a[topsort[i]-1]>=0:
ans+=a[topsort[i]-1]
end=b[topsort[i]-1]
if end!=-1:
a[b[topsort[i]-1]-1]+=a[topsort[i]-1]
path.append(topsort[i])
visited[i]=1
else:
neg.append(topsort[i])
for i in neg:
ans+=a[i-1]
neg.reverse()
path+=neg
sys.stdout.write(str(ans)+'\n')
path=' '.join(map(str,path))
sys.stdout.write(path+'\n')
``` | output | 1 | 36,995 | 12 | 73,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 36,996 | 12 | 73,992 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
import sys
import collections
inpy = [int(x) for x in sys.stdin.read().split()]
n = inpy[0]
a = [0] + inpy[1:1+n]
b = [0] + inpy[1+n:]
p = [-1] * (n + 1)
res = 0
memo = []
# def helper(i):
# if p[i] != -1:
# return p[i]
# if b[i] == -1:
# return 1
# p[i] = 1 + helper(b[i])
# return p[i]
for i in range(1, n + 1):
que = collections.deque([i])
while que:
top = que[0]
if p[top] != -1:
que.popleft()
elif b[top] == -1:
p[top] = 1
que.popleft()
elif p[b[top]] != -1:
p[top] = 1 + p[b[top]]
que.popleft()
else:
que.appendleft(b[top])
memo.append((-p[i], a[i], b[i], i))
memo.sort()
# print(memo)
inc = [0] * (n + 1)
start = collections.deque()
end = collections.deque()
for i, j, k, l in memo:
nj = j + inc[l]
res += nj
if k != -1 and nj > 0:
inc[k] += nj
if nj > 0:
start.append(l)
else:
end.appendleft(l)
# print(start, end)
print(res)
print(*start, *end)
``` | output | 1 | 36,996 | 12 | 73,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 36,997 | 12 | 73,994 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
@bootstrap
def dfs(b,i,depths):
if b[i]==-1:
depths[i]=0
else:
if depths[b[i]]==-1:
yield dfs(b,b[i],depths)
depths[i]=1+depths[b[i]]
yield None
def main():
n=int(input())
a=[0]+readIntArr()
b=[0]+readIntArr()
depths=[-1 for _ in range(n+1)] #depths[i] stores the depth of index i
#depth will be 0 for i where b[i]==-1
#the indexes leading to i where b[i]==-1 shall have depth 1 etc...
for i in range(1,n+1):
if depths[i]==-1:
dfs(b,i,depths)
indexesByDepths=[[] for _ in range(n)] #indexesByDepths[depth] are the indexes with that depth
for i in range(1,n+1):
indexesByDepths[depths[i]].append(i)
for depth in range(n):
if len(indexesByDepths[depth])>0:
largestDepth=depth
else:
break
#starting from the largest depth
#NEGATIVE a[i] SHALL GO LAST
total=0
order=[]
delayedOrder=[] #all negative a[i] shall be delayed, and go from smallest depth first
for depth in range(largestDepth,-1,-1):
for i in indexesByDepths[depth]:
# print(i,a[i],total,a)#######
if a[i]>=0:
order.append(i)
total+=a[i]
if b[i]!=-1:
a[b[i]]+=a[i]
else: #delay. we don't want a negative value added to the next a[b[i]]
delayedOrder.append(i)
delayedOrder.sort(key=lambda i:depths[i]) #sort by depth asc
for i in delayedOrder:
order.append(i)
total+=a[i]
if b[i]!=-1:
a[b[i]]+=a[i]
print(total)
oneLineArrayPrint(order)
return
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
#import sys
#input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
main()
``` | output | 1 | 36,997 | 12 | 73,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 36,998 | 12 | 73,996 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
from collections import defaultdict, deque
if __name__ == "__main__":
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
graph = defaultdict(list)
inorder = defaultdict(int)
value = defaultdict(int)
for i in range(n):
value[i] = a[i]
if(b[i]!=-1):
graph[i].append(b[i]-1)
inorder[b[i]-1] += 1
q = deque()
for i in range(n):
if(inorder[i]==0):
q.append(i)
#print(q)
stack = []
neg_val = []
while(q):
current_node = q.popleft()
if(value[current_node]>=0):
stack.append(current_node)
elif(value[current_node]<0):
neg_val.append(current_node)
for i in graph[current_node]:
if(value[current_node]>0):
value[i] += value[current_node]
inorder[i] -= 1
if(inorder[i]==0):
q.append(i)
print(sum(value.values()))
print(*[i+1 for i in (stack+neg_val[::-1])])
``` | output | 1 | 36,998 | 12 | 73,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 36,999 | 12 | 73,998 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
from collections import deque
n,a,b = int(input()),list(map(int,input().split())),list(map(int,input().split()));ans = 0;ent = [0]*n
for x in b:
if x >= 0:ent[x-1] += 1
q = deque();G = [list() for _ in range(n)]
for i in range(n):
if not ent[i]:q.append(i)
while q:
v = q.popleft();ans += a[v]
if b[v] < 0: continue
x = b[v] - 1
if a[v] >= 0:G[v].append(x);a[x] += a[v]
else:G[x].append(v)
ent[x] -= 1
if not ent[x]: q.append(x)
ent = [0]*n
for l in G:
for x in l:ent[x] += 1
q = deque();l = list()
for i in range(n):
if not ent[i]:q.append(i)
while q:
v = q.popleft();l.append(v + 1)
for x in G[v]:
ent[x] -= 1
if not ent[x]: q.append(x)
print(ans);print(*l)
``` | output | 1 | 36,999 | 12 | 73,999 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 37,000 | 12 | 74,000 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = list(int(x)-1 for x in input().split())
indeg = [0] * n
for x in b:
if x >= 0:
indeg[x] += 1
#print(*indeg)
q = [i for i in range(n) if indeg[i] == 0]
ans = 0
res = []
end = []
while q:
top = q.pop()
#print("yo", top)
if a[top] < 0:
end.append(top)
else:
res.append(top)
ans += a[top]
if b[top] >= 0:
a[b[top]] += a[top]
if b[top] >= 0:
nei = b[top]
indeg[nei] -= 1
if indeg[nei] == 0:
q.append(nei)
for i in end[::-1]:
ans += a[i]
if b[i] >= 0:
a[b[i]] += a[i]
res.append(i)
print(ans)
print(*[x+1 for x in res])
``` | output | 1 | 37,000 | 12 | 74,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 37,001 | 12 | 74,002 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
n=int(input())
val=list(map(int,input().split()))
b=list(map(int,input().split()))
neig=[0]*n
for i in range(n):
neig[i]=[0]
inedges=[0]*n
for i in range(n):
if b[i]!=-1:
neig[i][0]+=1
neig[i].append(b[i]-1)
inedges[b[i]-1]+=1
ans=0
beg=[]
en=[]
tod=[]
for i in range(n):
if inedges[i]==0:
tod.append(i)
while len(tod)>0:
x=tod.pop()
ans+=val[x]
if val[x]>0:
beg.append(x+1)
else:
en.append(x+1)
if neig[x][0]==1:
inedges[neig[x][1]]-=1
if inedges[neig[x][1]]==0:
tod.append(neig[x][1])
if val[x]>0:
val[neig[x][1]]+=val[x]
print(ans)
print(*beg,end=" ")
en.reverse()
print(*en)
``` | output | 1 | 37,001 | 12 | 74,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2 | instruction | 0 | 37,002 | 12 | 74,004 |
Tags: data structures, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
from collections import Counter
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]
indeg = Counter(b)
s = []
for i in range(n):
if i+1 not in indeg:
s.append(i)
ans = 0
steps =[]
while s:
index = s.pop()
if a[index]>=0:
steps.append(index+1)
ans+=a[index]
if b[index]!=-1:
if a[index]>=0:
a[b[index]-1]+=a[index]
indeg[b[index]]-=1
if indeg[b[index]] == 0:
s.append(b[index]-1)
outdeg = {}
adj= {}
for i in range(n):
if b[i]!=-1 and a[i]<0 and a[b[i]-1]<0:
if b[i]-1 in adj:
adj[b[i]-1].append(i)
else:
adj[b[i]-1] = [i]
s = []
for i in range(n):
if a[i]<0:
if b[i]!=-1 and a[b[i]-1]<0:
outdeg[i] = 1
else:
s.append(i)
while s:
index = s.pop()
ans+=a[index]
steps.append(index+1)
if index in adj:
for ele in adj[index]:
outdeg[ele]-=1
if outdeg[ele] == 0:
s.append(ele)
print(ans)
for ele in steps:
print(ele,end=' ')
``` | output | 1 | 37,002 | 12 | 74,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
edges = [[] for i in range(n)]
parent = [-1 for i in range(n)]
for i in range(len(b)):
if b[i] != -1:
edges[b[i]-1].append(i)
parent[i] = b[i]-1
done = [0 for i in range(n)]
first = []
last = []
ans = 0
for i in range(n):
if done[i] == 0:
dfs = [i]
while len(dfs) > 0:
curr = dfs[-1]
cont = 1
for i in edges[curr]:
if done[i] == 0:
cont = 0
dfs.append(i)
break
if cont == 1:
if a[curr] > 0:
first.append(curr+1)
if parent[curr] != -1:
a[parent[curr]] += a[curr]
else:
last.append(curr+1)
ans += a[curr]
done[curr] = 1
dfs.pop(-1)
print(ans)
print(' '.join(map(str, first)) + ' ' + ' '.join(map(str, last[::-1])))
``` | instruction | 0 | 37,003 | 12 | 74,006 |
Yes | output | 1 | 37,003 | 12 | 74,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
from sys import stdin, setrecursionlimit as srl
from threading import stack_size, Thread
srl(int(1e6)+7)
stack_size(int(1e8))
ip=stdin.readline
def solve():
n=int(ip())
a=list(map(int, ip().split()))
b=list(map(int, ip().split()))
adj=[[] for _ in range(n)]
for i in range(n):
if not b[i]==-1:
adj[i].append(b[i]-1)
visited=[0]*n
stk=[]
for x in range(n):
def topsort(v):
if visited[v]==2: return
visited[v]=1
for i in adj[v]:
topsort(i)
visited[v]=2
stk.append(v)
if not visited[x]: topsort(x)
laterstk=[]#later stack
extra=[0]*n
ans=0; soln=[]
while stk:
i=stk.pop()
if (a[i]+extra[i])<0: laterstk.append(i)
else:
ans+=a[i]+extra[i]
if len(adj[i])==1:
j=adj[i][0]
extra[j]+=extra[i]+a[i]
soln.append(i+1)
while laterstk:
i=laterstk.pop()
ans+=a[i]+extra[i]
soln.append(i+1)
print(ans)
print(*soln)
Thread(target=solve).start()
``` | instruction | 0 | 37,004 | 12 | 74,008 |
Yes | output | 1 | 37,004 | 12 | 74,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
from collections import deque
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
parent=[b[i]-1 for i in range(n)]
edge=[[] for i in range(n)]
for i in range(n):
pv=parent[i]
if pv>-1:
edge[pv].append(i)
w=[a[i] for i in range(n)]
dp=[a[i] for i in range(n)]
order=[-1]*n
rest=[i+1 for i in range(n)]
rest=rest[::-1]
size=[1]*n
def solve(r):
deq=deque([r])
res=[]
while deq:
v=deq.popleft()
res.append(v)
for nv in edge[v]:
if nv!=parent[v]:
deq.append(nv)
res=res[::-1]
for v in res:
for nv in edge[v]:
if nv!=parent[v]:
w[v]+=w[nv]
ROOT=set([r])
for v in res:
for nv in edge[v]:
if nv!=parent[v]:
if dp[nv]>=0:
dp[v]+=dp[nv]
size[v]+=size[nv]
else:
ROOT.add(nv)
res=res[::-1]
def ordering(R):
deq=deque([R])
rrest=[-1]*size[R]
for i in range(size[R]):
rrest[i]=rest.pop()
#print(R,rrest)
while deq:
v=deq.popleft()
order[v]=rrest.pop()
for nv in edge[v]:
if nv not in ROOT:
deq.append(nv)
#if r==1:
#print(ROOT)
#for i in range(1,4):
#print(dp[i])
#print(ROOT)
#print(res)
for v in res:
if v in ROOT:
ordering(v)
#print(order)
root=[r for r in range(n) if b[r]==-1]
for r in root:
solve(r)
ans=0
for i in range(n):
ans+=dp[i]
print(ans)
#print(*order)
res=[0]*n
for i in range(n):
res[order[i]-1]=i+1
print(*res)
#print(dp)
``` | instruction | 0 | 37,005 | 12 | 74,010 |
Yes | output | 1 | 37,005 | 12 | 74,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
import math
from sys import setrecursionlimit
import threading
g = []
used = []
ord = []
head = []
def dfs(v):
now = []
now.append(v)
used[v] = 1
while len(now) > 0:
v = now[-1]
if head[v] == len(g[v]):
ord.append(v)
now.pop()
continue
if used[g[v][head[v]]] == 0:
now.append(g[v][head[v]])
used[g[v][head[v]]] = 1
head[v] += 1
def main():
global g, used, ord, head
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
answ = []
used = [0] * (n + 1)
g = [[] for i in range(n + 1)]
go = [[] for i in range(n + 1)]
dp = [0] * n
head = [0] * n
for i in range(n):
if b[i] == -1:
continue
b[i] -= 1
g[i].append(b[i])
go[b[i]].append(i)
for i in range(n):
if used[i] == 1:
continue
dfs(i)
ord.reverse()
for x in ord:
dp[x] += a[x]
for y in go[x]:
dp[x] += max(0, dp[y])
ans = 0
for x in ord:
if dp[x] < 0:
continue
ans += a[x]
answ.append(x)
if b[x] == -1:
continue
a[b[x]] += a[x]
for i in range(n - 1, -1, -1):
x = ord[i]
if dp[x] >= 0:
continue
ans += a[x]
answ.append(x)
if b[x] == -1:
continue
a[b[x]] += a[x]
print(ans)
for x in answ:
print(x + 1, end=" ")
main()
``` | instruction | 0 | 37,006 | 12 | 74,012 |
Yes | output | 1 | 37,006 | 12 | 74,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
ans = 0
queue = []
def tree(d,i):
for j in d[i]:
d[j].remove(i)
for j in d[i]:
tree(d,j)
return
def traverse(d,i,a,b):
global ans, queue
for j in d[i]:
traverse(d,j,a,b)
ans+=a[i]
if a[i]>0 and b[i]!=-1:
a[b[i]-1]+=a[i]
queue.append(i+1)
return
n = int ( input() )
a = list ( map ( int, input().split() ) )
b = list ( map ( int, input().split() ) )
terminators = []
for i in range(n):
if b[i]==-1:
terminators.append(i)
d={}
for i in range(n):
d[i]=[]
for i in range(n):
if b[i]!=-1:
d[i].append(b[i]-1)
d[b[i]-1].append(i)
for i in terminators:
tree(d,i)
for i in terminators:
traverse(d,i,a,b)
for i in terminators:
queue.append(i+1)
for i in range(n):
if a[i]<=0 and b[i]!=-1:
queue.append(i+1)
print(ans)
print(*queue)
``` | instruction | 0 | 37,007 | 12 | 74,014 |
No | output | 1 | 37,007 | 12 | 74,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")
def getlist():
return list(map(int, input().split()))
class Graph(object):
def __init__(self):
self.graph = defaultdict(list)
def __len__(self):
return len(self.graph)
def add_edge(self, a, b):
self.graph[a].append(b)
P = []
def DFS(G, W, A, visit, depth, node):
for i in G.graph[node]:
if visit[i] != 1:
visit[i] = 1
depth[i] = depth[node] + 1
DFS(G, W, A, visit, depth, i)
if A[i] > 0:
W[node] += W[i]
global P
P.append(i + 1)
# if A[node] > 0:
# global P
# P.append(node + 1)
#処理内容
def main():
N = int(input())
A = getlist()
B = getlist()
G = Graph()
W = [0] * N
for i in range(N):
W[i] = A[i]
u, v = B[i], i
if u != -1:
u -= 1
G.add_edge(u, v)
visit = [0] * N
depth = [INF] * N
for i in range(N):
if B[i] == -1:
visit[i] = 1
depth[i] = 0
DFS(G, W, A, visit, depth, i)
P.append(i + 1)
for i in range(N):
if A[i] <= 0 and B[i] != -1:
P.append(i + 1)
weight = sum(W)
print(weight)
print(*P)
if __name__ == '__main__':
main()
``` | instruction | 0 | 37,008 | 12 | 74,016 |
No | output | 1 | 37,008 | 12 | 74,017 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
import sys
import collections
inpy = [int(x) for x in sys.stdin.read().split()]
n = inpy[0]
a = [0] + inpy[1:1+n]
b = [0] + inpy[1+n:]
p = [-1] * (n + 1)
res = 0
memo = []
def helper(i):
if p[i] != -1:
return p[i]
if b[i] == -1:
return 1
p[i] = 1 + helper(b[i])
return p[i]
for i in range(1, n + 1):
memo.append((-helper(i), a[i], b[i], i))
memo.sort()
inc = [0] * (n + 1)
start = collections.deque()
end = collections.deque()
for i, j, k, l in memo:
nj = j + inc[l]
res += nj
if k != -1 and nj > 0:
inc[k] += nj
if nj > 0:
start.append(l)
else:
end.append(l)
# print(start, end)
print(res)
print(*start, *end)
``` | instruction | 0 | 37,009 | 12 | 74,018 |
No | output | 1 | 37,009 | 12 | 74,019 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
import math
n=int(input())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
li=[]
flag=0
for i in range(n):
if a[i]<0:
flag=1
li.append((a[i],i))
if flag:
li.sort(reverse=True)
else:
li.sort()
ans=0
order=[]
for i in range(n):
order.append(li[i][1]+1)
ans+=a[li[i][1]]
if b[li[i][1]]!=-1:
a[b[li[i][1]]-1]+=a[li[i][1]]
print(ans)
print(*order)
``` | instruction | 0 | 37,010 | 12 | 74,020 |
No | output | 1 | 37,010 | 12 | 74,021 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...
There are two arrays a and b of length n. Initially, an ans is equal to 0 and the following operation is defined:
1. Choose position i (1 ≤ i ≤ n);
2. Add a_i to ans;
3. If b_i ≠ -1 then add a_i to a_{b_i}.
What is the maximum ans you can get by performing the operation on each i (1 ≤ i ≤ n) exactly once?
Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.
Input
The first line contains the integer n (1 ≤ n ≤ 2 ⋅ 10^5) — the length of arrays a and b.
The second line contains n integers a_1, a_2, …, a_n (−10^6 ≤ a_i ≤ 10^6).
The third line contains n integers b_1, b_2, …, b_n (1 ≤ b_i ≤ n or b_i = -1).
Additional constraint: it's guaranteed that for any i (1 ≤ i ≤ n) the sequence b_i, b_{b_i}, b_{b_{b_i}}, … is not cyclic, in other words it will always end with -1.
Output
In the first line, print the maximum ans you can get.
In the second line, print the order of operations: n different integers p_1, p_2, …, p_n (1 ≤ p_i ≤ n). The p_i is the position which should be chosen at the i-th step. If there are multiple orders, print any of them.
Examples
Input
3
1 2 3
2 3 -1
Output
10
1 2 3
Input
2
-1 100
2 -1
Output
99
2 1
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import combinations
pr=stdout.write
import heapq
raw_input = stdin.readline
def ni():
return int(raw_input())
def li():
return list(map(int,raw_input().split()))
def pn(n):
stdout.write(str(n)+'\n')
def pa(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return (map(int,stdin.read().split()))
range = xrange # not for python 3.0+
n=ni()
a=li()
b=li()
d=Counter()
for i in range(n):
if b[i]!=-1:
d[b[i]-1]+=1
b[i]-=1
q=[]
arr1=[]
for i in range(n):
if not d[i]:
q.append(i)
ans=0
arr=[]
while q:
x=q.pop(0)
if a[x]<0:
arr1.append(x+1)
if b[x]!=-1:
d[b[x]]-=1
if not d[b[x]]:
q.append(b[x])
continue
arr.append(x+1)
ans+=a[x]
if b[x]!=-1:
a[b[x]]+=a[x]
d[b[x]]-=1
if not d[b[x]]:
q.append(b[x])
pn(ans+sum(a[i-1] for i in arr1))
pa(arr+arr1)
``` | instruction | 0 | 37,011 | 12 | 74,022 |
No | output | 1 | 37,011 | 12 | 74,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,033 | 12 | 74,066 |
Tags: constructive algorithms, implementation
Correct Solution:
```
#n=int(input())
for y in range(int(input())):
#n,m=map(int,input().split())
#lst1=list(map(int,input().split()))
n=int(input())
lst=list(map(int,input().split()))
dif=[0]*(n-1)
for i in range(n-2,-1,-1):
dif[i]=abs(lst[i]-lst[i+1])
summ=sum(dif)
minn=100000000000000001
for i in range(n):
if i==0:
minn=min(minn,summ-dif[0])
elif i==n-1:
minn=min(minn,summ-dif[-1])
else:
minn=min(minn,summ-dif[i-1]-dif[i]+abs(lst[i-1]-lst[i+1]))
print(minn)
``` | output | 1 | 37,033 | 12 | 74,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,034 | 12 | 74,068 |
Tags: constructive algorithms, implementation
Correct Solution:
```
"""
Author - Satwik Tiwari .
4th Dec , 2020 - Friday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
dp = [[-1,-1] for i in range(200010)]
def rec(pos,a,passed,diff):
# print(diff,pos)
if(pos >= len(a)):
return 0
if(dp[pos][passed] != -1):
return dp[pos][passed]
temp = inf
if(not passed):
# print(pos)
temp = min(temp,rec(pos+1,a,1-passed,diff))
temp = min(temp,abs(a[0] - (a[pos] + diff)) + rec(pos+1,a,passed,diff + a[0] - (a[pos] + diff)))
# dp[pos][passed] = temp
return temp
def solve(case):
n = int(inp())
a = lis()
# ans = 0
# temp = a[0]
# a[0] = a[1]
# diff = 0
# for i in range(1,n):
# curr = a[i] + diff
# diff += a[0] - curr
# ans += abs(a[0] - curr)
# # print(ans,'===')
#
# a[0] = temp
# for i in range(n):
# dp[i][0],dp[i][1] = -1,-1
# print(min(rec(1,a,0,0),ans))
pre = [0]*n
#without removal
for i in range(1,n):
pre[i] += pre[i-1]
pre[i] += abs(a[i] - a[i-1])
ans = pre[n-2]
suff = 0
for i in range(n-2,0,-1):
curr = pre[i-1] + abs(a[i+1] - a[i-1]) + suff
suff += abs(a[i+1] - a[i])
ans = min(ans,curr)
print(min(ans,suff))
# testcase(1)
testcase(int(inp()))
``` | output | 1 | 37,034 | 12 | 74,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,035 | 12 | 74,070 |
Tags: constructive algorithms, implementation
Correct Solution:
```
def solve():
n=int(input())
arr=[int(v) for v in input().split()]
dp=[[0]*(n+10) for _ in range(2)]
for i in reversed(range(n-1)):
dp[1][i] = dp[1][i+1] + abs(arr[i+1]-arr[i])
if i<n-2:
dp[0][i] = dp[0][i+1] + abs(arr[i+1]-arr[i])
dp[0][i] = min(dp[0][i], dp[1][i+2]+abs(arr[i+2]-arr[i]))
#print(ans, mxabs)
#print(dp)
print(min(dp[0][0], dp[1][1]))
t = int(input())
for _ in range(t):
solve()
``` | output | 1 | 37,035 | 12 | 74,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,036 | 12 | 74,072 |
Tags: constructive algorithms, implementation
Correct Solution:
```
t=int(input())
for q in range(t):
n=int(input())
ch=input()
L=[int(i)for i in ch.split()]
nb=0
for i in range(1,n):
nb+=abs(L[i]-L[i-1])
v=[]
v.append(abs(L[0]-L[1]))
v.append(abs(L[-1]-L[-2]))
for i in range(1,n-1):
if (L[i]<L[i+1] and L[i]<L[i-1])or((L[i]>L[i+1] and L[i]>L[i-1])):
v.append(abs(L[i]-L[i-1])+abs(L[i]-L[i+1])-abs(L[i-1]-L[i+1]))
print(nb-max(v))
``` | output | 1 | 37,036 | 12 | 74,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,037 | 12 | 74,074 |
Tags: constructive algorithms, implementation
Correct Solution:
```
# author : Tapan Goyal
# MNIT Jaipur
import math
import bisect
import itertools
import sys
I=lambda : sys.stdin.readline()
one=lambda : int(I())
more=lambda : map(int,I().split())
linput=lambda : list(more())
mod=10**9 +7
inf=10**18 + 1
'''fact=[1]*100001
ifact=[1]*100001
for i in range(1,100001):
fact[i]=((fact[i-1])*i)%mod
ifact[i]=((ifact[i-1])*pow(i,mod-2,mod))%mod
def ncr(n,r):
return (((fact[n]*ifact[n-r])%mod)*ifact[r])%mod
def npr(n,r):
return (((fact[n]*ifact[n-r])%mod))
'''
def merge(a,b):
i=0;j=0
c=0
ans=[]
while i<len(a) and j<len(b):
if a[i]<b[j]:
ans.append(a[i])
i+=1
else:
ans.append(b[j])
c+=len(a)-i
j+=1
ans+=a[i:]
ans+=b[j:]
return ans,c
def mergesort(a):
if len(a)==1:
return a,0
mid=len(a)//2
left,left_inversion=mergesort(a[:mid])
right,right_inversion=mergesort(a[mid:])
m,c=merge(left,right)
c+=(left_inversion+right_inversion)
return m,c
def is_prime(num):
if num == 1: return False
if num == 2: return True
if num == 3: return True
if num%2 == 0: return False
if num%3 == 0: return False
t = 5
a = 2
while t <= int(math.sqrt(num)):
if num%t == 0: return False
t += a
a = 6 - a
return True
def ceil(a,b):
return (a+b-1)//b
#/////////////////////////////////////////////////////////////////////////////////////////////////
if __name__ == "__main__":
for _ in range(one()):
n=one()
a=linput()
left=[0]*(n)
right=[0]*(n)
for i in range(n-1,0,-1):
left[i-1]=left[i] + abs(a[i]-a[i-1])
for i in range(n-1):
right[i+1]=right[i] + abs(a[i+1]-a[i])
ans=min((left[1]),(right[n-2]))
# print(ans)
for i in range(1,n-1):
x=left[i+1] + right[i-1] + abs(a[i-1]-a[i+1])
# print(x,i)
ans=min(ans,x)
# print(left,right)
print(ans)
``` | output | 1 | 37,037 | 12 | 74,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,038 | 12 | 74,076 |
Tags: constructive algorithms, implementation
Correct Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
a=list(map(int,input().split()))
ans=0
for i in range(n-1):
ans+=abs(a[i]-a[i+1])
c=0
c=max(abs(a[1]-a[0]),c)
c=max(c,abs(a[-1]-a[-2]))
for i in range(1,n-1):
c=max(c,abs(a[i]-a[i+1])+abs(a[i]-a[i-1])-abs(a[i-1]-a[i+1]))
print(ans-c)
``` | output | 1 | 37,038 | 12 | 74,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,039 | 12 | 74,078 |
Tags: constructive algorithms, implementation
Correct Solution:
```
from sys import stdin
import math
input=stdin.readline
for _ in range(int(input())):
n,=map(int,input().split())
l=list(map(int,input().split()))
s=0
for j in range(n-1):
s+=abs(l[j]-l[j+1])
mx=max(abs(l[1]-l[0]),abs(l[n-1]-l[n-2]))
for i in range(1,n-1):
mx=max(mx,abs(l[i]-l[i+1])+abs(l[i]-l[i-1])-abs(l[i+1]-l[i-1]))
print(s-mx)
``` | output | 1 | 37,039 | 12 | 74,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3]. | instruction | 0 | 37,040 | 12 | 74,080 |
Tags: constructive algorithms, implementation
Correct Solution:
```
for i1 in range(int(input())):
n=int(input())
a=[0]+list(map(int,input().split()))
ref=[abs(a[i]-a[i-1]) for i in range(2,n+1)]
ans=sum(ref)
mx = max(abs(a[2] - a[1]), abs(a[n] - a[n - 1]))
for i in range(2, n):
mx = max(mx, abs(a[i] - a[i - 1]) + abs(a[i + 1] - a[i]) - abs(a[i + 1] - a[i - 1]))
print(ans - mx)
``` | output | 1 | 37,040 | 12 | 74,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
a=[int(x) for x in input().split()]
t=0
for i in range(1,n):
t+=abs(a[i]-a[i-1])
maxDecrease=0
for i in range(n):
if i-1>=0 and i+1<n:
original=abs(a[i+1]-a[i])+abs(a[i]-a[i-1])
new=abs(a[i+1]-a[i-1])
elif i==0:
original=abs(a[i+1]-a[i])
new=0
else:
original=abs(a[i]-a[i-1])
new=0
maxDecrease=max(maxDecrease,original-new)
print(t-maxDecrease)
``` | instruction | 0 | 37,041 | 12 | 74,082 |
Yes | output | 1 | 37,041 | 12 | 74,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
for i in range(int(input())):
n = int(input());s = 0;l = list(map(int,input().split()))
for i in range(n-1):s += abs(l[i]-l[i+1])
sm = min(s,s-abs(l[1]-l[0]),s-abs(l[n-1]-l[n-2]))
for i in range(1,n-1):sm = min(sm,s-abs(l[i]-l[i-1])-abs(l[i+1]-l[i])+abs(l[i+1]-l[i-1]))
print(sm)
``` | instruction | 0 | 37,042 | 12 | 74,084 |
Yes | output | 1 | 37,042 | 12 | 74,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
def solve():
n = int(input())
a = [0] + list(map(int, input().split()))
ans = 0
for i in range(2, n + 1):
ans += abs(a[i] - a[i - 1])
mx = max(abs(a[2] - a[1]), abs(a[n] - a[n - 1]))
for i in range(2, n):
mx = max(mx, abs(a[i] - a[i - 1]) + abs(a[i + 1] - a[i]) - abs(a[i + 1] - a[i - 1]))
print(ans - mx)
t = int(input())
for _ in range(t):
solve()
``` | instruction | 0 | 37,043 | 12 | 74,086 |
Yes | output | 1 | 37,043 | 12 | 74,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
for i in range(int(input())):
x=int(input())
a=list(map(int,input().split()))
summ=0
for j in range(1,x):
summ+=abs(a[j]-a[j-1])
maxx=abs(a[1]-a[0])
for j in range(2,x):
if maxx<((abs(a[j]-a[j-1])+abs(a[j-1]-a[j-2]))-abs(a[j]-a[j-2])):
maxx=((abs(a[j]-a[j-1])+abs(a[j-1]-a[j-2]))-abs(a[j]-a[j-2]))
if maxx<abs(a[x-1]-a[x-2]):
maxx=abs(a[x-1]-a[x-2])
print(str(summ-maxx))
``` | instruction | 0 | 37,044 | 12 | 74,088 |
Yes | output | 1 | 37,044 | 12 | 74,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
cases = int(input())
for t in range(cases):
n = int(input())
a = list(map(int,input().split()))
inans = sum([abs(a[i]-a[i-1]) for i in range(1,n)])
out = inans
for i in range(n):
if i==0:
newans = inans-abs(a[i]-a[i+1])
elif i==n-1:
newans = inans-abs(a[i]-a[i-1])
else:
if i+2<n:
newans1 = inans - abs(a[i]-a[i+1]) - abs(a[i]-a[i-1]) + abs(a[i+1] - a[i-1])
else:
newans1 = inans - abs(a[i]-a[i+1])
if i-2>-1:
newans2 = inans - abs(a[i]-a[i+1]) - abs(a[i]-a[i-1]) + abs(a[i+1] - a[i-1])
else:
newans2 = inans - abs(a[i]-a[i-1])
newans = min(newans1,newans2)
out = min(newans,out)
print(out)
``` | instruction | 0 | 37,045 | 12 | 74,090 |
No | output | 1 | 37,045 | 12 | 74,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
a = int(input())
for x in range(a):
b = int(input())
c = list(map(int,input().split()))
if len(list(set(c))) == 1:
print(0)
else:
if c[0] == c[1]:
if b == 2:
print(0)
else:
k = 2
for y in range(2,b):
if c[y] != c[0]:
k = y
break
j = 0
for x in range(b-1,k-1,-1):
j += abs(c[y]-c[y-1])
print(j)
else:
t = c.copy()
p = c.copy()
s = c.copy()
t[1] = t[0]
n = 0
if b == 2:
n = 0
else:
k = 2
for y in range(2,b):
if t[y] != t[0]:
k = y
break
for y in range(b - 1, k-1, -1):
n += abs(t[y] - t[y - 1])
m = 0
c[0] = c[1]
if b == 2:
m = 0
else:
k = 2
for y in range(2,b):
if c[y] != c[0]:
k = y
break
for y in range(b - 1, k-1, -1):
m += abs(c[y] - c[y - 1])
p[-1] = p[-2]
nn = 0
if b == 2:
nn = 0
else:
k = 2
for y in range(b-3,-1,-1):
if p[y] != p[-1]:
k = y
break
for y in range(0,k+1):
nn += abs(p[y] - p[y + 1])
s[-2] = s[-1]
mm = 0
if b == 2:
mm = 0
else:
k = 2
for y in range(b - 3, -1, -1):
if s[y] != s[-1]:
k = y
break
for y in range(0, k + 1):
mm += abs(s[y] - s[y + 1])
print(min(m,n,nn,mm))
``` | instruction | 0 | 37,046 | 12 | 74,092 |
No | output | 1 | 37,046 | 12 | 74,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
def solve(a):
record=sum=0
nums = list(map(int, a.split()))
for i in range(1, len(nums)):
dif = abs(nums[i] - nums[i - 1])
record = max(record, dif)
sum += dif
for i in range(2, len(nums)):
a = nums[i - 2]
b = nums[i - 1]
c = nums[i]
record = max(record, abs(a - b) + abs(b - c) - abs(c - a))
return sum - record
n = int(input())
for i in range(n):
input()
print(solve(input()))
``` | instruction | 0 | 37,047 | 12 | 74,094 |
No | output | 1 | 37,047 | 12 | 74,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong has an interesting machine that has an array a with n integers. The machine supports two kinds of operations:
1. Increase all elements of a suffix of the array by 1.
2. Decrease all elements of a suffix of the array by 1.
A suffix is a subsegment (contiguous elements) of the array that contains a_n. In other words, for all i where a_i is included in the subsegment, all a_j's where i < j ≤ n must also be included in the subsegment.
Gildong wants to make all elements of a equal — he will always do so using the minimum number of operations necessary. To make his life even easier, before Gildong starts using the machine, you have the option of changing one of the integers in the array to any other integer. You are allowed to leave the array unchanged. You want to minimize the number of operations Gildong performs. With your help, what is the minimum number of operations Gildong will perform?
Note that even if you change one of the integers in the array, you should not count that as one of the operations because Gildong did not perform it.
Input
Each test contains one or more test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1000).
Each test case contains two lines. The first line of each test case consists of an integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of elements of the array a.
The second line of each test case contains n integers. The i-th integer is a_i (-5 ⋅ 10^8 ≤ a_i ≤ 5 ⋅ 10^8).
It is guaranteed that the sum of n in all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print one integer — the minimum number of operations Gildong has to perform in order to make all elements of the array equal.
Example
Input
7
2
1 1
3
-1 0 2
4
99 96 97 95
4
-3 -5 -2 1
6
1 4 3 2 4 1
5
5 0 0 0 5
9
-367741579 319422997 -415264583 -125558838 -300860379 420848004 294512916 -383235489 425814447
Output
0
1
3
4
6
5
2847372102
Note
In the first case, all elements of the array are already equal. Therefore, we do not change any integer and Gildong will perform zero operations.
In the second case, we can set a_3 to be 0, so that the array becomes [-1,0,0]. Now Gildong can use the 2-nd operation once on the suffix starting at a_2, which means a_2 and a_3 are decreased by 1, making all elements of the array -1.
In the third case, we can set a_1 to 96, so that the array becomes [96,96,97,95]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [96,96,96,94].
* Use the 1-st operation on the suffix starting at a_4 2 times, making the array [96,96,96,96].
In the fourth case, we can change the array into [-3,-3,-2,1]. Now Gildong needs to:
* Use the 2-nd operation on the suffix starting at a_4 3 times, making the array [-3,-3,-2,-2].
* Use the 2-nd operation on the suffix starting at a_3 once, making the array [-3,-3,-3,-3].
Submitted Solution:
```
if __name__ == "__main__":
t = int(input())
while t:
t -= 1
n = int(input())
a = [int(x) for x in input().split()]
dif = []
rang = []
s = 0
for i in range(n - 1):
dif.append(abs(a[i] - a[i + 1]))
s += abs(a[i] - a[i + 1])
for i in range(n - 2):
rang.append(s - dif[i] - (dif[i + 1] - abs(dif[i + 1] - dif[i])))
rang.append(s - dif[0])
print(min(rang))
``` | instruction | 0 | 37,048 | 12 | 74,096 |
No | output | 1 | 37,048 | 12 | 74,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer array a of size n.
You have to perform m queries. Each query has one of two types:
* "1 l r k" — calculate the minimum value dif such that there are exist k distinct integers x_1, x_2, ..., x_k such that cnt_i > 0 (for every i ∈ [1, k]) and |cnt_i - cnt_j| ≤ dif (for every i ∈ [1, k], j ∈ [1, k]), where cnt_i is the number of occurrences of x_i in the subarray a[l..r]. If it is impossible to choose k integers, report it;
* "2 p x" — assign a_{p} := x.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the size of the array a and the number of queries.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5).
Next m lines contain queries (one per line). Each query has one of two types:
* "1 l r k" (1 ≤ l ≤ r ≤ n; 1 ≤ k ≤ 10^5)
* "2 p x" (1 ≤ p ≤ n; 1 ≤ x ≤ 10^5).
It's guaranteed that there is at least one query of the first type.
Output
For each query of the first type, print the minimum value of dif that satisfies all required conditions, or -1 if it is impossible to choose k distinct integers.
Example
Input
12 11
2 1 1 2 1 1 3 2 1 1 3 3
1 2 10 3
1 2 11 3
2 7 2
1 3 9 2
1 1 12 1
1 1 12 4
2 12 4
1 1 12 4
2 1 5
1 3 12 2
1 1 4 3
Output
5
4
1
0
-1
5
0
1
Submitted Solution:
```
print("Ato Hard problem set koren Keno??")
``` | instruction | 0 | 37,049 | 12 | 74,098 |
No | output | 1 | 37,049 | 12 | 74,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer array a of size n.
You have to perform m queries. Each query has one of two types:
* "1 l r k" — calculate the minimum value dif such that there are exist k distinct integers x_1, x_2, ..., x_k such that cnt_i > 0 (for every i ∈ [1, k]) and |cnt_i - cnt_j| ≤ dif (for every i ∈ [1, k], j ∈ [1, k]), where cnt_i is the number of occurrences of x_i in the subarray a[l..r]. If it is impossible to choose k integers, report it;
* "2 p x" — assign a_{p} := x.
Input
The first line contains two integers n and m (1 ≤ n, m ≤ 10^5) — the size of the array a and the number of queries.
The second line contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 10^5).
Next m lines contain queries (one per line). Each query has one of two types:
* "1 l r k" (1 ≤ l ≤ r ≤ n; 1 ≤ k ≤ 10^5)
* "2 p x" (1 ≤ p ≤ n; 1 ≤ x ≤ 10^5).
It's guaranteed that there is at least one query of the first type.
Output
For each query of the first type, print the minimum value of dif that satisfies all required conditions, or -1 if it is impossible to choose k distinct integers.
Example
Input
12 11
2 1 1 2 1 1 3 2 1 1 3 3
1 2 10 3
1 2 11 3
2 7 2
1 3 9 2
1 1 12 1
1 1 12 4
2 12 4
1 1 12 4
2 1 5
1 3 12 2
1 1 4 3
Output
5
4
1
0
-1
5
0
1
Submitted Solution:
```
print("5")
print("4")
print("1")
print("0")
print("-1")
print("5")
print("0")
print("1")
``` | instruction | 0 | 37,050 | 12 | 74,100 |
No | output | 1 | 37,050 | 12 | 74,101 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,051 | 12 | 74,102 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
def sol(n,d,F):
L=[[0]*(n+2),[0]*(n+2)];L[0][-1]=L[1][0]=2*n+1
q=[1];nq=[];m=g=f=t=0;l=1;h=n+1;u=[0]*(2*n+1);u[1]=1;p=1
while l!=h:
if not q:
t+=min(f,g-f)
f=g=m=0
while u[p]:p+=1
q=[p];u[p]=1
else:
while q:
v=q.pop();g+=1;f+=F[v];u[d[v]]=1
if m:
if L[0][h-1]!=0:return -1
L[0][h-1]=v;L[1][h-1]=d[v]
if v>L[0][h] or d[v]<L[1][h]:return -1
for i in range(L[1][h]+1,d[v]):
if not u[i]:nq.append(i);u[i]=1
h-=1
else:
if L[0][l]!=0:return -1
L[0][l]=v;L[1][l]=d[v]
if v<L[0][l-1] or d[v]>L[1][l-1]:return -1
for i in range(L[1][l-1]-1,d[v],-1):
if not u[i]:nq.append(i);u[i]=1
l+=1
m,q,nq=1-m,nq[::-1],[]
for i in range(1,n+2):
if L[0][i]<L[0][i-1] or L[1][i]>L[1][i-1]:return -1
return t+min(f,g-f)
n=int(Z());d=[0]*(2*n+1);F=[0]*(2*n+1)
for _ in range(n):a,b=map(int,Z().split());d[a]=b;d[b]=a;F[a]=1
print(sol(n,d,F))
``` | output | 1 | 37,051 | 12 | 74,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,052 | 12 | 74,104 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
import sys,io,os
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
def sol(n,d,F):
L=[[0]*(n+2),[0]*(n+2)];L[0][-1]=L[1][0]=2*n+1
q=[1];nq=[];m=g=f=t=0;l=1;h=n+1
u=[0]*(2*n+1);u[1]=1;p=1
while l!=h:
#print(q,L,m)
if not q:
t+=min(f,g-f)
f=g=m=0
while u[p]:p+=1
q=[p];u[p]=1
else:
while q:
v=q.pop()
g+=1
f+=F[v]
u[d[v]]=1
if m:
if L[0][h-1]!=0:return -1
L[0][h-1]=v
L[1][h-1]=d[v]
if v>L[0][h] or d[v]<L[1][h]:return -1
for i in range(L[1][h]+1,d[v]):
if not u[i]:nq.append(i);u[i]=1
h-=1
else:
if L[0][l]!=0:return -1
L[0][l]=v
L[1][l]=d[v]
if v<L[0][l-1] or d[v]>L[1][l-1]:return -1
for i in range(L[1][l-1]-1,d[v],-1):
if not u[i]:nq.append(i);u[i]=1
l+=1
m=1-m
q,nq=nq[::-1],[]
#print(q,L)
for i in range(1,n+2):
if L[0][i]<L[0][i-1] or L[1][i]>L[1][i-1]:return -1
t+=min(f,g-f)
return t
n=int(Z())
d=[0]*(2*n+1);F=[0]*(2*n+1)
for _ in range(n):
a,b=map(int,Z().split())
d[a]=b;d[b]=a;F[a]=1
print(sol(n,d,F))
``` | output | 1 | 37,052 | 12 | 74,105 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,053 | 12 | 74,106 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
from sys import stdin
def solve():
n = int(stdin.readline())
dic = {}
cards = set()
for i in range(n):
a, b = map(int, stdin.readline().split())
a -= 1
b -= 1
dic[a] = b
dic[b] = a
cards.add((a, b))
top = []
bot = []
used = [False] * (2*n)
left = 0
right = 2*n-1
left_target = 0
right_target = 2*n
count = 0
final_ans = 0
try:
while count != n:
flag = True
while left < left_target:
flag = False
while used[left]:
left += 1
if left == left_target:
break
else:
a, b = left, dic[left]
top.append((a, b))
used[a] = True
used[b] = True
right_target = min(right_target, b)
count += 1
left += 1
#print(top, bot, left, left_target, right, right_target)
if left == left_target:
break
if len(top) + len(bot) == n:
continue
while right > right_target:
flag = False
while used[right]:
right -= 1
if right == right_target:
break
else:
a, b = right, dic[right]
bot.append((a, b))
used[a] = True
used[b] = True
left_target = max(left_target, b)
count += 1
right -= 1
#print(top, bot, left, left_target, right, right_target)
if right == right_target:
break
if flag:
#print('boop')
srt = top + bot[::-1]
for i in range(len(srt)-1):
if not (srt[i][0] < srt[i+1][0] and srt[i][1] > srt[i+1][1]):
return -1
else:
ans = 0
for c in top + bot:
if c in cards:
ans += 1
final_ans += min(ans, len(top)+len(bot)-ans)
left_target += 1
right_target -= 1
top = []
bot = []
#print(top, bot, left, left_target, right, right_target)
#else:
#print("restarting loop")
if count == n:
srt = top + bot[::-1]
for i in range(len(srt)-1):
if not (srt[i][0] < srt[i+1][0] and srt[i][1] > srt[i+1][1]):
return -1
else:
ans = 0
for c in top + bot:
if c in cards:
ans += 1
final_ans += min(ans, len(top)+len(bot)-ans)
return final_ans
except:
return -1
print(solve())
``` | output | 1 | 37,053 | 12 | 74,107 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,054 | 12 | 74,108 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
number_of_cards = int(input())
opposite_side = {}
cards = set()
result = 0
top = []
bottom = []
highest_taken = 2 * number_of_cards + 1
lowest_taken = 0
for _ in range(number_of_cards):
front, back = map(int, input().split())
opposite_side[front] = back
opposite_side[back] = front
cards.add((front, back))
def end():
print(-1)
exit(0)
for i in range(1, 2*number_of_cards + 1):
if opposite_side[i] == -1:
continue
a, b = i, opposite_side[i]
opposite_side[a], opposite_side[b] = -1, -1
top.append((a, b))
counter = 1
cost = 0 if (a, b) in cards else 1
should_repeat = True
candidate_max = b
candidate_min = a
while should_repeat:
should_repeat = False
while highest_taken > candidate_max:
highest_taken -= 1
if opposite_side[highest_taken] == -1:
continue
should_repeat = True
tmp_a, tmp_b = highest_taken, opposite_side[highest_taken]
# print("***", tmp_a, tmp_b)
opposite_side[tmp_a], opposite_side[tmp_b] = -1, -1
if (len(bottom) == 0 or (tmp_a < bottom[-1][0] and tmp_b > bottom[-1][1])) and (tmp_a > top[-1][0] and tmp_b < top[-1][1]):
bottom.append((tmp_a, tmp_b))
candidate_min = max(candidate_min, tmp_b)
counter += 1
if (tmp_a, tmp_b) not in cards:
cost += 1
else:
end()
while lowest_taken < candidate_min:
lowest_taken += 1
if opposite_side[lowest_taken] == -1:
continue
should_repeat = True
tmp_a, tmp_b = lowest_taken, opposite_side[lowest_taken]
opposite_side[tmp_a], opposite_side[tmp_b] = -1, -1
if (len(top) == 0 or (tmp_a > top[-1][0] and tmp_b < top[-1][1])) and (len(bottom) == 0 or (tmp_a < bottom[-1][0] and tmp_b > bottom[-1][1])):
top.append((tmp_a, tmp_b))
candidate_max = min(candidate_max, tmp_b)
counter += 1
if (tmp_a, tmp_b) not in cards:
cost += 1
else:
end()
result += min(cost, counter - cost)
print(result)
``` | output | 1 | 37,054 | 12 | 74,109 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,055 | 12 | 74,110 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
front = [-1] * n
back = [-1] * n
rev = [-1] * (2 * n)
used = [False] * n
opp = [-1] * (2 * n)
for c in range(n):
a, b = map(lambda x: int(x) - 1, input().split())
front[c] = a
back[c] = b
rev[a] = c
rev[b] = c
opp[a] = b
opp[b] = a
left = -1
right = 2 * n
out = 0
works = True
while right - left > 1:
s_l = left + 1
s_r = right
curr = 0
curr_f = 0
while (s_l > left or s_r < right) and right - left > 1:
#print(left, s_l, s_r, right)
if s_l > left:
left += 1
card = rev[left]
if not used[card]:
used[card] = True
curr += 1
if front[card] == left:
curr_f += 1
if opp[left] < s_r:
s_r = opp[left]
else:
works = False
elif s_r < right:
right -= 1
card = rev[right]
if not used[card]:
used[card] = True
curr += 1
if front[card] == right:
curr_f += 1
if opp[right] > s_l:
s_l = opp[right]
else:
works = False
if s_l > s_r:
works = False
if not works:
break
out += min(curr_f, curr - curr_f)
if works:
print(out)
else:
print(-1)
``` | output | 1 | 37,055 | 12 | 74,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,056 | 12 | 74,112 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
N = int(input())
AB = [-1] * (2*N+1)
BA = [-1] * (2*N+1)
for _ in range(N):
a, b = map(int, input().split())
AB[a] = b
BA[b] = a
seen = [0] * (2*N+1)
small = 0
large = 2*N+1
top = []
bottom = []
ans = 0
seen_sum = 0
while True:
cnt_all = 0
cnt_flipped = 0
small += 1
cnt_all += 1
if BA[small] != -1:
cnt_flipped += 1
L = BA[small]
else:
L = AB[small]
top.append((small, L))
seen[small] = 1
seen[L] = 1
small_new = small
large_new = L
seen_sum += 2
while small != small_new or large_new != large:
if large_new != large:
for l in range(large - 1, large_new, -1):
if seen[l]:
continue
cnt_all += 1
if BA[l] != -1:
cnt_flipped += 1
s = BA[l]
else:
s = AB[l]
bottom.append((l, s))
seen[s] = 1
seen[l] = 1
seen_sum += 2
small_new = max(small_new, s)
large = large_new
elif small_new != small:
for s in range(small + 1, small_new):
if seen[s]:
continue
cnt_all += 1
if BA[s] != -1:
cnt_flipped += 1
l = BA[s]
else:
l = AB[s]
top.append((s, l))
seen[s] = 1
seen[l] = 1
large_new = min(large_new, l)
seen_sum += 2
small = small_new
if seen_sum == 2*N:
break
ans += min(cnt_flipped, cnt_all - cnt_flipped)
if seen_sum == 2*N:
break
bottom.reverse()
top.extend(bottom)
ok = 1
for i in range(N-1):
if top[i][0] > top[i+1][0] or top[i][1] < top[i+1][1]:
ok = 0
break
if ok:
print(ans)
else:
print(-1)
if __name__ == '__main__':
main()
``` | output | 1 | 37,056 | 12 | 74,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,057 | 12 | 74,114 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LI1(): return list(map(int1, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = 10**16
# md = 998244353
md = 10**9+7
n = II()
rev = [0]*2*n
inc = [False]*2*n
ab=[]
for _ in range(n):
a, b = LI1()
if a<b:ab.append((a,b,0))
else:ab.append((b,a,1))
inc=sorted(ab,key=lambda x:-x[0])
dec=sorted(ab,key=lambda x:x[1])
al=[]
bl=[2*n]
ar=[]
br=[-1]
ans=0
fin=[False]*2*n
while inc and dec:
c0 = c1 = 0
a,b,t=inc.pop()
if fin[a]: continue
fin[a]=fin[b]=True
al.append(a)
bl.append(b)
if t==0:c0+=1
else:c1+=1
up=True
while up:
up=False
while inc and inc[-1][0]<br[-1]:
a, b, t = inc.pop()
if fin[a]: continue
fin[a] = fin[b] = True
al.append(a)
bl.append(b)
if t == 0: c0 += 1
else: c1 += 1
up=True
while dec and dec[-1][1]>bl[-1]:
a, b, t = dec.pop()
if fin[a]: continue
fin[a] = fin[b] = True
ar.append(b)
br.append(a)
if t == 0: c1 += 1
else: c0 += 1
up=True
ans+=min(c0,c1)
# print(al,ar[::-1])
# print(bl,br[::-1])
def ok():
bb=br+bl[::-1]
return bb==sorted(bb)
if ok():print(ans)
else:print(-1)
``` | output | 1 | 37,057 | 12 | 74,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck. | instruction | 0 | 37,058 | 12 | 74,116 |
Tags: 2-sat, constructive algorithms, data structures, greedy, sortings, two pointers
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
from collections import deque
N = int(input())
X = [0] * (2 * N)
for i in range(N):
a, b = map(int, input().split())
a -= 1
b -= 1
X[a] = (0, b)
X[b] = (1, a)
l, r = 0, 2 * N - 1
done = [0] * (2 * N)
Q = deque([])
R = deque([])
mi = 0
ma = 2 * N - 1
ans = 0
while l <= r:
while done[l]:
l += 1
if l > r: break
if l > r: break
x = l
done[x] = 1
l += 1
p, y = X[x]
done[y] = 1
c = 1
s = p
while 1:
while r > y:
if not done[r]:
R.append(r)
done[r] = 1
r -= 1
if not R: break
while R:
x = R.popleft()
p, y = X[x]
if done[y]:
print(-1)
exit()
done[y] = 1
if y < mi:
print(-1)
exit()
c += 1
s += p
mi = y
while l < mi:
if not done[l]:
Q.append(l)
done[l] = 1
l += 1
if not Q: break
while Q:
x = Q.popleft()
p, y = X[x]
if done[y]:
print(-1)
exit()
done[y] = 1
if y > ma:
print(-1)
exit()
c += 1
s += p
ma = y
ans += min(s, c - s)
print(ans)
``` | output | 1 | 37,058 | 12 | 74,117 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a deck of n cards. The i-th card has a number a_i on the front and a number b_i on the back. Every integer between 1 and 2n appears exactly once on the cards.
A deck is called sorted if the front values are in increasing order and the back values are in decreasing order. That is, if a_i< a_{i+1} and b_i> b_{i+1} for all 1≤ i<n.
To flip a card i means swapping the values of a_i and b_i. You must flip some subset of cards (possibly, none), then put all the cards in any order you like. What is the minimum number of cards you must flip in order to sort the deck?
Input
The first line contains a single integer n (1≤ n≤ 2⋅ 10^5) — the number of cards.
The next n lines describe the cards. The i-th of these lines contains two integers a_i, b_i (1≤ a_i, b_i≤ 2n). Every integer between 1 and 2n appears exactly once.
Output
If it is impossible to sort the deck, output "-1". Otherwise, output the minimum number of flips required to sort the deck.
Examples
Input
5
3 10
6 4
1 9
5 8
2 7
Output
2
Input
2
1 2
3 4
Output
-1
Input
3
1 2
3 6
4 5
Output
-1
Note
In the first test case, we flip the cards (1, 9) and (2, 7). The deck is then ordered (3,10), (5,8), (6,4), (7,2), (9,1). It is sorted because 3<5<6<7<9 and 10>8>4>2>1.
In the second test case, it is impossible to sort the deck.
Submitted Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
N = int(input())
AB = [-1] * (2*N+1)
BA = [-1] * (2*N+1)
for _ in range(N):
a, b = map(int, input().split())
AB[a] = b
BA[b] = a
seen = [0] * (2*N+1)
small = 0
large = 2*N+1
top = []
bottom = []
ans = 0
seen_sum = 0
while True:
cnt_all = 0
cnt_flipped = 0
small += 1
cnt_all += 1
if BA[small] != -1:
cnt_flipped += 1
L = BA[small]
else:
L = AB[small]
top.append((small, L))
seen[small] = 1
seen[L] = 1
small_new = small
large_new = L
seen_sum += 2
while small != small_new or large_new != large:
if large_new != large:
for l in range(large - 1, large_new, -1):
if seen[l]:
continue
cnt_all += 1
if BA[l] != -1:
cnt_flipped += 1
s = BA[l]
else:
s = AB[l]
bottom.append((l, s))
seen[s] = 1
seen[l] = 1
seen_sum += 2
small_new = max(small_new, s)
large = large_new
elif small_new != small:
for s in range(small + 1, small_new):
if seen[s]:
continue
cnt_all += 1
if BA[s] != -1:
cnt_flipped += 1
l = BA[s]
else:
l = AB[s]
top.append((s, l))
seen[s] = 1
seen[l] = 1
large_new = min(large_new, l)
small = small_new
if seen_sum == 2*N:
break
ans += min(cnt_flipped, cnt_all - cnt_flipped)
if seen_sum == 2*N:
break
bottom.reverse()
top.extend(bottom)
ok = 1
for i in range(N-1):
if top[i][0] > top[i+1][0] or top[i][1] < top[i+1][1]:
ok = 0
break
if ok:
print(ans)
else:
print(-1)
if __name__ == '__main__':
main()
``` | instruction | 0 | 37,061 | 12 | 74,122 |
No | output | 1 | 37,061 | 12 | 74,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.
Sereja needs to rush to the gym, so he asked to find all the described positions of q.
Input
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
Output
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
Examples
Input
5 3 1
1 2 3 2 1
1 2 3
Output
2
1 3
Input
6 3 2
1 3 2 2 3 1
1 2 3
Output
2
1 2 | instruction | 0 | 37,163 | 12 | 74,326 |
Tags: binary search, data structures
Correct Solution:
```
from sys import stdin, stdout
from math import log, sqrt
lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
hash_map = {}
def hash_elem(elem):
if hash_map.get(elem, -1) == -1:
if elem < 1000:
hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem)) + elem&213213 + elem^324234211323 + elem|21319423094023
else:
hash_map[elem] = 3 + elem^34# elem<<2 + elem>>7 + elem&243 + elem^324 + elem|434
return elem + hash_map[elem]
c = [hash_elem(elem) for elem in a]
c_new = [sum([c[q + p*i] for i in range(m)]) for q in range(min(p, max(0,n - (m-1)*p)))]
for q in range(p,n - (m-1)*p):
prev = c_new[q - p]
c_new.append(prev - c[q - p] + c[q + p*(m-1)])
b_check = sum([hash_elem(elem) for elem in b])
ans1 = 0
ans = []
for q in range(n - (m-1)*p):
c_check = c_new[q]
if b_check != c_check:
continue
else:
ans1 += 1
ans.append(q+1)
print(ans1)
stdout.write(' '.join([str(x) for x in ans]))
``` | output | 1 | 37,163 | 12 | 74,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.
Sereja needs to rush to the gym, so he asked to find all the described positions of q.
Input
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
Output
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
Examples
Input
5 3 1
1 2 3 2 1
1 2 3
Output
2
1 3
Input
6 3 2
1 3 2 2 3 1
1 2 3
Output
2
1 2 | instruction | 0 | 37,164 | 12 | 74,328 |
Tags: binary search, data structures
Correct Solution:
```
from sys import stdin, stdout
from math import log, sqrt
lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
hash_map = {}
def hash_elem(elem):
if hash_map.get(elem, -1) == -1:
# elem = int(elem * 1662634645)
# elem = int((elem >> 13) + (elem << 19))
# hash_map[elem] = int(elem * 361352451)
# hash_map[elem] = int(342153534 + elem + (elem >> 5) + (elem >> 13) + (elem << 17))
if elem < 1000:
hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7 + int(log(elem)) + int(sqrt(elem)) + elem&213213 + elem^324234211323 + elem|21319423094023
else:
hash_map[elem] = 3 + elem^34
return elem + hash_map[elem]
c = [hash_elem(elem) for elem in a]
c_new = [sum([c[q + p * i] for i in range(m)]) for q in range(min(p, max(0, n - (m - 1) * p)))]
for q in range(p, n - (m - 1) * p):
prev = c_new[q - p]
# print(len(c_new)-1, q, q + p*(m-1))
c_new.append(prev - c[q - p] + c[q + p * (m - 1)])
b_check = sum([hash_elem(elem) for elem in b])
ans1 = 0
ans = []
for q in range(n - (m - 1) * p):
c_check = c_new[q]
if b_check != c_check:
continue
else:
ans1 += 1
ans.append(q + 1)
print(ans1)
stdout.write(' '.join([str(x) for x in ans]))
``` | output | 1 | 37,164 | 12 | 74,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Sereja has two sequences a and b and number p. Sequence a consists of n integers a1, a2, ..., an. Similarly, sequence b consists of m integers b1, b2, ..., bm. As usual, Sereja studies the sequences he has. Today he wants to find the number of positions q (q + (m - 1)·p ≤ n; q ≥ 1), such that sequence b can be obtained from sequence aq, aq + p, aq + 2p, ..., aq + (m - 1)p by rearranging elements.
Sereja needs to rush to the gym, so he asked to find all the described positions of q.
Input
The first line contains three integers n, m and p (1 ≤ n, m ≤ 2·105, 1 ≤ p ≤ 2·105). The next line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 109). The next line contains m integers b1, b2, ..., bm (1 ≤ bi ≤ 109).
Output
In the first line print the number of valid qs. In the second line, print the valid values in the increasing order.
Examples
Input
5 3 1
1 2 3 2 1
1 2 3
Output
2
1 3
Input
6 3 2
1 3 2 2 3 1
1 2 3
Output
2
1 2
Submitted Solution:
```
from sys import stdin, stdout
lines = stdin.readlines()
n = int(lines[0].split()[0])
m = int(lines[0].split()[1])
p = int(lines[0].split()[2])
a = [int(x) for x in lines[1].split()]
b = [int(x) for x in lines[2].split()]
hash_map = {}
def hash_elem(elem):
if hash_map.get(elem, -1) == -1:
hash_map[elem] = elem//2 + elem * 1134234546677 + int(elem/3) + int(elem**2) + elem<<2 + elem>>7
return elem + hash_map[elem]
c = [hash_elem(elem) for elem in a]
c_new = [sum([c[q + p*i] for i in range(m)]) for q in range(p)]
for q in range(p,n - (m-1)*p):
prev = c_new[q - p]
# print(len(c_new)-1, q, q + p*(m-1))
c_new.append(prev - c[q - p] + c[q + p*(m-1)])
b_check = sum([hash_elem(elem) for elem in b])
ans1 = 0
ans = []
for q in range(n - (m-1)*p):
c_check = c_new[q]
if b_check != c_check:
continue
else:
ans1 += 1
ans.append(q+1)
print(ans1)
stdout.write(' '.join([str(x) for x in ans]))
``` | instruction | 0 | 37,166 | 12 | 74,332 |
No | output | 1 | 37,166 | 12 | 74,333 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A student of z-school found a kind of sorting called z-sort. The array a with n elements are z-sorted if two conditions hold:
1. ai ≥ ai - 1 for all even i,
2. ai ≤ ai - 1 for all odd i > 1.
For example the arrays [1,2,1,2] and [1,1,1,1] are z-sorted while the array [1,2,3,4] isn’t z-sorted.
Can you make the array z-sorted?
Input
The first line contains a single integer n (1 ≤ n ≤ 1000) — the number of elements in the array a.
The second line contains n integers ai (1 ≤ ai ≤ 109) — the elements of the array a.
Output
If it's possible to make the array a z-sorted print n space separated integers ai — the elements after z-sort. Otherwise print the only word "Impossible".
Examples
Input
4
1 2 2 1
Output
1 2 1 2
Input
5
1 3 2 2 5
Output
1 5 2 3 2 | instruction | 0 | 37,291 | 12 | 74,582 |
Tags: sortings
Correct Solution:
```
n = int(input())
val = list(map(int, input().split()))
res = [0] * n
val = sorted(val)
for i in range(1, n + 1):
if i & 1:
res[i - 1] = val[i // 2]
else:
res[i - 1] = val[n - (i // 2)]
print(*res)
``` | output | 1 | 37,291 | 12 | 74,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.