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 an array of integers b_1, b_2, …, b_n.
An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true:
* b_i = a_i, or
* b_i = ∑_{j=1}^{i} a_j.
Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of each test case contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9).
It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print a single integer: the number of hybrid arrays a_1, a_2, …, a_n modulo 10^9 + 7.
Example
Input
4
3
1 -1 1
4
1 2 3 4
10
2 -1 1 -2 2 3 -5 0 2 -1
4
0 0 0 1
Output
3
8
223
1
Note
In the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1].
In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4].
In the fourth test case, the only hybrid array is [0, 0, 0, 1].
Submitted Solution:
```
# Author: yumtam
# Created at: 2021-03-21 08:55
def solve():
MOD = 10**9 + 7
n = int(input())
a = [int(t) for t in input().split()]
p = [1]
q = [0]
psums = {0: 0}
s = 0
for i in range(n):
s += a[i]
if s in psums:
j = psums[s]
x = (p[j] + q[j]) % MOD
else:
x = 0
psums[s] = i+1
p.append(x)
q.append((p[i] + q[i]*2 - x) % MOD)
print((p[-1] + q[-1]) % MOD)
import sys, os, io
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
for _ in range(int(input())):
solve()
os.write(1, stdout.getvalue())
``` | instruction | 0 | 53,312 | 12 | 106,624 |
Yes | output | 1 | 53,312 | 12 | 106,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array of integers b_1, b_2, …, b_n.
An array a_1, a_2, …, a_n of integers is hybrid if for each i (1 ≤ i ≤ n) at least one of these conditions is true:
* b_i = a_i, or
* b_i = ∑_{j=1}^{i} a_j.
Find the number of hybrid arrays a_1, a_2, …, a_n. As the result can be very large, you should print the answer modulo 10^9 + 7.
Input
The first line contains a single integer t (1 ≤ t ≤ 10^4) — the number of test cases.
The first line of each test case contains a single integer n (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of each test case contains n integers b_1, b_2, …, b_n (-10^9 ≤ b_i ≤ 10^9).
It is guaranteed that the sum of n for all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print a single integer: the number of hybrid arrays a_1, a_2, …, a_n modulo 10^9 + 7.
Example
Input
4
3
1 -1 1
4
1 2 3 4
10
2 -1 1 -2 2 3 -5 0 2 -1
4
0 0 0 1
Output
3
8
223
1
Note
In the first test case, the hybrid arrays are [1, -2, 1], [1, -2, 2], [1, -1, 1].
In the second test case, the hybrid arrays are [1, 1, 1, 1], [1, 1, 1, 4], [1, 1, 3, -1], [1, 1, 3, 4], [1, 2, 0, 1], [1, 2, 0, 4], [1, 2, 3, -2], [1, 2, 3, 4].
In the fourth test case, the only hybrid array is [0, 0, 0, 1].
Submitted Solution:
```
"""
Author - Satwik Tiwari .
7th Feb , 2021 - Sunday
"""
#===============================================================================================
#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,log2
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 ;))
def solve(case):
n = int(inp())
b = lis()
dp = [0]*(n+1)
dp[0] = 1
help = [0]*(n+1)
if(b[0] == 0): help[0] = 1
curr = b[0]
pref = {0: 0, curr: 0}
for i in range(1,n):
curr += b[i]
dp[i] = 2*dp[i-1]
dp[i] -= help[i-1]
dp[i] %= mod
if(curr in pref):
help[i] = dp[pref[curr]]
pref[curr] = i
print(dp[n-1]%mod)
# testcase(1)
testcase(int(inp()))
``` | instruction | 0 | 53,313 | 12 | 106,626 |
Yes | output | 1 | 53,313 | 12 | 106,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,379 | 12 | 106,758 |
Tags: implementation
Correct Solution:
```
#!/usr/bin/env python3
n, m = map(int, input().split())
a = input().split().count('1')
b = min(a, n - a) * 2
ans = []
for i in range(m):
l, r = map(int, input().split())
length = r - l + 1
ans += ['0'] if length % 2 or length > b else ['1']
print('\n'.join(ans))
``` | output | 1 | 53,379 | 12 | 106,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,380 | 12 | 106,760 |
Tags: implementation
Correct Solution:
```
from sys import stdin,stdout
n,m = map(int,stdin.readline().split())
a = list(map(int,stdin.readline().split()))
neg_count = 0
pos_count = 0
for i in a:
if i == -1:
neg_count += 1
else:
pos_count += 1
for i in range(m):
l,r = map(int,stdin.readline().split())
if l == r:
stdout.write("0" + "\n")
else:
if (r-l +1) % 2 != 0 or neg_count < (r-l +1)//2 or pos_count < (r-l +1)//2:
stdout.write("0" + "\n")
else:
stdout.write("1" + "\n")
``` | output | 1 | 53,380 | 12 | 106,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,381 | 12 | 106,762 |
Tags: implementation
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
def mints():
return map(int, minp().split())
def solve():
n, m = mints()
a = list(mints())
ones = a.count(1)
mones = n-ones
for i in range(m):
l, r = mints()
c = r-l+1
if c % 2 == 1:
print(0)
elif c//2 <= ones and c//2 <= mones:
print(1)
else:
print(0)
solve()
``` | output | 1 | 53,381 | 12 | 106,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,382 | 12 | 106,764 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a_plus = input().split().count('1')
a_min = min(a_plus, n - a_plus) * 2
res = []
for i in range(m):
l, r = map(int, input().split())
length = r - l + 1
res.append('0' if length % 2 or length > a_min else '1')
print('\n'.join(res))
``` | output | 1 | 53,382 | 12 | 106,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,383 | 12 | 106,766 |
Tags: implementation
Correct Solution:
```
n,m=map(int, input().split())
a=input().split()
d=a.count("-1")
d=min(d, n-d)
s=""
for i in range(m):
l,r=map(int,input().split())
if (r-l)% 2==1 and d>=(r-l+1)//2:
s+="1\n"
else:
s+="0\n"
print(s)
``` | output | 1 | 53,383 | 12 | 106,767 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,384 | 12 | 106,768 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
a_plus = a.count(1)
a_min = min(a_plus, n - a_plus)
res = []
for i in range(m):
l, r = map(int, input().split())
length = r - l + 1
res += ['0'] if length % 2 or length // 2 > a_min else ['1']
print('\n'.join(res))
``` | output | 1 | 53,384 | 12 | 106,769 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,385 | 12 | 106,770 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
a_plus = a.count(1)
a_minus = a.count(-1)
s = ''
for i in range(m):
l, r = map(int, input().split())
length = r - l + 1
s += '0\n' if length % 2 or length // 2 > a_plus or length // 2 > a_minus else '1\n'
print(s)
``` | output | 1 | 53,385 | 12 | 106,771 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0 | instruction | 0 | 53,386 | 12 | 106,772 |
Tags: implementation
Correct Solution:
```
n, m = map(int, input().split())
a = input().split()
x = a.count("-1")
x = min(x, n-x)
ans = ""
for _ in range(m):
l, r = map(int, input().split())
if (r-l) % 2 == 1 and x >= (r-l+1)//2:
ans += "1\n"
else:
ans += "0\n"
print(ans)
``` | output | 1 | 53,386 | 12 | 106,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Eugeny has array a = a1, a2, ..., an, consisting of n integers. Each integer ai equals to -1, or to 1. Also, he has m queries:
* Query number i is given as a pair of integers li, ri (1 ≤ li ≤ ri ≤ n).
* The response to the query will be integer 1, if the elements of array a can be rearranged so as the sum ali + ali + 1 + ... + ari = 0, otherwise the response to the query will be integer 0.
Help Eugeny, answer all his queries.
Input
The first line contains integers n and m (1 ≤ n, m ≤ 2·105). The second line contains n integers a1, a2, ..., an (ai = -1, 1). Next m lines contain Eugene's queries. The i-th line contains integers li, ri (1 ≤ li ≤ ri ≤ n).
Output
Print m integers — the responses to Eugene's queries in the order they occur in the input.
Examples
Input
2 3
1 -1
1 1
1 2
2 2
Output
0
1
0
Input
5 5
-1 1 1 1 -1
1 1
2 3
3 5
2 5
1 5
Output
0
1
0
1
0
Submitted Solution:
```
n,m = map(int,input().split())
k = list(map(int,input().split()))
hash = {
-1: 0,
1:0,
}
for i in k:
if i == -1:
hash[-1]+=1
else:
hash[1]+=1
print(hash)
for i in range(m):
m1,m2 = map(int,input().split())
if abs(m2 - m1 + 1) % 2 ==0:
m1 = m1 - 1
m2 = m2 - 1
count1 = 0
count_1 = 0
for j in range(m1,m2+1):
if k[j] == 1:
count1+=1
else:
count_1+=1
# print(count1,count_1)
z = (count1 + count_1)//2
if z <=hash[1] and z <= hash[-1]:
print(1)
else:
print(0)
# if count1 == count_1:
# print(1)
# elif count1 > count_1:
#
# if hash[-1] >=count1:
# print(1)
# else:
# print(0)
# elif count1 < count_1:
#
# if hash[1] >=count_1:
# print(1)
# else:
# print(0)
else:
print(0)
``` | instruction | 0 | 53,392 | 12 | 106,784 |
No | output | 1 | 53,392 | 12 | 106,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,454 | 12 | 106,908 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
from random import randint
n, k = map(int, input().split())
perm = list(map(int, input().split()))
moves = []
for i in range(n):
for j in range(i, n):
moves.append((i, j))
def go(p, cnt):
if cnt == k:
ret = 0
for i in range(n):
for j in range(i + 1, n):
if p[j] < p[i]:
ret += 1
return ret
ans = 0
for move in moves:
fr, to = move
nx = p[fr:to + 1]
ans += go(p[:fr] + nx[::-1] + p[to + 1:], cnt + 1)
return ans
print(go(perm, 0) / pow(len(moves) * 1.0, k))
``` | output | 1 | 53,454 | 12 | 106,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,455 | 12 | 106,910 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
n, k = map(int, input().split())
p = list(map(int, input().split()))
def count_invs(a):
ans = 0
for i in range(n-1):
for j in range(i + 1, n):
if a[i] > a[j]:
ans += 1
return ans
def inv_in_perms(a, count):
if count > 0:
ans = 0
for l in range(n):
for r in range(l, n):
a[l: r + 1] = a[l: r + 1][::-1]
ans += inv_in_perms(a, count - 1)
a[l: r + 1] = a[l: r + 1][::-1]
return(ans)
else:
return(count_invs(a))
total = (n * (n + 1) // 2) ** k
perms = 0
print(inv_in_perms(p, k) / total)
``` | output | 1 | 53,455 | 12 | 106,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,456 | 12 | 106,912 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
def ofsum(num):
num2 = 0
for i in range(num+1):
num2+=i
return num2
def strspace(k):
spaces = 11 - len(str(k)) + len(str(int(k)))
return str(k)+'0' * spaces
def inversion(array):
num = 0
z = len(array)
for i in range(z):
for j in range(i+1,z):
if array[i] > array[j]:
num += 1
return num
def reversede(array):
z = len(array)
for i in range(len(array)//2):
temp = array [i]
array[i] = array[z-i-1]
array[z-i-1] = temp
return array
n, k = map(int,input().split())
pn = list(map(int,input().split()))
const = 10000 / float(ofsum(n)**k)
answer = 0
if k ==1:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
answer += inversion(pn2) * const
elif k ==2:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i1,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
answer += inversion(pn3) * const
elif k == 3:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i1,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
for i2 in range(n):
for j2 in range(i2,n):
pn4 = pn3[:i2]+reversede(pn3[i2:j2+1])+pn3[j2+1:]
answer += inversion(pn4) * const
elif k == 4:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i1,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
for i2 in range(n):
for j2 in range(i2,n):
pn4 = pn3[:i2]+reversede(pn3[i2:j2+1])+pn3[j2+1:]
for i3 in range(n):
for j3 in range(i3,n):
pn5 = pn4[:i3]+reversede(pn4[i3:j3+1])+pn4[j3+1:]
answer += inversion(pn5) * const
print(answer/10000)
``` | output | 1 | 53,456 | 12 | 106,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,457 | 12 | 106,914 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
#! /usr/bin/env python3
import bisect
def memo(f):
def _f(*args):
try:
return cache[args]
except KeyError:
data = cache[args] = f(*args)
return data
cache = {}
return _f
def count_inversions(nums):
invs = 0
for i, lnum in enumerate(nums):
for rnum in nums[i+1:]:
if lnum > rnum:
invs += 1
return invs
def search(depth, nums):
if depth >= max_depth:
return count_inversions(nums), 1
else:
invs = total = 0
depth += 1
for i in range(length):
for j in range(i + 1, length + 1):
nums[i:j] = nums[i:j][::-1]
invs, total = map(sum, zip(search(depth, nums), (invs, total)))
nums[i:j] = nums[i:j][::-1]
return invs, total
length, max_depth = map(int, input().split())
nums = list(map(int, input().split()))
invs, total = search(0, nums)
print(invs / total)
``` | output | 1 | 53,457 | 12 | 106,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,458 | 12 | 106,916 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
#! /usr/bin/env python3
def memo(f):
def _f(*args):
key = str(args)
try:
return cache[key]
except KeyError:
data = cache[key] = f(*args)
return data
cache = {}
return _f
def count_inversions(lo, hi):
if hi - lo <= 1:
return 0, nums[lo:hi]
mid = (lo + hi) // 2
invs, (nums1, nums2) = zip(count_inversions(lo, mid), count_inversions(mid, hi))
invs = sum(invs)
new_nums = []
i1 = i2 = 0
l1, l2 = map(len, (nums1, nums2))
for _ in range(l1 + l2):
if i1 == l1:
new_nums.append(nums2[i2])
i2 += 1
elif i2 == l2:
new_nums.append(nums1[i1])
i1 += 1
elif nums1[i1] <= nums2[i2]:
new_nums.append(nums1[i1])
i1 += 1
else:
new_nums.append(nums2[i2])
i2 += 1
invs += l1 - i1
return invs, new_nums
# def count_inversions(lo, hi):
# invs = 0
# for i in range(len(nums)):
# for j in range(i, len(nums)):
# if nums[i] > nums[j]:
# invs += 1
# return invs, 0
@memo
def search(depth, nums):
if depth >= max_depth:
invs, _ = count_inversions(0, len(nums))
return invs, 1
else:
invs = total = 0
depth += 1
for i in range(length):
for j in range(i + 1, length + 1):
nums[i:j] = nums[i:j][::-1]
invs, total = map(sum, zip(search(depth, nums), (invs, total)))
nums[i:j] = nums[i:j][::-1]
return invs, total
MAX = 1e9
length, max_depth = map(int, input().split())
nums = list(map(int, input().split()))
invs, total = search(0, nums)
print(invs / total)
``` | output | 1 | 53,458 | 12 | 106,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,459 | 12 | 106,918 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
import sys
TESTING = False
def reverse(a, l, r):
res = list(a)
while l < r:
res[l], res[r] = res[r], res[l]
l+=1
r-=1
return res
def inversions(a):
res = 0
for l in range(len(a)):
for r in range(l+1, len(a)):
if a[l] > a[r]: res+=1
return res
def solve():
n, k = read()
a = read()
al = list()
al.append(list(a))
for kk in range(k):
newal = list()
for val in al:
for l in range(n):
for r in range(l, n):
newal.append(reverse(val, l, r))
al = newal;
res = 0;
for val in al:
res += inversions(val)
return res/len(al)
def read(mode=2):
inputs = input().strip()
if mode == 0: return inputs # String
if mode == 1: return inputs.split() # List of strings
if mode == 2: return list(map(int, inputs.split())) # List of integers
def write(s="\n"):
if s is None: s = ""
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
def run():
if TESTING: sys.stdin = open("test.txt")
res = solve()
write(res)
run()
``` | output | 1 | 53,459 | 12 | 106,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,460 | 12 | 106,920 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
def f(p):
ans = 0
for i in range(len(p)):
for j in range(i, len(p)):
if (p[i] > p[j]):
ans += 1
return ans
n, k = map(int, input().split())
p = list(map(int, input().split()))
num = 0
cnt = 0
if k == 1:
tmp = []
for i in range(n):
for j in range(i+1):
tmp = p[0:j] + list(reversed(p[j:i+1])) + p[i+1::]
num += 1
cnt += f(tmp)
elif k == 2:
tmp1 = []
tmp2 = []
for i in range(n):
for j in range(i+1):
tmp1 = p[0:j] + list(reversed(p[j:i+1])) + p[i+1::]
for i1 in range(n):
for j1 in range(i1+1):
tmp2 = tmp1[0:j1] + list(reversed(tmp1[j1:i1+1])) + tmp1[i1+1::]
num += 1
cnt += f(tmp2)
elif k == 3:
tmp1 = []
tmp2 = []
tmp3 = []
for i in range(n):
for j in range(i+1):
tmp1 = p[0:j] + list(reversed(p[j:i+1])) + p[i+1::]
for i1 in range(n):
for j1 in range(i1+1):
tmp2 = tmp1[0:j1] + list(reversed(tmp1[j1:i1+1])) + tmp1[i1+1::]
for i2 in range(n):
for j2 in range(i2+1):
num += 1
tmp3 = tmp2[0:j2] + list(reversed(tmp2[j2:i2+1])) + tmp2[i2+1::]
cnt += f(tmp3)
elif k == 4:
tmp1 = []
tmp2 = []
tmp3 = []
tmp4 = []
for i in range(n):
for j in range(i+1):
tmp1 = p[0:j] + list(reversed(p[j:i+1])) + p[i+1::]
for i1 in range(n):
for j1 in range(i1+1):
tmp2 = tmp1[0:j1] + list(reversed(tmp1[j1:i1+1])) + tmp1[i1+1::]
for i2 in range(n):
for j2 in range(i2+1):
tmp3 = tmp2[0:j2] + list(reversed(tmp2[j2:i2+1])) + tmp2[i2+1::]
for i3 in range(n):
for j3 in range(i3+1):
tmp4 = tmp3[0:j3] + list(reversed(tmp3[j3:i3+1])) + tmp3[i3+1::]
num += 1
cnt += f(tmp4)
print(cnt/num)
``` | output | 1 | 53,460 | 12 | 106,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a permutation of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>. | instruction | 0 | 53,461 | 12 | 106,922 |
Tags: brute force, dfs and similar, dp, meet-in-the-middle
Correct Solution:
```
f = lambda: map(int, input().split())
n, k = f()
p = list(f())
r = range
u = [l * l + l >> 1 for l in r(n + 1)]
v = [(i, j) for i in r(n) for j in r(i + 1, n)]
t = [[p[i] > p[j] for j in r(n)] for i in r(n)]
a = [[0] * n for i in r(n)]
b = [[0] * n for i in r(n)]
c = [[0] * n for i in r(n)]
for l in r(min(k, 1000)):
for j in r(1, n):
s, x = 0, a[j]
for i in r(j):
s += t[i][j]
x[i + 1] = x[i] + s
for i in r(n):
s, y = 0, b[i]
for j in r(n - 1, i, -1):
s += t[i][j]
y[j - 1] = y[j] + s
for d in r(1, n):
s, z = 0, c[d]
for i in r(n - d):
s += t[i][i + d]
z[i + 1] = z[i] + s
for i, j in v:
d = j - i
x, y, z = a[j], b[i], c[d]
s = t[i][j] * (u[i] + u[d - 1] + u[n - j - 1])
s += x[j] - x[i] - x[d - 1]
s += y[i] - y[j] - y[n - d]
s += (i + 1) * (n - j) - z[n - d] + z[n - j - 1] + z[i]
t[i][j] = s / u[n]
print(sum(t[i][j] for i, j in v))
``` | output | 1 | 53,461 | 12 | 106,923 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
def genrevs(n):
ans = []
for l in range(n):
for r in range(l, n):
ans.append((l, r))
return ans
def cnt_rev(p):
n = len(p)
ans = 0
for i in range(n):
for j in range(i + 1, n):
if p[i] > p[j]:
ans += 1
return ans
def repl(l, r):
global p
for c in range((r - l + 1) // 2):
p[l + c], p[r - c] = p[r - c], p[l + c]
n, k = map(int, input().split())
p = list(map(int, input().split()))
rev = genrevs(n)
lr = len(rev)
tr = []
ans = 0
if k == 1:
for i in range(lr):
repl(rev[i][0], rev[i][1])
ans += cnt_rev(p)
repl(rev[i][0], rev[i][1])
print(ans / lr)
if k == 2:
for k1 in range(lr):
repl(rev[k1][0], rev[k1][1])
for k2 in range(lr):
repl(rev[k2][0], rev[k2][1])
ans += cnt_rev(p)
repl(rev[k2][0], rev[k2][1])
repl(rev[k1][0], rev[k1][1])
print(ans / (lr ** 2))
if k == 3:
for k1 in range(lr):
repl(rev[k1][0], rev[k1][1])
for k2 in range(lr):
repl(rev[k2][0], rev[k2][1])
for k3 in range(lr):
repl(rev[k3][0], rev[k3][1])
ans += cnt_rev(p)
repl(rev[k3][0], rev[k3][1])
repl(rev[k2][0], rev[k2][1])
repl(rev[k1][0], rev[k1][1])
print(ans / (lr ** 3))
if k == 4:
for k1 in range(lr):
repl(rev[k1][0], rev[k1][1])
for k2 in range(lr):
repl(rev[k2][0], rev[k2][1])
for k3 in range(lr):
repl(rev[k3][0], rev[k3][1])
for k4 in range(lr):
repl(rev[k4][0], rev[k4][1])
ans += cnt_rev(p)
repl(rev[k4][0], rev[k4][1])
repl(rev[k3][0], rev[k3][1])
repl(rev[k2][0], rev[k2][1])
repl(rev[k1][0], rev[k1][1])
print(ans / (lr ** 4))
``` | instruction | 0 | 53,462 | 12 | 106,924 |
Yes | output | 1 | 53,462 | 12 | 106,925 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
from sys import stdin, stdout
from math import *
from itertools import *
from copy import *
s = 0
invs = 0
def calc_invertions(a):
s = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
s += 1 if a[i] > a[j] else 0
return s
def do_flips(arr, num):
global s, invs
if num == 0:
invs += 1
s += calc_invertions(arr)
else:
for i in range(len(arr)):
for j in range(i, len(arr)):
for k in range((j - i + 1) // 2):
arr[i + k], arr[j - k] = arr[j - k], arr[i + k]
do_flips(arr, num - 1)
for k in range((j - i + 1) // 2):
arr[i + k], arr[j - k] = arr[j - k], arr[i + k]
def solve(test):
ints = list(map(int, test.strip().split()))
n, m = ints[:2]
arr = ints[2:]
do_flips(arr, m)
return s / invs
stdout.write(str(solve(stdin.read())))
``` | instruction | 0 | 53,463 | 12 | 106,926 |
Yes | output | 1 | 53,463 | 12 | 106,927 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
import operator
import itertools
def count_inversions(ns):
return sum(itertools.starmap(operator.gt, itertools.combinations(ns, 2)))
def rotate(ns, l, r):
return ns[:l] + ns[l:r + 1][::-1] + ns[r + 1:]
def rotate_times(ns, k):
if k == 0:
yield ns
else:
for l, r in itertools.combinations_with_replacement(range(len(ns)), 2):
yield from rotate_times(rotate(ns, l, r), k - 1)
n, k = map(int, str.split(input()))
ns = tuple(map(int, str.split(input())))
inv = tuple(map(count_inversions, rotate_times(ns, k)))
print(sum(inv) / len(inv))
``` | instruction | 0 | 53,464 | 12 | 106,928 |
Yes | output | 1 | 53,464 | 12 | 106,929 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
f = lambda: map(int, input().split())
g = lambda k: k * k - k >> 1
n, k = f()
p = list(f())
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
if p[i] > p[j]: a[i][j] = 1
else: a[j][i] = 1
for t in range(k):
b = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
p = q = 0
for x in range(j):
d = min(i + 1, j - x, x + 1, j - i)
p += d * a[x][j]
q += d
for y in range(i + 1, n):
d = min(n - j, y - i, n - y, j - i)
p += d * a[i][y]
q += d
for s in range(j, i + n):
x, y = s - i, s - j
d = min(i + 1, n - j, y + 1, n - x)
p += d * a[x][y]
q += d
d = g(j - i) + g(i + 1) + g(n - j)
b[i][j] = (p + d * a[i][j]) / (d + q)
a = b
for i in range(n):
for j in range(i + 1, n):
a[j][i] = 1 - a[i][j]
s = 0
for i in range(n):
for j in range(i + 1, n): s += a[i][j]
print(s)
``` | instruction | 0 | 53,465 | 12 | 106,930 |
Yes | output | 1 | 53,465 | 12 | 106,931 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
def inv(array):
length = len(array)
midpoint = int(length / 2)
inversions = 0
if length == 1:
return inversions, array
else:
leftInv, left = inv(array[:midpoint])
rightInv, right = inv(array[midpoint:])
inversions += (leftInv + rightInv)
lenLeft = len(left)
lenRight = len(right)
j = k = 0
mergedArray = []
for i in range(0, length):
if j != lenLeft and k != lenRight:
if left[j] <= right[k]:
mergedArray.append(left[j])
j += 1
else:
mergedArray.append(right[k])
k += 1
# Increment inversion count
if j != lenLeft:
inversions += lenLeft - j
elif j == lenLeft:
mergedArray.append(right[k])
k += 1
elif k == lenRight:
mergedArray.append(left[j])
j += 1
return inversions, mergedArray
def invert(a, x, y):
god = a[x:y+1]
god.reverse()
return a[:x] + god + a[y+1:]
n, k = map(int, input().split(' '))
x = list(map(int, input().split(' ')))
if n == 1:
print(1)
if n == 2:
if x == [1, 2] and k == 1:
print(1/3)
elif x == [2, 1] and k == 1:
print(2/3)
if x == [1, 2] and k == 2:
print(4/9)
elif x == [2, 1] and k == 2:
print(5/9)
if x == [1, 2] and k == 3:
print(13/27)
elif x == [2, 1] and k == 3:
print(13/27)
if x == [1, 2] and k == 4:
print(41/81)
elif x == [2, 1] and k == 4:
print(40/81)
if n == 3:
def dp0(k):
if k == 1:
return 5/6
return 1/2*dp0(k-1) + 1/6*2*dp1(k-1) + 1/6*dp3(k-1)
def dp1(k):
if k == 1:
return 7/6
return 1/2*dp1(k-1) + 1/6*2*dp2(k-1) + 1/6*dp0(k-1)
def dp2(k):
if k == 1:
return 11/6
return 1/2*dp2(k-1) + 1/6*2*dp1(k-1) + 1/6*dp3(k-1)
def dp3(k):
if k == 1:
return 13/6
return 1/2*dp3(k-1) + 1/6*2*dp2(k-1) + 1/6*dp0(k-1)
if inv(x) == 0:
print(dp0(k))
elif inv(x)==1:
print(dp1(k))
elif inv(x)==2:
print(dp2(k))
else:
print(dp3(k))
if n == 4:
god = []
if k >= 1:
for a in range(0, 4):
for y in range(a, 4):
god.append(invert(x, a, y))
if k == 1:
print(sum([inv(x)[0] for x in god])/10)
if k >= 2:
god2 = []
for x in god:
for a in range(0, 4):
for y in range(a, 4):
god2.append(invert(x, a, y))
if k == 2:
print(sum([inv(x)[0] for x in god2])/100)
if k >= 3:
god3 = []
for x in god2:
for a in range(0, 4):
for y in range(a, 4):
god3.append(invert(x, a, y))
if k == 3:
print(sum([inv(x)[0] for x in god3])/1000)
if k == 4:
god4 = []
for x in god3:
for a in range(0, 4):
for y in range(a, 4):
god4.append(invert(x, a, y))
if k == 4:
print(sum([inv(x)[0] for x in god4])/10000)
if n == 5:
god = []
if k >= 1:
for a in range(0, 5):
for y in range(a, 5):
god.append(invert(x, a, y))
if k == 1:
print(sum([inv(x)[0] for x in god])/15)
if k >= 2:
god2 = []
for x in god:
for a in range(0, 5):
for y in range(a, 5):
god2.append(invert(x, a, y))
if k == 2:
print(sum([inv(x)[0] for x in god2])/15*15)
if k >= 3:
god3 = []
for x in god2:
for a in range(0, 5):
for y in range(a, 5):
god3.append(invert(x, a, y))
if k == 3:
print(sum([inv(x)[0] for x in god3])/15*15*15)
if k == 4:
god4 = []
for x in god3:
for a in range(0, 5):
for y in range(a, 5):
god4.append(invert(x, a, y))
if k == 4:
print(sum([inv(x)[0] for x in god4])/15/15/15/15)
``` | instruction | 0 | 53,466 | 12 | 106,932 |
No | output | 1 | 53,466 | 12 | 106,933 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
from sys import stdin, stdout
from math import *
from itertools import *
from copy import *
s = 0
invs = 0
def calc_invertions(a):
s = 0
for i in range(len(a)):
for j in range(i + 1, len(a)):
s += 1 if a[i] > a[j] else 0
return s
def do_flips(arr, num):
global s, invs
if num == 0:
invs += 1
s += calc_invertions(arr)
else:
for i in range(len(arr)):
for j in range(i, len(arr)):
arr[i], arr[j] = arr[j], arr[i]
do_flips(arr, num - 1)
arr[i], arr[j] = arr[j], arr[i]
def solve(test):
ints = list(map(int, test.strip().split()))
n, m = ints[:2]
arr = ints[2:]
do_flips(arr, m)
return s / invs
stdout.write(str(solve(stdin.read())))
``` | instruction | 0 | 53,467 | 12 | 106,934 |
No | output | 1 | 53,467 | 12 | 106,935 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
f = lambda: map(int, input().split())
g = lambda k: k * k - k >> 1
n, k = f()
p = tuple(f())
a = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
if p[i] > p[j]:
a[i][j] = 1
else:
a[j][i] = 1
for t in range(k):
b = [[0] * n for i in range(n)]
for i in range(n):
for j in range(i + 1, n):
p = q = 0
for s in range(j):
d = min(i + 1, j - s, j - i)
p += d * a[s][j]
q += d
for s in range(i + 1, n):
d = min(n - j, s - i, j - i)
p += d * a[i][s]
q += d
for s in range(j, i + n):
x, y = s - i, s - j
d = min(i + 1, n - j, y + 1, n - x)
p += d * a[x][y]
q += d
d = g(j - i) + g(i + 1) + g(n - j)
b[i][j] = (p + d * a[i][j]) / (d + q)
a = b
for i in range(n):
for j in range(i + 1, n):
a[j][i] = 1 - a[i][j]
s = 0
for i in range(n):
for j in range(i + 1, n): s += a[i][j]
print(s)
``` | instruction | 0 | 53,468 | 12 | 106,936 |
No | output | 1 | 53,468 | 12 | 106,937 |
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 of n numbers p1, p2, ..., pn. We perform k operations of the following type: choose uniformly at random two indices l and r (l ≤ r) and reverse the order of the elements pl, pl + 1, ..., pr. Your task is to find the expected value of the number of inversions in the resulting permutation.
Input
The first line of input contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 109). The next line contains n integers p1, p2, ..., pn — the given permutation. All pi are different and in range from 1 to n.
The problem consists of three subproblems. The subproblems have different constraints on the input. You will get some score for the correct submission of the subproblem. The description of the subproblems follows.
* In subproblem G1 (3 points), the constraints 1 ≤ n ≤ 6, 1 ≤ k ≤ 4 will hold.
* In subproblem G2 (5 points), the constraints 1 ≤ n ≤ 30, 1 ≤ k ≤ 200 will hold.
* In subproblem G3 (16 points), the constraints 1 ≤ n ≤ 100, 1 ≤ k ≤ 109 will hold.
Output
Output the answer with absolute or relative error no more than 1e - 9.
Examples
Input
3 1
1 2 3
Output
0.833333333333333
Input
3 4
1 3 2
Output
1.458333333333334
Note
Consider the first sample test. We will randomly pick an interval of the permutation (1, 2, 3) (which has no inversions) and reverse the order of its elements. With probability <image>, the interval will consist of a single element and the permutation will not be altered. With probability <image> we will inverse the first two elements' order and obtain the permutation (2, 1, 3) which has one inversion. With the same probability we might pick the interval consisting of the last two elements which will lead to the permutation (1, 3, 2) with one inversion. Finally, with probability <image> the randomly picked interval will contain all elements, leading to the permutation (3, 2, 1) with 3 inversions. Hence, the expected number of inversions is equal to <image>.
Submitted Solution:
```
def ofsum(num):
num2 = 0
for i in range(num+1):
num2+=i
return num2
def strspace(k):
spaces = 11 - len(str(k)) + len(str(int(k)))
return str(k)+'0' * spaces
def inversion(array):
num = 0
z = len(array)
for i in range(z):
for j in range(i+1,z):
if array[i] > array[j]:
num += 1
return num
def reversede(array):
z = len(array)
for i in range(len(array)//2):
temp = array [i]
array[i] = array[z-i-1]
array[z-i-1] = temp
return array
n, k = map(int,input().split())
pn = list(map(int,input().split()))
const = 10000 / float(ofsum(n)**k)
answer = 0
if k ==1:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
answer += inversion(pn2) * const
elif k ==2:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
answer += inversion(pn3) * const
elif k == 3:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
for i2 in range(n):
for j2 in range(i1,n):
pn4 = pn3[:i2]+reversede(pn3[i2:j2+1])+pn3[j2+1:]
answer += inversion(pn4) * const
elif k == 4:
for i in range(n):
for j in range(i,n):
pn2 = pn[:i]+reversede(pn[i:j+1])+pn[j+1:]
for i1 in range(n):
for j1 in range(i1,n):
pn3 = pn2[:i1]+reversede(pn2[i1:j1+1])+pn2[j1+1:]
for i2 in range(n):
for j2 in range(i2,n):
pn4 = pn3[:i2]+reversede(pn3[i2:j2+1])+pn3[j2+1:]
for i3 in range(n):
for j3 in range(i3,n):
pn5 = pn4[:i3]+reversede(pn4[i3:j3+1])+pn4[j3+1:]
answer += inversion(pn5) * const
print(answer/10000)
``` | instruction | 0 | 53,469 | 12 | 106,938 |
No | output | 1 | 53,469 | 12 | 106,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,555 | 12 | 107,110 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
input()
l=sorted(list(map(int,input().split())))
a=l.count(l[0]);b=l.count(l[1]);c=l.count(l[2])
if a>2:
print(a*(a-1)*(a-2)//6)
elif a==1 and b>1:
print(b*(b-1)//2)
else:
print(c)
``` | output | 1 | 53,555 | 12 | 107,111 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,556 | 12 | 107,112 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
n = int(input())
a = input().split()
for i in range(n):
a[i] = int(a[i])
from math import factorial
'''def merge(a,b):
c=[]
a1=0
b1=0
while a1!=len(a) and b1!=len(b):
if a[a1]<b[b1]:
c.append(a[a1])
a1+=1
else:
c.append(b[b1])
b1+=1
c.extend(a[a1:])
c.extend(b[b1:])
return c
def merge_sort(a):
b=len(a)
if b==1:
return a
m=merge_sort(a[:b//2])
n=merge_sort(a[b//2:])
return merge(m,n)'''
def delete(l, n):
for i in range(len(l)):
if l[i] != n:
return l[i:]
def comb(n, k):
return factorial(n) // (factorial(k) * factorial(n - k))
def count(l, n):
mi = l[0]
c = l.count(mi)
if c >= n:
return comb(c, n)
else:
return count(delete(l, mi), n - c)
a.sort()
print(count(a, 3))
'''mi = a[0]
c = a.count(mi)
if c >= 3:
print(comb(c, 3))
elif c == 2:
a = delete(a, mi)
mi = a[0]
c = a.count(mi)
print(c)
elif c == 1:
a = delete(a, mi)
mi = a[0]
c = a.count(mi)
if c == 1:
a = delete(a, mi)
mi = a[0]
c = a.count(mi)
print(c)
elif c == 2:
print(1)
elif c >= 3:
a = delete(a, mi)
mi = a[0]
c = a.count(mi)
print(c * (c - 1) // 2)
'''
``` | output | 1 | 53,556 | 12 | 107,113 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,557 | 12 | 107,114 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
n = int(input())
A = list(map(int, input().split(' '))); A.sort()
ia, ib, ic = 0, 0, 0
while ia < n and A[ia] == A[0]: ia += 1
while (ia+ib) < n and A[ia+ib] == A[1]: ib += 1
while (ia+ib+ic) < n and A[ia+ib+ic] == A[2]: ic += 1
#This works because order of multiplication doesnt matter, ie associative shit
if ib == ic == 0: print(ia*(ia-1)*(ia-2)//6)
elif ic == 0: print(ia*ib*(ib-1)//2)
elif ib == 0: print(ic*ia*(ia-1)//2)
else: print(ia*ib*ic)
``` | output | 1 | 53,557 | 12 | 107,115 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,558 | 12 | 107,116 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
a.sort()
same = 1
while same < 3 and a[2 - same] == a[2]:
same += 1
cnt = 1
i = 3
if same == 1:
while i < n and a[i] == a[2]:
cnt += 1
i += 1
if same == 2:
while i < n and a[i] == a[2]:
cnt += same
same += 1
i += 1
if same == 3:
while i < n and a[i] == a[2]:
cnt += int(same * (same - 1) / 2)
same += 1
i += 1
print(cnt)
``` | output | 1 | 53,558 | 12 | 107,117 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,559 | 12 | 107,118 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
n = int(input())
a = (list(map(int, input().split())))
b = a[:]
a.sort()
a = a[:3]
if a[0] == a[1] and a[1] == a[2]:
ans = (b.count(a[0]) * (b.count(a[0]) - 1) * (b.count(a[0]) - 2)) // 6
elif a[1] == a[2]:
ans = (b.count(a[1]) * (b.count(a[1]) - 1))//2
else:
ans = b.count(a[2])
print(ans)
``` | output | 1 | 53,559 | 12 | 107,119 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,560 | 12 | 107,120 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
n=int(input())
inp=input().split()
l=[]
for val in inp:
l.append(int(val))
l.sort()
count=3
while(count<n and l[count]==l[count-1]):
count+=1
if(l[2]!=l[1]):
print(count-2)
elif(l[2]!=l[0]):
print(((count-1)*(count-2))//2)
else:
print((count*(count-1)*(count-2))//6)
``` | output | 1 | 53,560 | 12 | 107,121 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,561 | 12 | 107,122 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
import sys
input=sys.stdin.readline
from collections import defaultdict as dc
from collections import Counter
from bisect import bisect_right, bisect_left,bisect
import math
from operator import itemgetter
from heapq import heapify, heappop, heappush
n=int(input())
l=sorted(list(map(int,input().split())))
x=l[2]
c=0
for i in l:
if i==x:
c+=1
if l[0]==l[1] and l[0]==l[2]:
print((c*(c-1)*(c-2))//6)
elif l[1]==l[2]:
print(c*(c-1)//2)
else:
print(c)
``` | output | 1 | 53,561 | 12 | 107,123 |
Provide tags and a correct Python 3 solution for this coding contest problem.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices. | instruction | 0 | 53,562 | 12 | 107,124 |
Tags: combinatorics, implementation, math, sortings
Correct Solution:
```
def f(n, r):
if r == 1:
return n
elif r == 2:
return n * (n - 1) // 2
else:
return n * (n - 1) * (n - 2) // 6
n = int(input())
a = list(map(int, input().split()))
dic = {}
for ai in a:
if ai in dic:
dic[ai] += 1
else:
dic[ai] = 1
a = list(sorted(set(a)))
ans = 1
i = 0
cnt = 3
while 0 < cnt:
x = dic[a[i]]
if cnt < x:
ans *= f(x, min(x, cnt))
cnt -= x
i += 1
print(ans)
``` | output | 1 | 53,562 | 12 | 107,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
n = int(input())
A = list(map(int, input().split()))
A.sort()
p = A[0] * A[1] * A[2]
c = 1
for i in range(3, n):
if A[i] == A[2]:
c += 1
else:
break
if A[0] == A[1] == A[2]:
print((c + 2) * (c + 1) * c // 6)
elif A[1] == A[2]:
print((c + 1) * c // 2)
else:
print(c)
``` | instruction | 0 | 53,563 | 12 | 107,126 |
Yes | output | 1 | 53,563 | 12 | 107,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
n = int(input())
ai = list(map(int,input().split()))
ai.sort()
i = ai[0]
j = ai[1]
k = ai[2]
ans = 0
for num in range(2,n):
if k == ai[num]:
ans += 1
if j == k:
if i == j:
num2 = ans
ans = 0
for num in range(1,num2+2):
ans += (num*(num-1))//2
else:
ans = (ans*(ans+1))//2
print(ans)
``` | instruction | 0 | 53,564 | 12 | 107,128 |
Yes | output | 1 | 53,564 | 12 | 107,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
a.sort()
fir = a.count(a[0])
sec = a.count(a[1])
th = a.count(a[2])
if a[0] == a[1] and a[1] == a[2]:
print(fir * (fir - 1) * (fir - 2) // 6)
elif a[0] == a[1]:
print(fir * (fir - 1) // 2 * th)
elif a[1] == a[2]:
print(fir * sec * (sec - 1) // 2)
else:
print(fir * sec * th)
``` | instruction | 0 | 53,565 | 12 | 107,130 |
Yes | output | 1 | 53,565 | 12 | 107,131 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
from math import *
def nCr(n, r):
p = 1
k = 1
if (n - r < r):
r = n - r
if (r != 0):
while (r):
p *= n
k *= r
m = gcd(p, k)
p //= m
k //= m
n -= 1
r -= 1
else:
p = 1
return(p)
n=int(input())
a=list(map(int,input().split()))
a.sort()
k=a[2]
c=0
for i in range(3,n):
if a[i]==k:
c+=1
else:
break
if a[0]==a[1] and a[1]==a[2]:
print(nCr(c+3,3))
elif a[0]!=a[1] and a[1]==a[2]:
print(nCr(c+2,2))
else:
print(c+1)
``` | instruction | 0 | 53,566 | 12 | 107,132 |
Yes | output | 1 | 53,566 | 12 | 107,133 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
from math import factorial
def c(k, n): return factorial(n)//factorial(k)//factorial(n-k)
input()
a = [int(x) for x in input().split()]
counter = {k:0 for k in sorted(a)[:3]}
for n in a:
if n in counter:
counter[n] += 1
if len(counter) == 1:
answer = c(3, next(iter(counter.values())))
elif len(counter) == 2:
if counter[min(counter)] == 2:
answer = 1
else:
answer = c(2, counter[max(counter)])
else:
answer = counter[max(counter)]
print(answer)
``` | instruction | 0 | 53,567 | 12 | 107,134 |
No | output | 1 | 53,567 | 12 | 107,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
#####################################
import atexit, io, sys, collections, math, heapq, fractions,copy, os
from io import BytesIO, IOBase
##################################### python 3 START
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##################################### python 3 END
n = int(input())
ais = list(map(int, input().split()))
ais.sort()
u,v,w = ais[:3]
cc = collections.Counter(ais)
if u == v == w:
q = cc[u]
print (q*(q-1)*(q-2)//6)
elif u == v and v != w:
q = cc[w]
print (2*q)
elif u != v and v == w:
q = cc[w]
print (2*q*(q-1)/2)
elif u != v and v != w:
q = cc[w]
print (q)
``` | instruction | 0 | 53,568 | 12 | 107,136 |
No | output | 1 | 53,568 | 12 | 107,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
a.sort()
# print(a[:3])
x= list(set(a[0:3]))
if len(x)==1:
c=a.count(x[0])
print(c*(c-1)*(c-2)//6)
if len(x)==2:
c = a.count(x[0])
c1=a.count(x[1])
if c==1:
print(c1*(c1-1)//2)
else:
print(c)
if len(x)==3:
c=a.count(x[2])
print(c)
``` | instruction | 0 | 53,569 | 12 | 107,138 |
No | output | 1 | 53,569 | 12 | 107,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
After returning from the army Makes received a gift — an array a consisting of n positive integer numbers. He hadn't been solving problems for a long time, so he became interested to answer a particular question: how many triples of indices (i, j, k) (i < j < k), such that ai·aj·ak is minimum possible, are there in the array? Help him with it!
Input
The first line of input contains a positive integer number n (3 ≤ n ≤ 105) — the number of elements in array a. The second line contains n positive integer numbers ai (1 ≤ ai ≤ 109) — the elements of a given array.
Output
Print one number — the quantity of triples (i, j, k) such that i, j and k are pairwise distinct and ai·aj·ak is minimum possible.
Examples
Input
4
1 1 1 1
Output
4
Input
5
1 3 2 3 4
Output
2
Input
6
1 3 3 1 3 2
Output
1
Note
In the first example Makes always chooses three ones out of four, and the number of ways to choose them is 4.
In the second example a triple of numbers (1, 2, 3) is chosen (numbers, not indices). Since there are two ways to choose an element 3, then the answer is 2.
In the third example a triple of numbers (1, 1, 2) is chosen, and there's only one way to choose indices.
Submitted Solution:
```
def Count_Sort(l,m):
t=[]
n=[]
for i in range (m):
if i<len(l):
n.append(0)
t.append(0)
for i in l:
t[i-1]+=1
for i in range(1,m):
t[i]+=t[i-1]
for i in range(len(l)-1,-1,-1):
n[t[l[i]-1]-1]=l[i]
t[l[i]-1]-=1
return n
def Radix_Sort(ll,d):
m=9
for i in range(len(ll)):
if len(ll[i])<d:
ll[i]='0'*(d-len(ll[i]))+ll[i]
for i in range(d):
l=[]
for j in ll:
l.append(int(j[i]))
t=[]
nl=[]
n=[]
for i in range (m):
if i<len(l):
n.append(0)
nl.append('')
t.append(0)
for i in l:
t[i-1]+=1
for i in range(1,m):
t[i]+=t[i-1]
for i in range(len(l)-1,-1,-1):
n[t[l[i]-1]-1]=l[i]
nl[t[l[i]-1]-1]=ll[i]
t[l[i]-1]-=1
ll=nl.copy()
nl.clear()
return ll
#ll=['135','982','425','9']
n=int(input())
a=input()
a=a.split()
#print(a)
a=Radix_Sort(a,9)
z=[a[0],a[1],a[2]]
t=[]
j=1
for i in z:
if not(i in t):
j*=(a.count(i))
a.remove(i)
t.append(i)
print(j)
``` | instruction | 0 | 53,570 | 12 | 107,140 |
No | output | 1 | 53,570 | 12 | 107,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,605 | 12 | 107,210 |
Tags: brute force, math
Correct Solution:
```
n = int(input())
s = list(map(int, input().split()))
t = False #even
for i in range(n):
for j in range(i + 1, n):
if s[i] > s[j]:
t = not t
m = int(input())
a = []
for h in range(m):
l, r = map(int, input().split())
if ((r - l + 1) / 2) % 2 == 1 or ((r - l + 1) / 2) % 2 == 1.5:
t = not t
a.append(['even', 'odd'][t])
print('\n'.join(a))
``` | output | 1 | 53,605 | 12 | 107,211 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,606 | 12 | 107,212 |
Tags: brute force, math
Correct Solution:
```
import sys
class fenwick():
"""
This Tree Data Structure speeds up caliculating summations of partial sum
and also updating subsets of sequences. Both queries finish in logarithmic times.
"""
# 1-indexed
def __init__(self, n):
self.n = n
self.data = [0]*(n+1)
def to_sum(self, i):
# return sigma(a_j) (0<=j<=i)
s = 0
while i > 0:
s += self.data[i]
i -= (i & -i)
return s
def add(self, i, x):
#a_i -> a_i + x
while i <= self.n:
self.data[i] += x
i += (i & -i)
def get(self, i, j):
# return sigma(a_k) (i<=k<=j)
# assert 1<=i<=j<= N
return self.to_sum(j)-self.to_sum(i-1)
def input():
return sys.stdin.buffer.readline()
n = int(input())
permutation = list(map(int, input().split()))
seq = [(permutation[i], i + 1) for i in range(n)]
seq.sort(reverse=True)
m = int(input())
query = [tuple(map(int, input().split())) for i in range(m)]
#count whole inversion
WHOLE_INVERSION = 0
fenwick_1 = fenwick(n)
for value, index in seq:
WHOLE_INVERSION += fenwick_1.get(1, index)
fenwick_1.add(index, 1)
for l, r in query:
d = r - l + 1
WHOLE_INVERSION += d*(d-1)//2
if WHOLE_INVERSION % 2 != 0:
print("odd")
else:
print("even")
``` | output | 1 | 53,606 | 12 | 107,213 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,607 | 12 | 107,214 |
Tags: brute force, math
Correct Solution:
```
def divisors(M):
d=[]
i=1
while M>=i**2:
if M%i==0:
d.append(i)
if i**2!=M:
d.append(M//i)
i=i+1
return d
def popcount(x):
x = x - ((x >> 1) & 0x55555555)
x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
x = (x + (x >> 4)) & 0x0f0f0f0f
x = x + (x >> 8)
x = x + (x >> 16)
return x & 0x0000007f
def eratosthenes(n):
res=[0 for i in range(n+1)]
prime=set([])
for i in range(2,n+1):
if not res[i]:
prime.add(i)
for j in range(1,n//i+1):
res[i*j]=1
return prime
def factorization(n):
res=[]
for p in prime:
if n%p==0:
while n%p==0:
n//=p
res.append(p)
if n!=1:
res.append(n)
return res
def euler_phi(n):
res = n
for x in range(2,n+1):
if x ** 2 > n:
break
if n%x==0:
res = res//x * (x-1)
while n%x==0:
n //= x
if n!=1:
res = res//n * (n-1)
return res
def ind(b,n):
res=0
while n%b==0:
res+=1
n//=b
return res
def isPrimeMR(n):
d = n - 1
d = d // (d & -d)
L = [2, 3, 5, 7, 11, 13, 17]
for a in L:
t = d
y = pow(a, t, n)
if y == 1: continue
while y != n - 1:
y = (y * y) % n
if y == 1 or t == n - 1: return 0
t <<= 1
return 1
def findFactorRho(n):
from math import gcd
m = 1 << n.bit_length() // 8
for c in range(1, 99):
f = lambda x: (x * x + c) % n
y, r, q, g = 2, 1, 1, 1
while g == 1:
x = y
for i in range(r):
y = f(y)
k = 0
while k < r and g == 1:
ys = y
for i in range(min(m, r - k)):
y = f(y)
q = q * abs(x - y) % n
g = gcd(q, n)
k += m
r <<= 1
if g == n:
g = 1
while g == 1:
ys = f(ys)
g = gcd(abs(x - ys), n)
if g < n:
if isPrimeMR(g): return g
elif isPrimeMR(n // g): return n // g
return findFactorRho(g)
def primeFactor(n):
i = 2
ret = {}
rhoFlg = 0
while i*i <= n:
k = 0
while n % i == 0:
n //= i
k += 1
if k: ret[i] = k
i += 1 + i % 2
if i == 101 and n >= 2 ** 20:
while n > 1:
if isPrimeMR(n):
ret[n], n = 1, 1
else:
rhoFlg = 1
j = findFactorRho(n)
k = 0
while n % j == 0:
n //= j
k += 1
ret[j] = k
if n > 1: ret[n] = 1
if rhoFlg: ret = {x: ret[x] for x in sorted(ret)}
return ret
def divisors(n):
res = [1]
prime = primeFactor(n)
for p in prime:
newres = []
for d in res:
for j in range(prime[p]+1):
newres.append(d*p**j)
res = newres
res.sort()
return res
def xorfactorial(num):#排他的論理和の階乗
if num==0:
return 0
elif num==1:
return 1
elif num==2:
return 3
elif num==3:
return 0
else:
x=baseorder(num)
return (2**x)*((num-2**x+1)%2)+function(num-2**x)
def xorconv(n,X,Y):
if n==0:
res=[(X[0]*Y[0])%mod]
return res
x=[X[i]+X[i+2**(n-1)] for i in range(2**(n-1))]
y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))]
z=[X[i]-X[i+2**(n-1)] for i in range(2**(n-1))]
w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))]
res1=xorconv(n-1,x,y)
res2=xorconv(n-1,z,w)
former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))]
latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))]
former=list(map(lambda x:x%mod,former))
latter=list(map(lambda x:x%mod,latter))
return former+latter
def merge_sort(A,B):
pos_A,pos_B = 0,0
n,m = len(A),len(B)
res = []
while pos_A < n and pos_B < m:
a,b = A[pos_A],B[pos_B]
if a < b:
res.append(a)
pos_A += 1
else:
res.append(b)
pos_B += 1
res += A[pos_A:]
res += B[pos_B:]
return res
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
def get_size(self, x):
return self._size[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
class WeightedUnionFind():
def __init__(self,N):
self.parent = [i for i in range(N)]
self.size = [1 for i in range(N)]
self.val = [0 for i in range(N)]
self.flag = True
self.edge = [[] for i in range(N)]
def dfs(self,v,pv):
stack = [(v,pv)]
new_parent = self.parent[pv]
while stack:
v,pv = stack.pop()
self.parent[v] = new_parent
for nv,w in self.edge[v]:
if nv!=pv:
self.val[nv] = self.val[v] + w
stack.append((nv,v))
def unite(self,x,y,w):
if not self.flag:
return
if self.parent[x]==self.parent[y]:
self.flag = (self.val[x] - self.val[y] == w)
return
if self.size[self.parent[x]]>self.size[self.parent[y]]:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[x] += self.size[y]
self.val[y] = self.val[x] - w
self.dfs(y,x)
else:
self.edge[x].append((y,-w))
self.edge[y].append((x,w))
self.size[y] += self.size[x]
self.val[x] = self.val[y] + w
self.dfs(x,y)
class Dijkstra():
class Edge():
def __init__(self, _to, _cost):
self.to = _to
self.cost = _cost
def __init__(self, V):
self.G = [[] for i in range(V)]
self._E = 0
self._V = V
@property
def E(self):
return self._E
@property
def V(self):
return self._V
def add_edge(self, _from, _to, _cost):
self.G[_from].append(self.Edge(_to, _cost))
self._E += 1
def shortest_path(self, s):
import heapq
que = []
d = [10**15] * self.V
d[s] = 0
heapq.heappush(que, (0, s))
while len(que) != 0:
cost, v = heapq.heappop(que)
if d[v] < cost: continue
for i in range(len(self.G[v])):
e = self.G[v][i]
if d[e.to] > d[v] + e.cost:
d[e.to] = d[v] + e.cost
heapq.heappush(que, (d[e.to], e.to))
return d
#Z[i]:length of the longest list starting from S[i] which is also a prefix of S
#O(|S|)
def Z_algorithm(s):
N = len(s)
Z_alg = [0]*N
Z_alg[0] = N
i = 1
j = 0
while i < N:
while i+j < N and s[j] == s[i+j]:
j += 1
Z_alg[i] = j
if j == 0:
i += 1
continue
k = 1
while i+k < N and k + Z_alg[k]<j:
Z_alg[i+k] = Z_alg[k]
k += 1
i += k
j -= k
return Z_alg
class BIT():
def __init__(self,n,mod=None):
self.BIT=[0]*(n+1)
self.num=n
self.mod = mod
def query(self,idx):
res_sum = 0
mod = self.mod
while idx > 0:
res_sum += self.BIT[idx]
if mod:
res_sum %= mod
idx -= idx&(-idx)
return res_sum
#Ai += x O(logN)
def update(self,idx,x):
self.mod = mod
while idx <= self.num:
self.BIT[idx] += x
if mod:
self.BIT[idx] %= mod
idx += idx&(-idx)
return
class dancinglink():
def __init__(self,n,debug=False):
self.n = n
self.debug = debug
self._left = [i-1 for i in range(n)]
self._right = [i+1 for i in range(n)]
self.exist = [True for i in range(n)]
def pop(self,k):
if self.debug:
assert self.exist[k]
L = self._left[k]
R = self._right[k]
if L!=-1:
if R!=self.n:
self._right[L],self._left[R] = R,L
else:
self._right[L] = self.n
elif R!=self.n:
self._left[R] = -1
self.exist[k] = False
def left(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._left[res]
if res==-1:
break
k -= 1
return res
def right(self,idx,k=1):
if self.debug:
assert self.exist[idx]
res = idx
while k:
res = self._right[res]
if res==self.n:
break
k -= 1
return res
class SparseTable():
def __init__(self,A,merge_func,ide_ele):
N=len(A)
n=N.bit_length()
self.table=[[ide_ele for i in range(n)] for i in range(N)]
self.merge_func=merge_func
for i in range(N):
self.table[i][0]=A[i]
for j in range(1,n):
for i in range(0,N-2**j+1):
f=self.table[i][j-1]
s=self.table[i+2**(j-1)][j-1]
self.table[i][j]=self.merge_func(f,s)
def query(self,s,t):
b=t-s+1
m=b.bit_length()-1
return self.merge_func(self.table[s][m],self.table[t-2**m+1][m])
class BinaryTrie:
class node:
def __init__(self,val):
self.left = None
self.right = None
self.max = val
def __init__(self):
self.root = self.node(-10**15)
def append(self,key,val):
pos = self.root
for i in range(29,-1,-1):
pos.max = max(pos.max,val)
if key>>i & 1:
if pos.right is None:
pos.right = self.node(val)
pos = pos.right
else:
pos = pos.right
else:
if pos.left is None:
pos.left = self.node(val)
pos = pos.left
else:
pos = pos.left
pos.max = max(pos.max,val)
def search(self,M,xor):
res = -10**15
pos = self.root
for i in range(29,-1,-1):
if pos is None:
break
if M>>i & 1:
if xor>>i & 1:
if pos.right:
res = max(res,pos.right.max)
pos = pos.left
else:
if pos.left:
res = max(res,pos.left.max)
pos = pos.right
else:
if xor>>i & 1:
pos = pos.right
else:
pos = pos.left
if pos:
res = max(res,pos.max)
return res
def solveequation(edge,ans,n,m):
#edge=[[to,dire,id]...]
x=[0]*m
used=[False]*n
for v in range(n):
if used[v]:
continue
y = dfs(v)
if y!=0:
return False
return x
def dfs(v):
used[v]=True
r=ans[v]
for to,dire,id in edge[v]:
if used[to]:
continue
y=dfs(to)
if dire==-1:
x[id]=y
else:
x[id]=-y
r+=y
return r
class Matrix():
mod=10**9+7
def set_mod(m):
Matrix.mod=m
def __init__(self,L):
self.row=len(L)
self.column=len(L[0])
self._matrix=L
for i in range(self.row):
for j in range(self.column):
self._matrix[i][j]%=Matrix.mod
def __getitem__(self,item):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
return self._matrix[i][j]
def __setitem__(self,item,val):
if type(item)==int:
raise IndexError("you must specific row and column")
elif len(item)!=2:
raise IndexError("you must specific row and column")
i,j=item
self._matrix[i][j]=val
def __add__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]+other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __sub__(self,other):
if (self.row,self.column)!=(other.row,other.column):
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(self.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(self.column):
res[i][j]=self._matrix[i][j]-other._matrix[i][j]
res[i][j]%=Matrix.mod
return Matrix(res)
def __mul__(self,other):
if type(other)!=int:
if self.column!=other.row:
raise SizeError("sizes of matrixes are different")
res=[[0 for j in range(other.column)] for i in range(self.row)]
for i in range(self.row):
for j in range(other.column):
temp=0
for k in range(self.column):
temp+=self._matrix[i][k]*other._matrix[k][j]
res[i][j]=temp%Matrix.mod
return Matrix(res)
else:
n=other
res=[[(n*self._matrix[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)]
return Matrix(res)
def __pow__(self,m):
if self.column!=self.row:
raise MatrixPowError("the size of row must be the same as that of column")
n=self.row
res=Matrix([[int(i==j) for i in range(n)] for j in range(n)])
while m:
if m%2==1:
res=res*self
self=self*self
m//=2
return res
def __str__(self):
res=[]
for i in range(self.row):
for j in range(self.column):
res.append(str(self._matrix[i][j]))
res.append(" ")
res.append("\n")
res=res[:len(res)-1]
return "".join(res)
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
for i in range(n):
self.tree[self.num + i] = init_val[i]
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] <= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] <=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] <=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return -1
from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
forward = [to, cap, cost, None]
backward = forward[3] = [fr, 0, -cost, forward]
self.G[fr].append(forward)
self.G[to].append(backward)
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [None]*N
d0 = [INF]*N
dist = [INF]*N
while f:
dist[:] = d0
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
r0 = dist[v] + H[v]
for e in G[v]:
w, cap, cost, _ = e
if cap > 0 and r0 + cost - H[w] < dist[w]:
dist[w] = r = r0 + cost - H[w]
prv_v[w] = v; prv_e[w] = e
heappush(que, (r, w))
if dist[t] == INF:
return None
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, prv_e[v][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = prv_e[v]
e[1] -= d
e[3][1] += d
v = prv_v[v]
return res
import sys,random,bisect
from collections import deque,defaultdict
from heapq import heapify,heappop,heappush
from itertools import permutations
from math import log,gcd
input = lambda :sys.stdin.buffer.readline()
mi = lambda :map(int,input().split())
li = lambda :list(mi())
n = int(input())
a = li()
inv = 0
for i in range(n):
for j in range(i+1,n):
if a[i] > a[j]:
inv += 1
inv %= 2
m = int(input())
for _ in range(m):
l,r = mi()
L = r-l+1
all = L*(L-1)//2
if all%2==1:
inv = 1 - inv
print("odd" if inv else "even")
``` | output | 1 | 53,607 | 12 | 107,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,608 | 12 | 107,216 |
Tags: brute force, math
Correct Solution:
```
import sys
n = int(input())
a = [int(i) for i in input().split(" ")]
m = int(input())
inversion = 0
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
inversion += 1
if inversion % 2:
even = False
else:
even = True
lines = sys.stdin.readlines()
for k in range(m):
q = tuple(int(i) - 1 for i in lines[k].split(" "))
if (((q[1] - q[0]) + 1) // 2) % 2:
even = not even
if even:
print("even")
else:
print("odd")
``` | output | 1 | 53,608 | 12 | 107,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,609 | 12 | 107,218 |
Tags: brute force, math
Correct Solution:
```
import sys
input=sys.stdin.readline
def getsum(BITTree,i):
i=i+1
s = 0
while i > 0:
s += BITTree[i]
i -= i & (-i)
return(s)
def updatebit(BITTree , n , i ,v):
i=i+1
while i <= n:
BITTree[i] += v
i += i & (-i)
#print(BITTree)
n=int(input())
lista=[int(i) for i in input().split()]
invercount=0
bitTree=[0]*(n+2)
for k in reversed(lista):
updatebit(bitTree,n+1,k,1)
counter=getsum(bitTree,k-1)
invercount+=counter
m=int(input())
for i in range(m):
l,r=map(int,input().split())
summa=((r-l+1)*(r-l))/2
if (invercount+summa)%2:
print('odd')
invercount=1
else:
print('even')
invercount=0
``` | output | 1 | 53,609 | 12 | 107,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,610 | 12 | 107,220 |
Tags: brute force, math
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
inv = False # even
for i in range(n):
for j in range(i + 1, n):
if a[i] > a[j]:
inv = not inv
m = int(input())
ans = list()
for i in range(m):
l, r = map(int, input().split())
if ((r - l + 1) / 2) % 2 == 1 or ((r - l + 1) / 2) % 2 == 1.5:
inv = not inv
ans.append(['even', 'odd'][inv])
print('\n'.join(ans))
``` | output | 1 | 53,610 | 12 | 107,221 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A permutation of size n is an array of size n such that each integer from 1 to n occurs exactly once in this array. An inversion in a permutation p is a pair of indices (i, j) such that i > j and ai < aj. For example, a permutation [4, 1, 3, 2] contains 4 inversions: (2, 1), (3, 1), (4, 1), (4, 3).
You are given a permutation a of size n and m queries to it. Each query is represented by two indices l and r denoting that you have to reverse the segment [l, r] of the permutation. For example, if a = [1, 2, 3, 4] and a query l = 2, r = 4 is applied, then the resulting permutation is [1, 4, 3, 2].
After each query you have to determine whether the number of inversions is odd or even.
Input
The first line contains one integer n (1 ≤ n ≤ 1500) — the size of the permutation.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n) — the elements of the permutation. These integers are pairwise distinct.
The third line contains one integer m (1 ≤ m ≤ 2·105) — the number of queries to process.
Then m lines follow, i-th line containing two integers li, ri (1 ≤ li ≤ ri ≤ n) denoting that i-th query is to reverse a segment [li, ri] of the permutation. All queries are performed one after another.
Output
Print m lines. i-th of them must be equal to odd if the number of inversions in the permutation after i-th query is odd, and even otherwise.
Examples
Input
3
1 2 3
2
1 2
2 3
Output
odd
even
Input
4
1 2 4 3
4
1 1
1 4
1 4
2 3
Output
odd
odd
odd
even
Note
The first example:
1. after the first query a = [2, 1, 3], inversion: (2, 1);
2. after the second query a = [2, 3, 1], inversions: (3, 1), (3, 2).
The second example:
1. a = [1, 2, 4, 3], inversion: (4, 3);
2. a = [3, 4, 2, 1], inversions: (3, 1), (4, 1), (3, 2), (4, 2), (4, 3);
3. a = [1, 2, 4, 3], inversion: (4, 3);
4. a = [1, 4, 2, 3], inversions: (3, 2), (4, 2). | instruction | 0 | 53,611 | 12 | 107,222 |
Tags: brute force, math
Correct Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify, nlargest
from copy import deepcopy
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
n = inp()
a = inpl()
res = 0
for i in range(n):
for j in range(i+1,n):
if a[i] > a[j]:
res = 1-res
for _ in range(inp()):
l,r = inpl(); m = r-l+1
swap = m*(m-1)//2
if swap%2: res = 1-res
print('odd' if res else 'even')
``` | output | 1 | 53,611 | 12 | 107,223 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.