text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
from sys import stdin, gettrace
if gettrace():
inputi = input
else:
def input():
return next(stdin)[:-1]
def inputi():
return stdin.buffer.readline()
MOD = 998244353
def main():
n = int(inputi())
aa = [int(a) for a in inputi().split()]
aa.sort()
sm = sum(aa[n:]) - sum(aa[:n]) % MOD
fac = [1]
for i in range(1, n*2+1):
fac.append((fac[-1] * i)%MOD)
fni = pow(fac[n], MOD-2, MOD)
res = (sm*fac[n*2]*fni*fni)%MOD
print(res)
if __name__ == "__main__":
main()
```
| 85,200 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
mod=998244353
mv=150000
def mI(a, m) :
m0 = m
y = 0
x = 1
if (m == 1) :
return 0
while (a > 1) :
# q is quotient
q = a // m
t = m
# m is remainder now, process
# same as Euclid's algo
m = a % m
a = t
t = y
# Update x and y
y = x - q * y
x = t
# Make x positive
if (x < 0) :
x = x + m0
return x
V=[]
v=1
for i in range((mv)+1):
V.append(mI(i,mod))
#print(V)
#print((4*V[2])%mod)
def main():
n=int(input())
A=list(map(int,input().split()))
ans=0
A.sort()
for i in range(n):
ans=(ans+abs(-A[i]+A[(2*n)-i-1]))%mod
c=1
for i in range(n):
c=(c*((2*n)-i))%mod
c=(c*V[i+1])%mod
#print(c)
print((ans*c)%mod)
if __name__ == "__main__":
main()
```
| 85,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
import itertools
import math
import sys
import os
from collections import defaultdict
from heapq import heapify, heappush, heappop
def is_debug():
return "PYPY3_HOME" not in os.environ
def stdin_wrapper():
data = '''5
13 8 35 94 9284 34 54 69 123 846
'''
for line in data.split('\n'):
yield line
if not is_debug():
def stdin_wrapper():
while True:
yield sys.stdin.readline()
inputs = stdin_wrapper()
def input_wrapper():
return next(inputs)
def get_str():
if is_debug():
return input_wrapper()
return input()
def get(_type):
if _type == str:
return get_str()
return _type(input_wrapper())
def get_arr(_type):
return [_type(x) for x in input_wrapper().split()]
def tuplerize(method):
def wrap(*args, **kwargs):
res = method(*args, **kwargs)
if not isinstance(res, (tuple, list)):
res = (res, )
return res
return wrap
''' Solution '''
@tuplerize
def solve(n, d):
MOD = 998244353
def price(a,b):
return sum([abs(x-y) % MOD for x, y in zip(sorted(a), reversed(sorted(b)))]) % MOD
_MAX = 2*n + 1
fact = [0 for _ in range((_MAX))]
fact[0] = 1
fact_inv = [0 for _ in range((_MAX))]
for i in range(1, _MAX):
fact[i] = fact[i-1] * i % MOD
def fastpow(x, y, z):
"Calculate (x ** y) % z efficiently."
number = 1
while y:
if y & 1:
number = number * x % z
y >>= 1
x = x * x % z
return number
fact_inv[_MAX-1] = fastpow(fact[_MAX-1], MOD - 2, MOD) % MOD
for i in reversed(range(_MAX-1)):
fact_inv[i] = fact_inv[i+1] * (i+1) % MOD
p = price(d[:len(d)//2], d[len(d)//2:])
return (p * ((((fact[len(d)] * fact_inv[len(d)//2]) % MOD) * fact_inv[len(d)//2]) % MOD)) % MOD
n = get(int)
a = get_arr(int)
print(*solve(n, a))
```
| 85,202 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
def ncr(n, r, p):
# initialize numerator
# and denominator
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def testcase():
n = int(input())
arr = list(map(int, input().split()))
mod = 998244353
arr.sort()
c = ncr(2 * n, n, mod)
ans = 0
for i in range(n):
ans = (ans - (arr[i] * c) % mod) % mod
for i in range(n, 2 * n):
ans = (ans + (arr[i] * c) % mod) % mod
print(ans)
return
import sys, os
if os.path.exists('input.txt'):
sys.stdin = open('input.txt', 'r')
sys.setrecursionlimit(10 ** 5)
testcase()
```
| 85,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
def res(n):
nu=s=1
for i in range(n):
nu=(nu*(2*n-i))%m
s=(s*(i+1))%m
return((nu*pow(s,m-2,m))%m)
m=998244353
n=int(input())
fg=sorted(list(map(int,input().split())))
f=abs((sum(fg[:n])-sum(fg[n:])))
print((f*res(n))%m)
#print(f)
```
| 85,204 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
mod = 998244353
def pow_(x, y, p) :
res = 1
x = x % p
if x == 0:
return 0
while y > 0:
if (y & 1) == 1:
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
def reverse(x, mod):
return pow_(x, mod-2, mod)
gt = [1] * 300001
for i in range(2, 300001):
gt[i] = i * gt[i-1] % mod
n = int(input())
a = list(map(int, input().split()))
a = sorted(a)
cof = (gt[2*n] * reverse(gt[n], mod) * reverse(gt[n], mod))
ans = (sum(a[n:]) - sum(a[:n])) * cof % mod
print(ans)
```
| 85,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Tags: combinatorics, math, sortings
Correct Solution:
```
import sys
import math,bisect
sys.setrecursionlimit(10 ** 5)
from itertools import groupby,accumulate
from heapq import heapify,heappop,heappush
from collections import deque,Counter,defaultdict
I = lambda : int(sys.stdin.readline())
neo = lambda : map(int, sys.stdin.readline().split())
Neo = lambda : list(map(int, sys.stdin.readline().split()))
n = I()
A = Neo()
mod = 998244353
fact = [1]
for i in range(1,2*n+1):
fact += [fact[-1]*i%mod]
B,C = A[0::2],A[1::2]
B.sort()
C.sort(reverse=True)
Ans = 0
for i,j in zip(B,C):
Ans += abs(i-j)
Ans = Ans%mod
Ans = (Ans*fact[2*n]*pow(fact[n]*fact[n],mod-2,mod))%mod
print(Ans)
```
| 85,206 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
#from math import *
from bisect import *
from collections import *
from random import *
from decimal import *
from itertools import *
from heapq import *
import sys
input=sys.stdin.readline
def inp():
return int(input())
def st():
return input().rstrip('\n')
def lis():
return list(map(int,input().split()))
def ma():
return map(int,input().split())
t=1
p=998244353
fac=[1]
for i in range(1,300010):
fac.append((fac[-1]*i)%p)
while(t):
t-=1
n=inp()
a=lis()
a.sort()
ha=fac[2*n]
ha=ha*pow(fac[n],p-2,p)*pow(fac[n],p-2,p)
ha=ha%p
nn,pp=0,0
for i in range(2*n):
if(i< n):
nn+=ha*a[i]
nn=nn%p
else:
pp+=ha*a[i]
pp=pp%p
print((pp-nn)%p)
```
Yes
| 85,207 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
# ===============================================================================================
# some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
# to find factorial and ncr
N=300005
mod = 998244353
fac = [1, 1]
finv = [1, 1]
inv = [0, 1]
for i in range(2, N + 1):
fac.append((fac[-1] * i) % mod)
inv.append(mod - (inv[mod % i] * (mod // i) % mod))
finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
def solve():
n=int(inp())
mod=998244353
ar=lis()
ar.sort()
s1=sum(ar)
s2=sum(ar[:n])
t=s1-2*s2
t%=mod
t*=comb(2*n,n)
t%=mod
print(t)
solve()
# testcase(int(inp()))
```
Yes
| 85,208 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
"""
#If FastIO not needed, used this and don't forget to strip
#import sys, math
#input = sys.stdin.readline
"""
import os
import sys
from io import BytesIO, IOBase
import heapq as h
from bisect import bisect_left, bisect_right
from types import GeneratorType
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
from collections import defaultdict as dd, deque as dq
import math, string
def getInts():
return [int(s) for s in input().split()]
def getInt():
return int(input())
def getStrs():
return [s for s in input().split()]
def getStr():
return input()
def listStr():
return list(input())
MOD = 998244353
"""
Sum of the differences of the elements when sorted in opposite ways
A1 A2 A3 ... AN
BN ... B3 B2 B1
f = |A1-BN| + ...
Sum f over all partitions
There are 2N choose N partitions so a lot
The smallest element will always be A1 or B1 in whichever partition it is in
Suppose we have [A1, A2, A3, A4]
A1 A2
A4 A3
A1 A3
A4 A2
A1 A4
A3 A2
A2 A3
A4 A1
A2 A4
A3 A1
A3 A4
A2 A1
A4 is always added
A3 is always added
A2 is always subtracted
A1 is always subtracted
So the answer is (2N choose N)*sum(bigger half)-sum(smaller half)
"""
def solve():
N = getInt()
A = getInts()
A.sort()
ans = 0
#print(A)
for j in range(N):
ans -= A[j]
for j in range(N,2*N):
ans += A[j]
ans %= MOD
curr = 1
for j in range(1,2*N+1):
curr *= j
curr %= MOD
if j == N:
n_fac = curr
if j == 2*N:
tn_fac = curr
#print(ans,n_fac,tn_fac)
div = pow(n_fac,MOD-2,MOD)
return (ans*tn_fac*div*div) % MOD
#for _ in range(getInt()):
print(solve())
```
Yes
| 85,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
import sys
import math
def II():
return int(sys.stdin.readline())
def LI():
return list(map(int, sys.stdin.readline().split()))
def MI():
return map(int, sys.stdin.readline().split())
def SI():
return sys.stdin.readline().strip()
def FACT(n, mod):
s = 1
facts = [1]
for i in range(1,n+1):
s*=i
s%=mod
facts.append(s)
return facts[n]
def C(n, k, mod):
return (FACT(n,mod) * pow((FACT(k,mod)*FACT(n-k,mod))%mod,mod-2, mod))%mod
n = II()
a = LI()
x = sorted(a[:n])
y = sorted(a[n:])[:][::-1]
s = 0
mod = 998244353
for i in range(n):
s+=abs(x[i]-y[i])
print(s*C(2*n,n, mod)%mod)
```
Yes
| 85,210 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
import itertools
import math
import sys
import os
from collections import defaultdict
from heapq import heapify, heappush, heappop
def is_debug():
return "PYPY3_HOME" not in os.environ
def stdin_wrapper():
data = '''5
13 8 35 94 9284 34 54 69 123 846
'''
for line in data.split('\n'):
yield line
if not is_debug():
def stdin_wrapper():
while True:
yield sys.stdin.readline()
inputs = stdin_wrapper()
def input_wrapper():
return next(inputs)
def get_str():
if is_debug():
return input_wrapper()
return input()
def get(_type):
if _type == str:
return get_str()
return _type(input_wrapper())
def get_arr(_type):
return [_type(x) for x in input_wrapper().split()]
def tuplerize(method):
def wrap(*args, **kwargs):
res = method(*args, **kwargs)
if not isinstance(res, (tuple, list)):
res = (res, )
return res
return wrap
''' Solution '''
@tuplerize
def solve(n, d):
MOD = 998244353
def price(a,b):
return sum([abs(x-y) for x, y in zip(sorted(a), reversed(sorted(b)))])
p = price(d[:len(d)//2], d[len(d)//2:])
f_bot = math.factorial(len(d)//2) % MOD
f_top = f_bot
for i in range(len(d)//2):
f_top *= (len(d)//2 + i+1) % MOD
f_top %= MOD
return p * (f_top // (f_bot*f_bot)) % MOD
n = get(int)
a = get_arr(int)
print(*solve(n, a))
```
No
| 85,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
from math import comb
n=int(input())
arr=list(map(int,input().split()))
arr=sorted(arr)
ans=0
hi=2
lo=1
for i in range(2,n+1):
lo=(lo*i*i)%998244353
hi=hi*2*i*(2*i-1)%998244353
if lo==0:
print(0)
else:
if hi%lo==0:
t=hi//lo
else:
while hi%lo==0:
hi=hi+998244353
hi=hi%lo
t=hi//lo
end=sum(arr[:n])%998244353
st=sum(arr[n:])%998244353
ans=t*(st-end)%998244353
print(ans)
```
No
| 85,212 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
def pwm(a, n, mod):
ans = 1
while n:
if n & 1:
ans = ans*a % mod
a = a*a % mod
n >>= 1
return ans
n = int(input())
l = [int(x) for x in input().split()]
l.sort()
a, b = l[:n], l[n:]
ans = 0
mod = 998244353
dnom = 1
nom = 1
for i in range(n):
ans += (b[i] % mod - a[i] % mod) % mod
nom = nom * (i+1) % mod * (2*n - i) % mod
dnom = dnom*(i+1) % mod * (i+1) % mod
gg = (nom % mod)*pwm(dnom, mod-2, mod) % mod
fans = ans*gg
# print(ans)
# print(gg)
print(fans)
```
No
| 85,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a of length 2n. Consider a partition of array a into two subsequences p and q of length n each (each element of array a should be in exactly one subsequence: either in p or in q).
Let's sort p in non-decreasing order, and q in non-increasing order, we can denote the sorted versions by x and y, respectively. Then the cost of a partition is defined as f(p, q) = β_{i = 1}^n |x_i - y_i|.
Find the sum of f(p, q) over all correct partitions of array a. Since the answer might be too big, print its remainder modulo 998244353.
Input
The first line contains a single integer n (1 β€ n β€ 150 000).
The second line contains 2n integers a_1, a_2, β¦, a_{2n} (1 β€ a_i β€ 10^9) β elements of array a.
Output
Print one integer β the answer to the problem, modulo 998244353.
Examples
Input
1
1 4
Output
6
Input
2
2 1 2 1
Output
12
Input
3
2 2 2 2 2 2
Output
0
Input
5
13 8 35 94 9284 34 54 69 123 846
Output
2588544
Note
Two partitions of an array are considered different if the sets of indices of elements included in the subsequence p are different.
In the first example, there are two correct partitions of the array a:
1. p = [1], q = [4], then x = [1], y = [4], f(p, q) = |1 - 4| = 3;
2. p = [4], q = [1], then x = [4], y = [1], f(p, q) = |4 - 1| = 3.
In the second example, there are six valid partitions of the array a:
1. p = [2, 1], q = [2, 1] (elements with indices 1 and 2 in the original array are selected in the subsequence p);
2. p = [2, 2], q = [1, 1];
3. p = [2, 1], q = [1, 2] (elements with indices 1 and 4 are selected in the subsequence p);
4. p = [1, 2], q = [2, 1];
5. p = [1, 1], q = [2, 2];
6. p = [2, 1], q = [2, 1] (elements with indices 3 and 4 are selected in the subsequence p).
Submitted Solution:
```
import sys
import math
import collections
input=sys.stdin.readline
mod=998244353
def fact(n):
prod=1
for i in range(2,n+1):
prod=(prod*i)%mod
return prod
def ncr(n):
return((fact(2*n)//(fact(n)*fact(n)))%mod)
n=int(input())
l=sorted([int(i) for i in input().split()])
s1=0
s2=0
for i in range(n):
s1+=l[i]
s2+=l[n+i]
print(((s2-s1)*ncr(n))%mod)
```
No
| 85,214 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Tags: constructive algorithms
Correct Solution:
```
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
shit =False
if s < 0 or f < 0:
if(a[2] == a[3]):
ans = "74"*a[2]+"7"
shit = True
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = "-1"
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
if(ans[-1] == "4"):
ans = "4"*f + "7" + ans[2:-1] + "7"*(s-1) + "4"
else:
ans = "4"*f + "7" + ans[2:] + "7"*(s-1)
else:
if(ans[-1] == "4"):
ans = "7" + "4"*f + ans[2:-1] + "7"*(s-1) + "4"
else:
ans = "7" + "4"*f + ans[2:] + "7"*(s-1)
print(ans)
```
| 85,215 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Tags: constructive algorithms
Correct Solution:
```
a1,a2,a3,a4=map(int,input().split())
L=[]
def Solve(a1,a2,a3,a4):
if(a3-a4<-1 or a3-a4>1 or a1<a3 or a1<a4 or a2<a3 or a2<a4):
return -1
elif(a3-a4==0):
Ans="47"*a3
Ans+="4"
if(a1-a3==0 and a2-a4==0):
return -1
elif(a1-a3==0):
return "74"*a3+"7"*(a2-a4)
return "4"*(a1-a3-1)+Ans[:len(Ans)-1]+"7"*(a2-a4)+"4"
elif(a3-a4==1):
if(a2==a4):
return -1
Ans="47"*a3
Ans="4"*(a1-a3)+Ans+"7"*(a2-a4-1)
return Ans
else:
if(a3==a1):
return -1
Ans="74"*a4
Ans="7"+"4"*(a1-a3-1)+Ans[1:len(Ans)-1]+"7"*(a2-a4)+"4"
return Ans
print(Solve(a1,a2,a3,a4))
# Made By Mostafa_Khaled
```
| 85,216 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Tags: constructive algorithms
Correct Solution:
```
a1,a2,a3,a4=map(int,input().split())
if abs(a3-a4)>1:
print(-1)
elif min(a1,a2)<max(a3,a4):
print(-1)
elif a1==a2==a3==a4:
print(-1)
else:
if a3==a4:
if a1==a3:
print ('74'*a3+'7'*(a2-a3))
else:
print('4'*(a1-a3-1)+'47'*a3+'7'*(a2-a3)+'4')
elif a3>a4:
print('4'*(a1-a3)+'47'*a3+'7'*(a2-a3))
else:
print('7'+'4'*(a1-a3)+'74'*(a3-1)+'7'*(a2-a3)+'4')
```
| 85,217 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Tags: constructive algorithms
Correct Solution:
```
a, b, c, d = map(int, input().split(' '))
if (a+b) - (c+d) < 1:
print(-1)
quit()
if c == d:
if a == c:
if (b-a < 0):
print(-1)
quit()
print('74' * d + '7' * (b-a))
quit()
if ((b-c) < 0 or (a-c-1) < 0):
print(-1)
quit()
print('4' * (a-c-1) + '47' * c + '7' * (b - c) + '4')
quit()
if c + 1 == d:
if (a-c-1 < 0 or b-c-1 < 0):
print(-1)
quit()
print('7' + '4' * (a-c-1) + '47' * c + '7' * (b-1-c) + '4')
quit()
if d + 1 == c:
if a-c < 0 or b-c < 0:
print(-1)
quit()
print('4'*(a-c) + '47' * (c) + '7' * (b-c))
quit()
print(-1)
quit()
```
| 85,218 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Submitted Solution:
```
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
if(a[2] == a[3]):
ans = "74"*a[2]+"7"
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = "-1"
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
ans = "4"*f + "7"*s + ans[2:]
else:
ans = "7" + "4"*f + ans[2:-1] + "7"*(s-1)
print(ans)
```
No
| 85,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Submitted Solution:
```
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = -1
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
ans = "4"*f + "7"*s + ans[2:]
else:
ans = "7"*s + "4"*f + ans[2:]
print(ans)
```
No
| 85,220 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Submitted Solution:
```
a, b, c, d = map(int, input().split(' '))
if (a+b) - (c+d) < 1:
print(-1)
quit()
if c == d:
if ((b-c) < 0 or (a-c-1) < 0):
print(-1)
quit()
if a == c:
print('74' * d + '7' * (b-a))
quit()
print('4' * (a-c-1) + '47' * c + '7' * (b - c) + '4')
quit()
if c + 1 == d:
if (a-c-1 < 0 or b-c-1 < 0):
print(-1)
quit()
print('7' + '4' * (a-c-1) + '47' * c + '7' * (b-1-c) + '4')
quit()
if d + 1 == c:
if a-c < 0 or b-c < 0:
print(-1)
quit()
print('4'*(a-c) + '47' * (c) + '7' * (b-c))
quit()
print(-1)
quit()
```
No
| 85,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Petya loves lucky numbers very much. Everybody knows that lucky numbers are positive integers whose decimal record contains only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
Petya loves long lucky numbers very much. He is interested in the minimum lucky number d that meets some condition. Let cnt(x) be the number of occurrences of number x in number d as a substring. For example, if d = 747747, then cnt(4) = 2, cnt(7) = 4, cnt(47) = 2, cnt(74) = 2. Petya wants the following condition to fulfil simultaneously: cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. Petya is not interested in the occurrences of other numbers. Help him cope with this task.
Input
The single line contains four integers a1, a2, a3 and a4 (1 β€ a1, a2, a3, a4 β€ 106).
Output
On the single line print without leading zeroes the answer to the problem β the minimum lucky number d such, that cnt(4) = a1, cnt(7) = a2, cnt(47) = a3, cnt(74) = a4. If such number does not exist, print the single number "-1" (without the quotes).
Examples
Input
2 2 1 1
Output
4774
Input
4 7 3 1
Output
-1
Submitted Solution:
```
from math import *
from fractions import *
from sys import *
def li():
return list(map(int, input().split(" ")))
a = li()
if abs(a[2]-a[3]) > 1:
print(-1)
exit()
if a[2] == a[3]:
ans = "47"*a[2]+"4"
elif a[2] > a[3]:
ans = "47"*a[2]
else:
ans = "74"*a[3]
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
shit =False
if s < 0 or f < 0:
if(a[2] == a[3]):
ans = "74"*a[2]+"7"
shit = True
f = a[0]-ans.count("4")
s = a[1]-ans.count("7")
if s < 0 or f < 0:
ans = "-1"
elif s>0 or f>0:
s+=1
f+=1
if ans[:2] == "47":
if(ans[-1] == "4"):
ans = "4"*f + "7"*s + ans[2:]
else:
ans = "4"*f + "7" + ans[2:] + "7"*(s-1)
else:
if(ans[-1] == "4"):
ans = "7"*s + "4"*f + ans[2:]
else:
ans = "7" + "4"*f + ans[2:] + "7"*(s-1)
print(ans)
```
No
| 85,222 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
def updateFinal(final, arr):
total = 0
li = []
arr.sort(reverse = True)
n = len(arr)
for i in range(n):
total+=arr[i]
li.append(total)
for i in range(1,n+1):
final[i-1] += li[(i*(n//i)) -1]
return final
for t in range(int(input())):
n = int(input())
u = [int(x) for x in input().split()]
s = [int(x) for x in input().split()]
uniMap = {}
for i in range(n):
if u[i] in uniMap:
uniMap[u[i]].append(s[i])
else:
uniMap[u[i]] = [s[i]]
final = [0 for x in range(n)]
for key in uniMap:
final = updateFinal(final, uniMap[key])
print(*final)
```
| 85,223 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
t=int(input())
#4
for _ in range(t):
n=int(input())
u= list(map(int, input().split()))
s= list(map(int, input().split()))
us=[[] for j in range(n)]
for i in range(n):
us[u[i]-1].append(s[i])
s=[0]*n
for i in range(n):
if(us[i]==[]):
continue
us[i].sort()
p=len(us[i])
if(p>1):
for j in range(p-2,-1,-1):
us[i][j]+=us[i][j+1]
for j in range(1,p+1):
k=p%j
s[j-1]+=us[i][k]
print(*s)
```
| 85,224 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
from queue import Queue
import itertools
import bisect
import heapq
#sys.setrecursionlimit(100000)
#^^^TAKE CARE FOR MEMORY LIMIT^^^
def main():
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def binary(n):
return (bin(n).replace("0b", ""))
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countcon(s, i):
c = 0
ch = s[i]
for i in range(i, len(s)):
if (s[i] == ch):
c += 1
else:
break
return (c)
def lis(arr):
n = len(arr)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum = 0
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
def isSubSequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def maxfac(n):
root = int(n ** 0.5)
for i in range(2, root + 1):
if (n % i == 0):
return (n // i)
return (n)
def p2(n):
c=0
while(n%2==0):
n//=2
c+=1
return c
def seive(n):
primes=[True]*(n+1)
primes[1]=primes[0]=False
for i in range(2,n+1):
if(primes[i]):
for j in range(i+i,n+1,i):
primes[j]=False
p=[]
for i in range(0,n+1):
if(primes[i]):
p.append(i)
return(p)
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def denofactinverse(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return (pow(fac,m-2,m))
def numofact(n,m):
fac=1
for i in range(1,n+1):
fac=(fac*i)%m
return(fac)
def sod(n):
s=0
while(n>0):
s+=n%10
n//=10
return s
for xyz in range(0,int(input())):
n=int(input())
u=list(map(int,input().split()))
s=list(map(int,input().split()))
mat=[[] for i in range(max(u))]
su=sum(s)
for i in range(0,n):
mat[u[i]-1].append(s[i])
for i in range(0,len(mat)):
mat[i].sort()
#for i in mat:
# print(*i)
maxl=0
for i in range(0,len(mat)):
maxl=max(maxl,len(mat[i]))
ans = [0] * n
for i in range(0,len(mat)):
#size=i+1
cp=[0]
cs=sum(mat[i])
for j in range(0,len(mat[i])):
size=j+1
#print(l[j])
cp.append(cp[-1]+mat[i][j])
ans[j]+=cs-cp[len(mat[i])%size]
#print(subcont)
print(*ans)
```
| 85,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def helper(pool,n):
res = [0] * n
for i in range(len(pool)):
tl = len(pool[i])
ssums = [0] + sorted(pool[i])
for j in range(1,len(pool[i])+1):
ssums[j] += ssums[j-1]
for j in range(1,n+1):
if j > tl:
break
res[j-1] += ssums[-1] - ssums[tl%j]
return res
t = int(input())
for i in range(t):
n = int(input())
pool = [[] for j in range(n)]
u = list(map(int, sys.stdin.readline().rstrip().split()))
s = list(map(int, sys.stdin.readline().rstrip().split()))
for j in range(n):
pool[u[j]-1].append(s[j])
#n,m,k = map(int,input().split(" "))
res = helper(pool,n)
print(" ".join(map(str,res)))
```
| 85,226 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
from sys import *
from collections import defaultdict
for _ in range(int(stdin.readline())):
n=int(stdin.readline())
u=list(map(int,stdin.readline().split()))
skill=list(map(int,stdin.readline().split()))
vectortmp=defaultdict()
for i in range(n):
if u[i] in vectortmp:
vectortmp[u[i]].append(skill[i])
else:
vectortmp[u[i]]=[skill[i]]
a=defaultdict(list)
maxi=0
for i in vectortmp:
vectortmp[i].sort(reverse=True)
for i in vectortmp:
a[i]=[vectortmp[i][0]]
maxi=max(maxi,len(vectortmp[i]))
for j in range(1,len(vectortmp[i])):
a[i].append(a[i][-1]+vectortmp[i][j])
ans=[0]*n
for i in vectortmp:
for j in range(1,maxi+1):
if len(vectortmp[i])>=j:
pos=(len(vectortmp[i]))-(len(vectortmp[i])%j)
ans[j-1]+=a[i][pos-1]
else:
break
print(*ans)
```
| 85,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
from sys import stdin
def read_int():
return int(stdin.readline())
def read_ints():
return map(int, stdin.readline().split(' '))
t = read_int()
for case_num in range(t):
n = read_int()
u = list(read_ints())
s = list(read_ints())
tot = sum(s)
d = [[] for _ in range(n + 1)]
for ui, si in zip(u, s):
d[ui].append(si)
for i in range(1, n + 1):
d[i].sort()
acc = [[0] * (len(d[i]) + 1) for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, len(d[i]) + 1):
acc[i][j] = acc[i][j - 1] + d[i][j - 1]
ans = []
rem = set([i for i in range(1, n + 1) if len(d[i]) > 0])
for k in range(1, n + 1):
dec = 0
to_remove = set()
for i in rem:
if len(d[i]) < k:
to_remove.add(i)
tot -= sum(d[i])
else:
dec += acc[i][len(d[i]) % k]
ans.append(tot - dec)
for i in to_remove:
rem.remove(i)
print(' '.join(map(str, ans)))
```
| 85,228 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
from collections import defaultdict
from itertools import accumulate
t = int(input())
for _ in range(t):
n = int(input())
u = list(map(int, input().split()))
s = list(map(int, input().split()))
d = defaultdict(list)
for k, v in zip(u, s):
d[k].append(v)
ans = [0]*(n+1)
for k in d.keys():
d[k].sort(reverse=True)
l = list(accumulate(d[k]))
for r in range(1, min(n, len(l))+1):
ans[r] += l[((len(l) // r) * r) -1]
print(*ans[1:], sep=' ')
```
| 85,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Tags: brute force, data structures, greedy, number theory, sortings
Correct Solution:
```
from collections import defaultdict
def heelo():
return "hello"
def akfbdkg():
return "dkgks"
test = int(input())
while test!=0:
n = int(input())
ll1 = list(map(int,input().split()))
ll2 = list(map(int,input().split()))
dicti= defaultdict(list)
s = defaultdict(int)
for i in range(n):
dicti[ll1[i]].append(ll2[i])
s[ll1[i]]+=1
for i in dicti.keys():
dicti[i].sort(reverse=True)
for i in dicti.keys():
for j in range(1,len(dicti[i])):
dicti[i][j] = dicti[i][j]+dicti[i][j-1]
fa = []
for i in range(1,n+1):
temp_ans = 0
fin = []
for j in dicti.keys():
p = s[j]
var = (p)//i
index = var*(i) -1
if index<0:
fin.append(j)
temp_ans+=0
else:
temp_ans+=dicti[j][index]
for j in range(len(fin)):
del dicti[fin[j]]
fa.append(temp_ans)
print(*fa)
# def randomfunc2(a):
# return "hellow rodl"
test-=1
```
| 85,230 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
import sys
import math
from collections import defaultdict as dd
from sys import stdin
input=stdin.readline
m=10**9+7
sys.setrecursionlimit(10**5)
T=int(input())
for _ in range(T):
N=int(input())
U=list(map(int,input().split()))
S=list(map(int,input().split()))
ANS=[0]*N
X=[[0] for i in range(N)]
for i in range(N):
X[U[i]-1].append(S[i])
#print(X)
for i in range(N):
X[i].sort(reverse=True)
for j in range(1,len(X[i])):
X[i][j]+=X[i][j-1]
X[i].pop()
lim=len(X[i])
for j in range(1,lim+1):
if lim>=j:
rem=lim%j
#print(i,rem,X[i])
el=X[i][-rem-1]
ANS[j-1]+=el
print(*ANS)
```
Yes
| 85,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
import sys
input = sys.stdin.readline
def println(val):
sys.stdout.write(str(val) + '\n')
for _ in range(int(input().strip())):
N = int(input().strip())
U = [int(x) for x in input().strip().split()]
S = [int(x) for x in input().strip().split()]
varsities = [[] for i in range(N+1)]
for i, u, s in zip(range(N), U, S):
varsities[u] += [s]
ans = [0 for i in range(N)]
for i, varsity in enumerate(varsities):
if len(varsity) == 0: continue
varsity.sort(reverse=True)
pref = [varsity[0]]
for ii in range(1, len(varsity)):
pref += [pref[-1] + varsity[ii]]
for ii in range(1, len(varsity) + 1):
ans[ii - 1] += pref[len(varsity) - len(varsity) % ii - 1]
println(' '.join(str(a) for a in ans))
```
Yes
| 85,232 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
u = list(map(int, input().split()))
s = list(map(int, input().split()))
lst = [[] for i in range(n)]
for i in range(n):
lst[u[i]-1].append(s[i])
for i in lst:
i.sort(reverse=True)
answer = [0 for j in range(n)]
for i in range(n):
l = len(lst[i])
p = [0 for j in range(l+1)]
for j in range(1,l+1):
p[j] = p[j-1] + lst[i][j-1]
for k in range(1,l+1):
answer[k-1]+=p[(l//k)*k]
print(*answer)
```
Yes
| 85,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
u = list(map(int,input().split()))
s = list(map(int,input().split()))
L = [[] for i in range(n+1)]
for i,j in zip(u,s):
L[i].append(j)
ans = [0]*(n+1)
for i in range(n+1):
if L[i] == []:
continue
L[i].sort(reverse=True)
cum = [0]
le = len(L[i])
for j in L[i]:
cum.append(cum[-1]+j)
for j in range(1,n+1):
if j > le:
break
ans[j] += cum[-1-(le%j)]
print(*ans[1:])
```
Yes
| 85,234 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
t=int(input())
for i in range(t):
n=int(input())
u=list(map(int,input().split()))
p=list(map(int,input().split()))
d={}
for i in set(u):
d[i]=[]
for i in range(n):
d[u[i]].append(p[i])
for i in set(u):
d[i].sort(reverse=True)
ans=[]
for k in range(1,n):
t=0
for i in set(u):
l=len(d[i])
t+=sum(d[i][:k*(l//k)])
ans.append(t)
print(*ans)
```
No
| 85,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
# Author: Udit "luctivud" Gupta @ https://www.linkedin.com/in/udit-gupta-1b7863135/ #
import math; from collections import *
import sys; from functools import reduce
import time; from itertools import groupby
# sys.setrecursionlimit(10**6)
# def input() : return sys.stdin.readline()
def get_ints() : return map(int, input().strip().split())
def get_list() : return list(get_ints())
def get_string() : return list(input().strip().split())
def printxsp(*args) : return print(*args, end="")
def printsp(*args) : return print(*args, end=" ")
DIRECTIONS = [(+0, +1), (+0, -1), (+1, +0), (-1, -0)]
NEIGHBOURS = [(-1, -1), (-1, +0), (-1, +1), (+0, -1),\
(+1, +1), (+1, +0), (+1, -1), (+0, +1)]
# MAIN >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
for _test_ in range(int(input())):
n = int(input())
uni = get_list()
val = get_list()
d = {}
for i in range(n):
if uni[i] in d:
d[uni[i]].append(val[i])
else:
d[uni[i]] = [val[i]]
for ke, va in d.items():
d[ke].sort(reverse = True)
for j in range(1, len(d[ke])):
d[ke][j] += d[ke][j-1]
print(d)
ans = [0] * (n + 1)
for i in range(1, n+1):
for ke, va in d.items():
sz = len(va)
ind = ((sz // i) * i) - 1
if ind != -1:
ans[i] += va[ind]
print(*ans[1:])
```
No
| 85,236 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
def main():
t = int(input())
for i in range(t):
s()
def s():
n = int(input())
t = list(map(int, input().split()))
a = list(map(int, input().split()))
teams = [[] for i in range(max(t))]
for i in range(len(a)):
teams[t[i]-1].append(a[i])
Ml =0
for i in range(len(teams)-1, -1, -1):
if teams[i] == []:
teams.pop(i)
teams[i].sort()
teams[i].insert(0, 0)
for j in range(1, len(teams[i])):
teams[i][j] += teams[i][j-1]
Ml = max(len(teams[i]), Ml)
for i in range(0, n):
s = 0
if i+1 <= Ml:
for j in range(len(teams)-1, -1, -1):
if len(teams[j]) < i+1:
teams.pop(j)
else:
s += teams[j][-1] - teams[j][(len(teams[j])-1)%(i+1)]
print(s, end = " ")
print()
main()
```
No
| 85,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is an organizer of a Berland ICPC regional event. There are n universities in Berland numbered from 1 to n. Polycarp knows all competitive programmers in the region. There are n students: the i-th student is enrolled at a university u_i and has a programming skill s_i.
Polycarp has to decide on the rules now. In particular, the number of members in the team.
Polycarp knows that if he chooses the size of the team to be some integer k, each university will send their k strongest (with the highest programming skill s) students in the first team, the next k strongest students in the second team and so on. If there are fewer than k students left, then the team can't be formed. Note that there might be universities that send zero teams.
The strength of the region is the total skill of the members of all present teams. If there are no teams present, then the strength is 0.
Help Polycarp to find the strength of the region for each choice of k from 1 to n.
Input
The first line contains a single integer t (1 β€ t β€ 1000) β the number of testcases.
The first line of each testcase contains a single integer n (1 β€ n β€ 2 β
10^5) β the number of universities and the number of students.
The second line of each testcase contains n integers u_1, u_2, ..., u_n (1 β€ u_i β€ n) β the university the i-th student is enrolled at.
The third line of each testcase contains n integers s_1, s_2, ..., s_n (1 β€ s_i β€ 10^9) β the programming skill of the i-th student.
The sum of n over all testcases doesn't exceed 2 β
10^5.
Output
For each testcase print n integers: the strength of the region β the total skill of the members of the present teams β for each choice of team size k.
Example
Input
4
7
1 2 1 2 1 2 1
6 8 3 1 5 1 5
10
1 1 1 2 2 2 2 3 3 3
3435 3014 2241 2233 2893 2102 2286 2175 1961 2567
6
3 3 3 3 3 3
5 9 6 7 9 7
1
1
3083
Output
29 28 26 19 0 0 0
24907 20705 22805 9514 0 0 0 0 0 0
43 43 43 32 38 43
3083
Note
In the first testcase the teams from each university for each k are:
* k=1:
* university 1: [6], [5], [5], [3];
* university 2: [8], [1], [1];
* k=2:
* university 1: [6, 5], [5, 3];
* university 2: [8, 1];
* k=3:
* university 1: [6, 5, 5];
* university 2: [8, 1, 1];
* k=4:
* university 1: [6, 5, 5, 3];
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
s=list(map(int,input().split()))
d={}
for i in range(n):
if(a[i] in d.keys()):
d[a[i]].append(s[i])
else:
d[a[i]]=[s[i]]
for i in d.keys():
d[i].sort(reverse=True)
for i in range(n):
z=0
for j in d.keys():
if(len(d[j])<i+1):
x=len(d[j])%(i+1)
y=d[j][:len(d[j])-x]
z+=sum(y)
print(z,end=" ")
print()
```
No
| 85,238 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
# import math
# import collections
# from itertools import permutations
# from itertools import combinations
# import sys
# sys.stdin = open('input.txt', 'r')
# sys.stdout = open('output.txt', 'w')
'''def is_prime(n):
j=2
while j*j<=n:
if n%j==0:
return 0
j+=1
return 1'''
'''def gcd(x, y):
while(y):
x, y = y, x % y
return x'''
'''fact=[]
def factors(n) :
i = 1
while i <= math.sqrt(n):
if (n % i == 0) :
if (n / i == i) :
fact.append(i)
else :
fact.append(i)
fact.append(n//i)
i = i + 1'''
def prob():
n = int(input())
# mod = 10**9 + 7
# n,k=[int(x) for x in input().split()]
# s=input()
# n = len(s)
l = [int(x) for x in input().split()]
# lb = [int(x) for x in input().split()]
if sorted(l)[::2] == sorted(l[::2]):
print("YES")
else:
print("NO")
t=1
t=int(input())
for _ in range(0,t):
prob()
```
| 85,239 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
from collections import Counter
import string
import math
import bisect
#import random
import sys
# sys.setrecursionlimit(10**6)
from fractions import Fraction
def array_int():
return [int(i) for i in sys.stdin.readline().split()]
def vary(arrber_of_variables):
if arrber_of_variables==1:
return int(sys.stdin.readline())
if arrber_of_variables>=2:
return map(int,sys.stdin.readline().split())
def makedict(var):
return dict(Counter(var))
testcases=vary(1)
for _ in range(testcases):
n=vary(1)
num=array_int()
evens=[]
odds=[]
num2=[]
for i in range(n):
if i%2==0:
evens.append(num[i])
else:
odds.append(num[i])
evens.sort()
odds.sort()
for i in range(n//2):
num2.append(evens[i])
num2.append(odds[i])
if n%2!=0:
num2.append(evens[-1])
if sorted(num)==num2:
print('YES')
else:
print('NO')
```
| 85,240 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
t = int(input())
for _ in range(t):
n = int(input())
a = []
cache = []
for q in range(10 ** 5):
cache.append([0, 0])
ind = 0
for i in input().split():
i = int(i)
if ind % 2 == 0:
cache[i - 1][0] += 1
else:
cache[i - 1][1] += 1
ind += 1
a.append(i)
a_sorted = a.copy()
a_sorted.sort()
#print(cache[:5])
ind = 0
ans = 'YES'
while ind < n:
cur = a_sorted[ind]
if ind % 2 == 0:
cache[cur - 1][0] -= 1
else:
cache[cur - 1][1] -= 1
#print(cur, cache[:5])
ind += 1
if ind < n:
if a_sorted[ind - 1] != a_sorted[ind]:
if cache[cur - 1] != [0, 0]:
ans = 'NO'
break
print(ans)
```
| 85,241 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
zoz = [int(x) for x in input().split()]
l1 = sorted([zoz[i] for i in range(n) if (i%2 == 0)])
l2 = sorted([zoz[i] for i in range(n) if (i%2 == 1)])
new_zoz = []
x = y = 0
while(x<len(l1) or y<len(l2)):
if (x<len(l1)):
new_zoz.append(l1[x]); x += 1
if (y<len(l2)):
new_zoz.append(l2[y]); y += 1
zoz.sort()
if zoz != new_zoz:
print("No")
else:
print("Yes")
```
| 85,242 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
# ____ _ _ _ _ _
# / ___| __ _ _ __ __ _ | | | | __ _ _ __ ___| |__ (_) |_
# | | _ / _` | '__/ _` |_____| |_| |/ _` | '__/ __| '_ \| | __|
# | |_| | (_| | | | (_| |_____| _ | (_| | | \__ \ | | | | |_
# \____|\__,_|_| \__, | |_| |_|\__,_|_| |___/_| |_|_|\__|
# |___/
from typing import Counter
from sys import *
from collections import defaultdict
from math import *
def vinp():
return map(int,stdin.readline().split())
def linp():
return list(map(int,stdin.readline().split()))
def sinp():
return stdin.readline()
def inp():
return int(stdin.readline())
def mod(f):
return f % 1000000007
def pr(*x):
print(*x , flush=True)
def finp():
f=open("input.txt","r")
f=f.read().split("\n")
return f
def finp():
f=open("input.txt","r")
f=f.read().split("\n")
return f
def fout():
return open("output.txt","w")
def fpr(f,x):
f.write(x+"\n")
def csort(c):
sorted(c.items(), key=lambda pair: pair[1], reverse=True)
def indc(l,n):
c={}
for i in range(n):
c[l[i]]=c.get(l[i],[])+[i+1]
return c
if __name__ =="__main__":
cou=inp()
for i in range(cou):
# n,m=vinp()
# st=[sinp() for i in range(n)]
# st2=[sinp() for i in range(n-1)]
# l=[]
# for i in range(m):
# d = defaultdict(int)
# for s in st:
# d[s[i]] += 1
# for s in st2:
# d[s[i]] -= 1
# if d[s[i]] == 0:
# del d[s[i]]
# for j in d:
# l.append(j)
# pr("".join(l))
n = inp()
l = linp()
l2= sorted(l)
a,b,c,d = [],[],[],[]
for i in range(0,n,2):
try:
a.append(l2[i])
b.append(l[i])
c.append(l2[i+1])
d.append(l[i+1])
except:
pass
b=sorted(b)
d=sorted(d)
if a==b and c==d:
pr('YES')
else:
pr('NO')
```
| 85,243 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
t=int(input())
for _ in range (t):
n=int(input())
#n,m=map(int,input().split())
a=list(map(int,input().split()))
#tp=list(map(int,input().split()))
#s=input()
b=[[a[i],i]for i in range (n)]
d=defaultdict(list)
b.sort()
#print(b)
for i in range (n):
c=(abs(b[i][1]-i))%2
if not c:
if d[b[i][0]] and d[b[i][0]][-1]==0:
d[b[i][0]].pop()
else:
d[b[i][0]].append(0)
else:
if d[b[i][0]] and d[b[i][0]][-1]==1:
d[b[i][0]].pop()
else:
d[b[i][0]].append(1)
#print(d)
ch=1
for i in d:
if sum(d[i]):
ch=0
break
if ch:
print("YES")
else:
print("NO")
```
| 85,244 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
import sys
from collections import Counter
input = sys.stdin.readline
for nt in range(int(input())):
n = int(input())
a = list(map(int,input().split()))
b = sorted(a)
d = {}
ans = "YES"
for i in range(n):
if a[i] in d:
d[a[i]][i%2] += 1
else:
d[a[i]] = [0, 0]
d[a[i]][i%2] += 1
for i in range(n):
d[b[i]][i%2] -= 1
for i in d:
if d[i][0]!=0 or d[i][1]!=0:
ans = "NO"
print (ans)
```
| 85,245 |
Provide tags and a correct Python 3 solution for this coding contest problem.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Tags: sortings
Correct Solution:
```
import io,os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
t = 1
while t<=T:
n = int(input())
arr = list(map(int,input().split()))
dic = {}
for i in range(n):
if arr[i] not in dic: dic[arr[i]] = []
dic[arr[i]].append(i)
after = sorted(arr)
i = 0
flag = True
while i<n:
odd = 0
even = 0
if i%2==0: even += 1
else: odd += 1
while i+1<n and after[i+1]==after[i]:
i += 1
if i%2==0: even += 1
else: odd += 1
# print(even,odd)
oriseq = dic[after[i]]
for j in oriseq:
if j%2==0: even -= 1
else: odd -= 1
# print(even,odd)
if odd!=0 or even!=0:
flag = False
break
i += 1
if flag: print("YES")
else: print("NO")
t += 1
```
| 85,246 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
t = int(input())
while t:
t -= 1
n = int(input())
a = list(map(int, input().split()))
b = a[:]
b.sort()
even = {}
odd = {}
for i in range(n):
odd[a[i]] = 0
even[a[i]] = 0
for i in range(n):
if(i % 2 == 0):
even[b[i]] += 1
else:
odd[b[i]] += 1
f = 0
# print(odd, even)
for i in range(n):
if(i % 2 == 0):
if(even[a[i]] <= 0):
f = 1
break
even[a[i]] -= 1
else:
if(odd[a[i]] <= 0):
f = 1
break
odd[a[i]] -= 1
if(f == 1):
print("NO")
else:
print("YES")
```
Yes
| 85,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
arr1 = [int(w) for w in input().split(' ')]
from collections import defaultdict
odd = defaultdict(int)
even = defaultdict(int)
arr2 = arr1.copy()
arr2.sort()
for i in range(n):
if i%2==0:
even[arr1[i]] += 1
else:
odd[arr1[i]] += 1
ans = 'YES'
for i in range(n):
if i%2==0:
if even[arr2[i]] > 0:
even[arr2[i]] -= 1
else:
ans = 'NO'
break
else:
if odd[arr2[i]] > 0:
odd[arr2[i]] -= 1
else:
ans = 'NO'
break
print(ans)
```
Yes
| 85,248 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from collections import defaultdict
for _ in range(int(input())):
n=int(input())
a=list(map(int,input().split()))
o=defaultdict(lambda:0)
e=defaultdict(lambda:0)
for i in range(n):
if i%2==0:
e[a[i]]+=1
else:
o[a[i]]+=1
a.sort()
am=True
for i in range(n):
if i%2==0:
e[a[i]]-=1
else:
o[a[i]]-=1
if e[a[i]]<0 or o[a[i]]<0:
am=False
break
if am:
print("YES")
else:
print("NO")
```
Yes
| 85,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
t = int(input())
while t > 0:
t -= 1
n = int(input())
a = input().split()
a = [int(x) for x in a]
if sorted(a)[::2] == sorted(a[::2]):
print('YES')
else:
print('NO')
```
Yes
| 85,250 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from collections import Counter
for _ in range(int(input())):
n=int(input())
l1=[]
l=list(map(int,input().split()))
d=Counter(l)
for a,b in enumerate(l):
l1.append([b,a])
ans=sorted(l1)
for i in range(0,n,2):
if abs(ans[i][1]-i)%2!=0:
print("NO")
break
else:
print("YES")
```
No
| 85,251 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from itertools import combinations_with_replacement
import sys
from sys import stdin
import math
import bisect
#Find Set LSB = (x&(-x)), isPowerOfTwo = (x & (x-1))
# 1<<x =2^x
#x^=1<<pos flip the bit at pos
def BinarySearch(a, x):
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
def iinput():
return int(input())
def minput():
return map(int,input().split())
def linput():
return list(map(int,input().split()))
def fiinput():
return int(stdin.readline())
def fminput():
return map(int,stdin.readline().strip().split())
def flinput():
return list(map(int,stdin.readline().strip().split()))
for _ in range(fiinput()):
n=fiinput()
# flist=[0 for i in range(100001)]
dict2={}
list1=linput()
list2=sorted(list1)
for i in range(n):
ele=list2[i]
if(ele in dict2):
dict2[ele].append(i)
else:
dict2[ele]=[i]
dict1={}
for i in range(n):
ele=list1[i]
if(ele in dict1):
dict1[ele].append(i)
else:
dict1[ele]=[i]
f=0
for i in dict1:
l1=dict1[i]
l2=dict2[i]
s=0
for j in range(len(l1)):
s+=abs(l1[j]-l2[j])
if(s%2!=0):
f=1
break
if(f==1):
print("NO")
else:
print("YES")
```
No
| 85,252 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
import io
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
from collections import Counter
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
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")
#-------------------game starts now-----------------------------------------------------
#mod = 9223372036854775807
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a,b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: a+b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
MOD=10**9+7
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
mod=10**9+7
omod=998244353
#-------------------------------------------------------------------------
prime = [True for i in range(10001)]
prime[0]=prime[1]=False
#pp=[0]*10000
def SieveOfEratosthenes(n=10000):
p = 2
c=0
while (p <= n):
if (prime[p] == True):
c+=1
for i in range(p, n+1, p):
#pp[i]=1
prime[i] = False
p += 1
#-----------------------------------DSU--------------------------------------------------
class DSU:
def __init__(self, R, C):
#R * C is the source, and isn't a grid square
self.par = range(R*C + 1)
self.rnk = [0] * (R*C + 1)
self.sz = [1] * (R*C + 1)
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr: return
if self.rnk[xr] < self.rnk[yr]:
xr, yr = yr, xr
if self.rnk[xr] == self.rnk[yr]:
self.rnk[xr] += 1
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
def size(self, x):
return self.sz[self.find(x)]
def top(self):
# Size of component at ephemeral "source" node at index R*C,
# minus 1 to not count the source itself in the size
return self.size(len(self.sz) - 1) - 1
#---------------------------------Lazy Segment Tree--------------------------------------
# https://github.com/atcoder/ac-library/blob/master/atcoder/lazysegtree.hpp
class LazySegTree:
def __init__(self, _op, _e, _mapping, _composition, _id, v):
def set(p, x):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
_d[p] = x
for i in range(1, _log + 1):
_update(p >> i)
def get(p):
assert 0 <= p < _n
p += _size
for i in range(_log, 0, -1):
_push(p >> i)
return _d[p]
def prod(l, r):
assert 0 <= l <= r <= _n
if l == r:
return _e
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push(r >> i)
sml = _e
smr = _e
while l < r:
if l & 1:
sml = _op(sml, _d[l])
l += 1
if r & 1:
r -= 1
smr = _op(_d[r], smr)
l >>= 1
r >>= 1
return _op(sml, smr)
def apply(l, r, f):
assert 0 <= l <= r <= _n
if l == r:
return
l += _size
r += _size
for i in range(_log, 0, -1):
if ((l >> i) << i) != l:
_push(l >> i)
if ((r >> i) << i) != r:
_push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
_all_apply(l, f)
l += 1
if r & 1:
r -= 1
_all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, _log + 1):
if ((l >> i) << i) != l:
_update(l >> i)
if ((r >> i) << i) != r:
_update((r - 1) >> i)
def _update(k):
_d[k] = _op(_d[2 * k], _d[2 * k + 1])
def _all_apply(k, f):
_d[k] = _mapping(f, _d[k])
if k < _size:
_lz[k] = _composition(f, _lz[k])
def _push(k):
_all_apply(2 * k, _lz[k])
_all_apply(2 * k + 1, _lz[k])
_lz[k] = _id
_n = len(v)
_log = _n.bit_length()
_size = 1 << _log
_d = [_e] * (2 * _size)
_lz = [_id] * _size
for i in range(_n):
_d[_size + i] = v[i]
for i in range(_size - 1, 0, -1):
_update(i)
self.set = set
self.get = get
self.prod = prod
self.apply = apply
MIL = 1 << 20
def makeNode(total, count):
# Pack a pair into a float
return (total * MIL) + count
def getTotal(node):
return math.floor(node / MIL)
def getCount(node):
return node - getTotal(node) * MIL
nodeIdentity = makeNode(0.0, 0.0)
def nodeOp(node1, node2):
return node1 + node2
# Equivalent to the following:
return makeNode(
getTotal(node1) + getTotal(node2), getCount(node1) + getCount(node2)
)
identityMapping = -1
def mapping(tag, node):
if tag == identityMapping:
return node
# If assigned, new total is the number assigned times count
count = getCount(node)
return makeNode(tag * count, count)
def composition(mapping1, mapping2):
# If assigned multiple times, take first non-identity assignment
return mapping1 if mapping1 != identityMapping else mapping2
#---------------------------------Pollard rho--------------------------------------------
def memodict(f):
"""memoization decorator for a function taking a single argument"""
class memodict(dict):
def __missing__(self, key):
ret = self[key] = f(key)
return ret
return memodict().__getitem__
def pollard_rho(n):
"""returns a random factor of n"""
if n & 1 == 0:
return 2
if n % 3 == 0:
return 3
s = ((n - 1) & (1 - n)).bit_length() - 1
d = n >> s
for a in [2, 325, 9375, 28178, 450775, 9780504, 1795265022]:
p = pow(a, d, n)
if p == 1 or p == n - 1 or a % n == 0:
continue
for _ in range(s):
prev = p
p = (p * p) % n
if p == 1:
return math.gcd(prev - 1, n)
if p == n - 1:
break
else:
for i in range(2, n):
x, y = i, (i * i + 1) % n
f = math.gcd(abs(x - y), n)
while f == 1:
x, y = (x * x + 1) % n, (y * y + 1) % n
y = (y * y + 1) % n
f = math.gcd(abs(x - y), n)
if f != n:
return f
return n
@memodict
def prime_factors(n):
"""returns a Counter of the prime factorization of n"""
if n <= 1:
return Counter()
f = pollard_rho(n)
return Counter([n]) if f == n else prime_factors(f) + prime_factors(n // f)
def distinct_factors(n):
"""returns a list of all distinct factors of n"""
factors = [1]
for p, exp in prime_factors(n).items():
factors += [p**i * factor for factor in factors for i in range(1, exp + 1)]
return factors
def all_factors(n):
"""returns a sorted list of all distinct factors of n"""
small, large = [], []
for i in range(1, int(n**0.5) + 1, 2 if n & 1 else 1):
if not n % i:
small.append(i)
large.append(n // i)
if small[-1] == large[-1]:
large.pop()
large.reverse()
small.extend(large)
return small
#---------------------------------Binary Search------------------------------------------
def binarySearch(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=n
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
res=mid
right = mid-1
else:
left = mid + 1
return res
def binarySearch1(arr, n,i, key):
left = 0
right = n-1
mid = 0
res=-1
while (left <= right):
mid = (right + left)//2
if (arr[mid][i] > key):
right = mid-1
else:
res=mid
left = mid + 1
return res
#---------------------------------running code------------------------------------------
t=1
t=int(input())
for _ in range (t):
n=int(input())
#n,m=map(int,input().split())
a=list(map(int,input().split()))
#tp=list(map(int,input().split()))
#s=input()
b=[[a[i],i]for i in range (n)]
d=defaultdict(list)
b.sort()
#print(b)
for i in range (n):
c=(abs(b[i][1]-i))%2
if not c:
d[b[i][0]].append(0)
else:
if d[b[i][0]] and d[b[i][0]]==1:
d[b[i][0]].pop()
else:
d[b[i][0]].append(1)
#print(d)
ch=1
for i in d:
if sum(d[i]):
ch=0
break
if ch:
print("YES")
else:
print("NO")
```
No
| 85,253 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
AquaMoon has n friends. They stand in a row from left to right, and the i-th friend from the left wears a T-shirt with a number a_i written on it. Each friend has a direction (left or right). In the beginning, the direction of each friend is right.
AquaMoon can make some operations on friends. On each operation, AquaMoon can choose two adjacent friends and swap their positions. After each operation, the direction of both chosen friends will also be flipped: left to right and vice versa.
AquaMoon hopes that after some operations, the numbers written on the T-shirt of n friends in the row, read from left to right, become non-decreasing. Also she wants, that all friends will have a direction of right at the end. Please find if it is possible.
Input
The input consists of multiple test cases. The first line contains a single integer t (1 β€ t β€ 50) β the number of test cases.
The first line of each test case contains a single integer n (1 β€ n β€ 10^5) β the number of Aquamoon's friends.
The second line contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β the numbers, written on the T-shirts.
It is guaranteed that the sum of n for all test cases does not exceed 10^5.
Output
For each test case, if there exists a possible sequence of operations, print "YES" (without quotes); otherwise, print "NO" (without quotes).
You can print each letter in any case (upper or lower).
Example
Input
3
4
4 3 2 5
4
3 3 2 2
5
1 2 3 5 4
Output
YES
YES
NO
Note
The possible list of operations in the first test case:
1. Swap a_1 and a_2. The resulting sequence is 3, 4, 2, 5. The directions are: left, left, right, right.
2. Swap a_2 and a_3. The resulting sequence is 3, 2, 4, 5. The directions are: left, left, right, right.
3. Swap a_1 and a_2. The resulting sequence is 2, 3, 4, 5. The directions are: right, right, right, right.
Submitted Solution:
```
from collections import Counter
for _ in range(int(input())):
n=int(input())
l1=[]
l=list(map(int,input().split()))
d=Counter(l)
for a,b in enumerate(l):
l1.append([b,a])
ans=sorted(l1)
for i in range(n):
if (ans[i][1]-i)%2!=0:
print("NO")
break
else:
print("YES")
```
No
| 85,254 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
t= int(input())
n, m, List = 10000, 15000, []
def function(input):
if input == 0:
return (0, 1)
a, b = function(input >> 1)
a, b = ((2 * a * b - a * a) % n, (b * b + a * a) % n)
if input & 1:
a, b = (b % n, (a + b) % n)
return (a, b)
for j in range(m):
if function(j)[0] == t % n:
List.append(j)
while n <(10**13):
n *= 10;
Test = []
for i in List:
for j in range(10):
if function(i + j * m)[0] == t % n:
Test.append(i + j * m)
List = Test;
m *= 10
if List == []:
break
if List == []:
print(-1)
else:
List.sort()
print(List[0])
```
| 85,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
ak=int(10**13)
f=int(input())
n,m,List=10000,15000,[]
def Fun1(input):
if input==0:
return (0,1)
a,b=Fun1(input>>1)
a,b=((2*a*b-a*a)%n,(b*b+a*a)%n)
if input&1:
a,b=(b%n,(a+b)%n)
return (a,b)
for j in range(m):
if Fun1(j)[0]==f%n:
List.append(j)
while n<ak:
n*=10;
Test=[]
for i in List:
for j in range(10):
if Fun1(i+j*m)[0]==f%n:
Test.append(i+j*m)
List=Test;m*=10
if List==[]:
break
if List==[]:
print(-1)
else:
List.sort()
print(List[0])
```
| 85,256 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
low_n = 1000
high_m = 15000
limit = int(10 ** 13)
f = int(input())
inputList = []
def customFunction(i):
if i == 0:
return (0, 1)
a, b = customFunction(i >> 1)
a, b = ((2 * a * b - a * a) % low_n, (b * b + a * a) % low_n)
if i & 1:
a, b = (b % low_n, (a + b) % low_n)
return (a, b)
i = 0
while i < high_m:
if customFunction(i)[0] == f % low_n:
inputList.append(i)
i += 1
while low_n < limit:
low_n *= 10
tempList = []
for i in inputList:
for j in range(10):
if customFunction(i + j * high_m)[0] == f % low_n:
tempList.append(i + j * high_m)
inputList = tempList
high_m *= 10
if inputList == []:
break
if inputList == []:
print(-1)
else:
inputList = sorted(inputList)
print(inputList[0])
```
| 85,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
n,m,limn,f,L=10000,15000,int(10**13),int(input()),[]
def F(i):
if i==0:
return (0,1)
a,b=F(i>>1)
a,b=((2*a*b-a*a)%n,(b*b+a*a)%n)
if i&1:
a,b=(b%n,(a+b)%n)
return (a,b)
for i in range(m):
if F(i)[0]==f%n:
L.append(i)
while n<limn:
n*=10;
T=[]
for i in L:
for j in range(10):
if F(i+j*m)[0]==f%n:
T.append(i+j*m)
L=T;m*=10
if L==[]:
break
if L==[]:
print(-1)
else:
L.sort()
print(L[0])
```
| 85,258 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
n,m,l,f,L=10000,15000,int(10**13),int(input()),[]
def F(i):
if i==0:
return (0,1)
x,y=F(i>>1)
x,y=((2*x*y-x*x)%n,(y*y+x*x)%n)
if i&1:
x,y=(y%n,(x+y)%n)
return (x,y)
for i in range(m):
if F(i)[0]==f%n:
L.append(i)
while n<l:
n*=10;
T=[]
for i in L:
for j in range(10):
if F(i+j*m)[0]==f%n:
T.append(i+j*m)
L=T;m*=10
if L==[]:
break
if L==[]:
print(-1)
else:
L.sort()
print(L[0])
```
| 85,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
p, q, li, s, l = 10000, 15000, int(10 ** 13), int(input()), []
def Fibo(i):
if i == 0:
return (0, 1)
a, b = Fibo(i >> 1)
a, b = ((2 * a * b - a * a) % p, (b * b + a * a) % p)
if i & 1:
a, b = (b % p, (a + b) % p)
return (a, b)
for i in range(q):
if Fibo(i)[0] == s % p:
l.append(i)
while p < li:
p *= 10;
T = []
for i in l:
for j in range(10):
if Fibo(i + j * q)[0] == s % p:
T.append(i + j * q)
l = T;
q *= 10
if l == []:
break
if l == []:
print(-1)
else:
l.sort()
print(l[0])
```
| 85,260 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
n=1000
m=15000
limit=int(10**13)
x=int(input())
l=[]
def fun(i):
if i==0:
return(0,1)
a,b=fun(i>>1)
a,b=((2*a*b-a*a)%n,(b*b+a*a)%n)
if i & 1:
a,b=(b%n,(a+b)%n)
return (a,b)
i=0
while i<m:
if fun(i)[0]==x%n:
l.append(i)
i+=1
while n<limit:
n*=10
t=[]
for i in l:
for j in range(10):
if fun(i+j*m)[0]==x%n:
t.append(i+j*m)
l=t
m*=10
if l==[]:
break
if l==[]:
print(-1)
else:
l=sorted(l)
print(l[0])
```
| 85,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Tags: brute force, math, matrices
Correct Solution:
```
mo = 10 ** 13
p = [
1, 60, 300, 1500, 15000, 150000, 1500000, 15000000,
150000000, 1500000000, 15000000000, 150000000000,
1500000000000, 15000000000000
]
class mat(object):
def __init__(self, a, b, c, d):
self.a, self.b, self.c, self.d = a, b, c, d
def times(self, k):
return mat(
(self.a * k.a + self.b * k.c) % mo,
(self.a * k.b + self.b * k.d) % mo,
(self.c * k.a + self.d * k.c) % mo,
(self.c * k.b + self.d * k.d) % mo
)
def copy(self):
return mat(self.a, self.b, self.c, self.d)
me, mt = mat(1, 0, 0, 1), mat(0, 1, 1, 1)
def fib(k):
ans, t = me.copy(), mt.copy()
while k > 0:
if k & 1:
ans = ans.times(t)
t = t.times(t)
k >>= 1
return ans.b
def gene(a, ta, b, tb, tab):
ab = []
for i in a:
for j in b:
y = -j // tb - 1
while j + y * tb < 0:
y += 1
while j + y * tb < tab:
if (j - i + y * tb) % ta == 0:
ab.append(j + y * tb)
y += 1
return ab
def filt(a, f, m):
r = f % m
return [i for i in a if (fib(i) % m == r)]
if __name__ == '__main__':
f = int(input())
a = filt(list(range(p[1])), f, 10)
b = a[:]
for i in range(2, 14):
m = 10 ** i
b = gene(a, p[1], b, p[i - 1], p[i])
b = filt(b, f, m)
print(min(b) if b else -1)
```
| 85,262 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
n, m, limn, f, L = 10000, 15000, int(10 ** 13), int(input()), []
def F(i):
if i == 0:
return (0, 1)
p, q = F(i >> 1)
p, q = ((2 * p * q - p * p) % n, (q * q + p * p) % n)
if i & 1:
p, q = (q % n, (p + q) % n)
return (p, q)
for i in range(m):
if F(i)[0] == f % n:
L.append(i)
while n < limn:
n *= 10;
Z = []
for i in L:
for j in range(10):
if F(i + j * m)[0] == f % n:
Z.append(i + j * m)
L = Z;
m *= 10
if L == []:
break
if L == []:
print(-1)
else:
L.sort()
print(L[0])
```
Yes
| 85,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
#https://codeforces.com/contest/193/problem/E
n, m, limn, f, L = 10000, 15000, int(10 ** 13), int(input()), []
def F(i):
if i == 0:
return (0, 1)
a, b = F(i >> 1)
a, b = ((2 * a * b - a * a) % n, (b * b + a * a) % n)
if i & 1:
a, b = (b % n, (a + b) % n)
return (a, b)
for i in range(m):
if F(i)[0] == f % n:
L.append(i)
while n < limn:
n *= 10;
T = []
for i in L:
for j in range(10):
if F(i + j * m)[0] == f % n:
T.append(i + j * m)
L = T;
m *= 10
if L == []:
break
if L == []:
print(-1)
else:
L.sort()
print(L[0])
```
Yes
| 85,264 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
x = int(10 ** 13)
f = int(input())
n, m, List = 10000, 15000, []
def Fun1(input):
if input == 0:
return (0, 1)
a, b = Fun1(input >> 1)
a, b = ((2 * a * b - a * a) % n, (b * b + a * a) % n)
if input & 1:
a, b = (b % n, (a + b) % n)
return (a, b)
for j in range(m):
if Fun1(j)[0] == f % n:
List.append(j)
while n < x:
n *= 10
Test = []
for i in List:
for j in range(10):
if Fun1(i + j * m)[0] == f % n:
Test.append(i + j * m)
List = Test
m *= 10
if List == []:
break
if List == []:
print(-1)
else:
List.sort()
print(List[0])
```
Yes
| 85,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
n=int(input())
n1=0
n2=1
n3=1
i=1
if n<=1:
print(n)
else:
while n3<=n:
n3=n2+n1
n1=n2
n2=n3
i=i+1
print(i)
```
No
| 85,266 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
n = int(input())
a1 = 1
a2 = 1
c=2
if(n == 2406684390626):
print(999999)
elif(n == 0):
print(0)
elif(n == 1):
print(1)
else:
while(a1 < n):
a1 += a2
a2 = a1 - a2
c+=1
#print(a1)
if(a1 == n):
print(c)
else:
print(-1)
```
No
| 85,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
def fibonacciNum(num):
if (num <= 1):
return num
firstNum = 0
secondNum = 1
thirdNum = 1
count = 1
while (num > thirdNum):
thirdNum = firstNum + secondNum
count += 1
firstNum = secondNum
secondNum = thirdNum
return count
n = int(input())
print(fibonacciNum(n))
```
No
| 85,268 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
John Doe has a list of all Fibonacci numbers modulo 1013. This list is infinite, it starts with numbers 0 and 1. Each number in the list, apart from the first two, is a sum of previous two modulo 1013. That is, John's list is made from the Fibonacci numbers' list by replacing each number there by the remainder when divided by 1013.
John got interested in number f (0 β€ f < 1013) and now wants to find its first occurrence in the list given above. Help John and find the number of the first occurence of number f in the list or otherwise state that number f does not occur in the list.
The numeration in John's list starts from zero. There, the 0-th position is the number 0, the 1-st position is the number 1, the 2-nd position is the number 1, the 3-rd position is the number 2, the 4-th position is the number 3 and so on. Thus, the beginning of the list looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
Input
The first line contains the single integer f (0 β€ f < 1013) β the number, which position in the list we should find.
Please, do not use the %lld specifier to read or write 64-bit integers in Π‘++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
Print a single number β the number of the first occurrence of the given number in John's list. If this number doesn't occur in John's list, print -1.
Examples
Input
13
Output
7
Input
377
Output
14
Submitted Solution:
```
fib_nums=[0,1]
while fib_nums[len(fib_nums)-1]<10000000000000:
fib_nums.append(fib_nums[len(fib_nums)-2]+fib_nums[len(fib_nums)-1])
n=int(input())
if n in fib_nums:
print(fib_nums.index(n))
else:
print(-1)
```
No
| 85,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as s1s2... s11, its mangled copy is s2s4s6s8s10s1s3s5s7s9s11.
For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2, 4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font.
Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first k elements of the DNA sequence after all the mutations.
Input
The first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length.
The second line contains a single integer k (1 β€ k β€ 3Β·106).
The third line contains a single integer n (0 β€ n β€ 5000) β the number of mutations. The next n lines describe the mutations in chronological order β each mutation is described by two numbers li and ri (1 β€ li β€ ri β€ 109), meaning that the continuous subsequence [li, ri] has become active and cloned itself, joining itself with the mangled copy.
It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least k elements.
Assume that the DNA elements are indexed starting from 1 and that the notation [l, r] meaning the continuous subsequence of DNA sequence that consists of r - l + 1 elements starting at the l-th DNA sequence element and ending at the r-th DNA sequence element.
Output
Output a single line, containing the first k letters of the mutated DNA sequence.
Examples
Input
GAGA
4
0
Output
GAGA
Input
ACGTACGT
16
2
1 2
2 8
Output
ACCAGTACCGACATCG
Note
In the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT".
Submitted Solution:
```
dna = input()
k = int(input())
n = int(input())
def mutation(word,start,end):
changed = word[start-1:end]
is_even_number = lambda x: x%2 == 0
is_odd_number = lambda x: x%2 != 0
changed_word = list(filter(is_even_number,range(1,len(changed)+1))) + list(filter(is_odd_number,range(1,len(changed)+1)))
changed_word = ''.join(list(map(lambda x:changed[x-1],changed_word)))
new_word = word[:end] + changed_word + word[end:]
return new_word
for i in range(n):
a,b = list(map(int,input().split()))
if a >= k:
continue
dna = mutation(dna[:k],a,b)
print (dna)
```
No
| 85,270 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as s1s2... s11, its mangled copy is s2s4s6s8s10s1s3s5s7s9s11.
For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2, 4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font.
Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first k elements of the DNA sequence after all the mutations.
Input
The first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length.
The second line contains a single integer k (1 β€ k β€ 3Β·106).
The third line contains a single integer n (0 β€ n β€ 5000) β the number of mutations. The next n lines describe the mutations in chronological order β each mutation is described by two numbers li and ri (1 β€ li β€ ri β€ 109), meaning that the continuous subsequence [li, ri] has become active and cloned itself, joining itself with the mangled copy.
It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least k elements.
Assume that the DNA elements are indexed starting from 1 and that the notation [l, r] meaning the continuous subsequence of DNA sequence that consists of r - l + 1 elements starting at the l-th DNA sequence element and ending at the r-th DNA sequence element.
Output
Output a single line, containing the first k letters of the mutated DNA sequence.
Examples
Input
GAGA
4
0
Output
GAGA
Input
ACGTACGT
16
2
1 2
2 8
Output
ACCAGTACCGACATCG
Note
In the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT".
Submitted Solution:
```
dna = input()
k = int(input())
n = int(input())
def mutation(word,start,end):
changed = word[start-1:end]
is_even_number = lambda x: x%2 == 0
is_odd_number = lambda x: x%2 != 0
changed_word = list(filter(is_even_number,range(1,len(changed)+1))) + list(filter(is_odd_number,range(1,len(changed)+1)))
changed_word = ''.join(list(map(lambda x:changed[x-1],changed_word)))
new_word = word[:end] + changed_word + word[end:]
return new_word
for i in range(n):
a,b = list(map(int,input().split()))
if len(dna) > 16 and a >= 16:
continue
dna = mutation(dna,a,b)
print (dna[:k])
```
No
| 85,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Professor Bajtocy is conducting experiments on alien DNA. He has discovered that it is subject to repetitive mutations β each mutation happens in the same way: some continuous subsequence of the alien DNA becomes active, copies itself, the copy gets mangled and inserts itself right after the original subsequence. The mangled copy of the activated continuous subsequence is formed by first joining all the elements at the even positions in that subsequence, and then joining all the elements at the odd ones at the end. That is, if the activated subsequence consists of 11 elements and represented as s1s2... s11, its mangled copy is s2s4s6s8s10s1s3s5s7s9s11.
For example, if the original sequence was "ACTGG" and the mutation happened on the segment [2, 4] (that is the activated subsequence is "CTG"), the mutated DNA is: "ACTGTCGG". The mangled copy of the activated subsequence is marked with bold font.
Professor Bajtocy has written down the original DNA sequence and the mutations that sequentially happened to it, and he now asks you to recover the first k elements of the DNA sequence after all the mutations.
Input
The first line of input contains the original DNA sequence, consisting only of letters "A", "C", "T" and "G" and not exceeding 3Β·106 in length.
The second line contains a single integer k (1 β€ k β€ 3Β·106).
The third line contains a single integer n (0 β€ n β€ 5000) β the number of mutations. The next n lines describe the mutations in chronological order β each mutation is described by two numbers li and ri (1 β€ li β€ ri β€ 109), meaning that the continuous subsequence [li, ri] has become active and cloned itself, joining itself with the mangled copy.
It is guaranteed that the input data is correct, that is, no mutation acts on non-existing elements of the DNA sequence, and the resulting DNA sequence has at least k elements.
Assume that the DNA elements are indexed starting from 1 and that the notation [l, r] meaning the continuous subsequence of DNA sequence that consists of r - l + 1 elements starting at the l-th DNA sequence element and ending at the r-th DNA sequence element.
Output
Output a single line, containing the first k letters of the mutated DNA sequence.
Examples
Input
GAGA
4
0
Output
GAGA
Input
ACGTACGT
16
2
1 2
2 8
Output
ACCAGTACCGACATCG
Note
In the second example, after the first mutation the sequence is "ACCAGTACGT". After the second mutation it's "ACCAGTACCGACATCGT".
Submitted Solution:
```
dna = input()
k = int(input())
n = int(input())
def mutation(word,start,end):
changed = word[start-1:end]
is_even_number = lambda x: x%2 == 0
is_odd_number = lambda x: x%2 != 0
changed_word = list(filter(is_even_number,range(1,len(changed)+1))) + list(filter(is_odd_number,range(1,len(changed)+1)))
changed_word = ''.join(list(map(lambda x:changed[x-1],changed_word)))
new_word = word[:end] + changed_word + word[end:]
return new_word
for i in range(n):
a,b = list(map(int,input().split()))
if a >= k:
continue
dna = mutation(dna[:k-1],a,b)
print (dna)
```
No
| 85,272 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Tags: constructive algorithms, greedy, math
Correct Solution:
```
def find_all(s, c):
index = s.index(c)
while True:
yield index
try:
index = s.index(c, index + 1)
except ValueError:
break
n = int(input())
row, col, actions = [], [], []
available = list(range(1, n + 1))
for _ in range(n - 1):
(r, c) = map(int, input().split(' '))
row.append(r)
col.append(c)
for cur in range(n, 1, -1):
if not row:
break
# for column
if cur in col:
indices = list(find_all(col, cur))
zero = list(set(available) - set(col))[0]
actions.append([2, cur, zero])
for i in indices:
col[i] = zero
# row
try:
idx = row.index(cur)
indices = list(find_all(row, cur))
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
continue
except ValueError:
val = row[0]
indices = list(find_all(row, val))
actions.append([1, row[0], cur])
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
if not actions:
print(0)
else:
print(len(actions))
for move in actions:
print(*move)
```
| 85,273 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Tags: constructive algorithms, greedy, math
Correct Solution:
```
import os
from io import BytesIO, IOBase
import sys
def main():
n = int(input())
row = [0] * n
col = [0] * n
a = [[0 for j in range(n)] for i in range(n)]
for i in range(n - 1):
x, y = map(int, input().split())
row[x - 1] += 1
col[y - 1] += 1
a[x - 1][y - 1] = 1
ans = []
for i in range(n):
zci = -1 # zero column index
for j in range(n - i):
if col[j] == 0:
zci = j
break
if zci == -1:
break
if zci != (n - i - 1):
ans.append([2, zci + 1, n - i])
col[n - i - 1], col[zci] = col[zci], col[n - i - 1]
for j in range(n - i):
a[j][zci], a[j][n - i - 1] = a[j][n - i - 1], a[j][zci]
nzri = -1 # non zero row index
for j in range(n - i):
if row[j] != 0:
nzri = j
break
if nzri == -1:
break
if nzri != (n - i - 1):
ans.append([1, nzri + 1, n - i])
row[nzri], row[n - i - 1] = row[n - i - 1], row[nzri]
for j in range(n - i):
if a[nzri][j] == 1:
col[j] -= 1
a[nzri][j], a[n - i - 1][j] = a[n - i - 1][j], a[nzri][j]
print(len(ans))
for i in ans:
print(*i)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
| 85,274 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Tags: constructive algorithms, greedy, math
Correct Solution:
```
# https://codeforces.com/problemset/problem/266/C
n = int(input())
P = [list(map(int, input().split())) for _ in range(n-1)]
col = set()
row = set()
sCol = {}
sRow = {}
for x, y in P:
row.add(x)
col.add(y)
n_col = len(col)
n_row = len(row)
cur_col, cur_row = 1, n
used_col = {}
used_row = {}
for c in sorted(col):
if c > n_col:
while cur_col in used_col:
cur_col += 1
used_col[cur_col] = 1
sCol[c] = cur_col
else:
used_col[c] = 1
for r in sorted(row, reverse=True):
if r < n - n_row + 1:
while cur_row in used_row:
cur_row -= 1
used_row[cur_row] = 1
sRow[r] = cur_row
else:
used_row[r] = 1
for i, [x, y] in enumerate(P):
if x in sRow:
P[i][0] = sRow[x]
if y in sCol:
P[i][1] = sCol[y]
minCol = [float('inf') for _ in range(n_col+1)]
minCol[0] = 0
for x, y in P:
if x < minCol[y]:
minCol[y] = x
def sort(minCol):
swap = []
pos = {}
for col, val in enumerate(minCol):
if col == 0:
continue
if val not in pos:
pos[val] = set()
pos[val].add(col)
sortCol = sorted(minCol)
for i, val in enumerate(sortCol):
if i == 0:
continue
if val == minCol[i]:
pos[val].remove(i)
else:
col_ = next(iter(pos[val]))
pos[val].remove(col_)
pos[minCol[i]].remove(i)
pos[minCol[i]].add(col_)
minCol[col_] = minCol[i]
minCol[i] = val
swap.append([2, i, col_])
#print(minCol)
return swap
swap = sort(minCol)
ans = [[1, x, y] for x, y in sRow.items()] + [[2, x, y] for x, y in sCol.items()] + swap
print(len(ans))
print('\n'.join([' '.join([str(x) for x in line]) for line in ans]))
#2
#1 2
#3
#3 1
#1 3
#3
#2 1
#3 2
```
| 85,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
a = []
b = [0] * (n+1)
c = [10000] * (n+1)
for i in range(0,n-1):
p1,p2 = list(map(int,input().split()))
a.append((p1,p2))
b[p1] = max(b[p1],p2)
ans = []
for i in range(1,n+1):
if b[i]==0: continue
k = 0
for j in range(i,n+1):
if b[j]==0:
k=j
break
if k==0:break
b[j]=b[i]
b[i]=0
for j in range(0,n-1):
if a[j][0]==i: a[j]=(k,a[j][1])
ans.append((1,i,k))
for i in a:
c[i[1]]=min(c[i[1]],i[0])
for i in range(1,n+1):
k=i
for j in range(i+1,n+1):
if c[j]<c[i]: i=j
if (i==k): continue
ans.append((2,i,k))
c[0]=c[i];c[i]=c[k];c[k]=c[0]
print(len(ans))
for i in ans:print(i[0],i[1],i[2])
```
| 85,276 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Tags: constructive algorithms, greedy, math
Correct Solution:
```
n = int(input())
a, b, c = [], [0] * (n+1), [int(2e9)] * (n+1)
for i in range(n-1):
p1, p2 = map(int, input().split())
a.append((p1, p2))
b[p1] = max(b[p1], p2)
res = []
for i in range(1, n+1):
if b[i] == 0:
continue
k = 0
for j in range(i, n+1):
if b[j] == 0:
k = j
break
else:
break
b[j], b[i] = b[i], 0
for j in range(n-1):
if a[j][0] == i:
a[j] = (k, a[j][1])
res.append((1, i, k))
for i in a:
c[i[1]] = min(c[i[1]], i[0])
for i in range(1, n+1):
k = i
for j in range(i+1, n+1):
if c[j] < c[i]:
i = j
if i == k:
continue
res.append((2, i, k))
c[0], c[i], c[k] = c[i], c[k], c[0]
print(len(res))
for i in res:
print(i[0], i[1], i[2])
```
| 85,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Submitted Solution:
```
def find_all(s, c):
s = "".join(str(x) for x in s)
c = str(c)
index = s.find(c)
while index != -1:
yield index
index = s.find(c, index + 1)
n = int(input())
row, col, actions = [], [], []
available = list(range(1, n + 1))
for _ in range(n - 1):
(r, c) = map(int, input().split(' '))
row.append(r)
col.append(c)
for cur in range(n, 1, -1):
if not row:
break
print(row)
print(col)
# for column
if cur in col:
idx = col.index(cur)
zero = list(set(available) - set(col))[0]
col[idx] = zero
actions.append([2, cur, zero])
# row
try:
idx = row.index(cur)
indices = list(find_all(row, cur))
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
continue
except ValueError:
val = row[0]
indices = list(find_all(row, val))
print(indices)
actions.append([1, row[0], cur])
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
if not actions:
print(0)
else:
print(len(actions))
for move in actions:
print(*move)
```
No
| 85,278 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Submitted Solution:
```
def find_all(s, c):
s = "".join(str(x) for x in s)
c = str(c)
index = s.find(c)
while index != -1:
yield index
index = s.find(c, index + 1)
n = int(input())
row, col, actions = [], [], []
available = list(range(1, n + 1))
for _ in range(n - 1):
(r, c) = map(int, input().split(' '))
row.append(r)
col.append(c)
for cur in range(n, 1, -1):
if not row:
break
# for column
if cur in col:
idx = col.index(cur)
zero = list(set(available) - set(col))[0]
col[idx] = zero
actions.append([2, cur, zero])
# row
try:
idx = row.index(cur)
indices = list(find_all(row, cur))
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
continue
except ValueError:
val = row[0]
indices = list(find_all(row, val))
actions.append([1, row[0], cur])
indices.reverse()
for i in indices:
del row[i], col[i]
del available[-1]
if not actions:
print(0)
else:
print(len(actions))
for move in actions:
print(*move)
```
No
| 85,279 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a square matrix consisting of n rows and n columns. We assume that the rows are numbered from 1 to n from top to bottom and the columns are numbered from 1 to n from left to right. Some cells (n - 1 cells in total) of the the matrix are filled with ones, the remaining cells are filled with zeros. We can apply the following operations to the matrix:
1. Swap i-th and j-th rows of the matrix;
2. Swap i-th and j-th columns of the matrix.
You are asked to transform the matrix into a special form using these operations. In that special form all the ones must be in the cells that lie below the main diagonal. Cell of the matrix, which is located on the intersection of the i-th row and of the j-th column, lies below the main diagonal if i > j.
Input
The first line contains an integer n (2 β€ n β€ 1000) β the number of rows and columns. Then follow n - 1 lines that contain one's positions, one per line. Each position is described by two integers xk, yk (1 β€ xk, yk β€ n), separated by a space. A pair (xk, yk) means that the cell, which is located on the intersection of the xk-th row and of the yk-th column, contains one.
It is guaranteed that all positions are distinct.
Output
Print the description of your actions. These actions should transform the matrix to the described special form.
In the first line you should print a non-negative integer m (m β€ 105) β the number of actions. In each of the next m lines print three space-separated integers t, i, j (1 β€ t β€ 2, 1 β€ i, j β€ n, i β j), where t = 1 if you want to swap rows, t = 2 if you want to swap columns, and i and j denote the numbers of rows or columns respectively.
Please note, that you do not need to minimize the number of operations, but their number should not exceed 105. If there are several solutions, you may print any of them.
Examples
Input
2
1 2
Output
2
2 1 2
1 1 2
Input
3
3 1
1 3
Output
3
2 2 3
1 1 3
1 1 2
Input
3
2 1
3 2
Output
0
Submitted Solution:
```
n = int(input())
v = []
for i in range(n-1):
x,y = map(int, input().split())
if i+2 != x :
v.append((1,i+2,x))
if (i+1 != y):
v.append((2,i+1,y))
print(len(v))
for o in v:
for x in o:
print(x, end=' ')
print()
```
No
| 85,280 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 50) β the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 β€ ai β€ 50). ai means the amount of wash basins in the i-th room.
Output
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Examples
Input
1 1
2
Output
1.00000000000000000000
Input
2 2
1 1
Output
1.50000000000000000000
Input
2 3
1 1 1
Output
1.33333333333333350000
Input
7 5
1 1 2 3 1
Output
2.50216960000000070000
Tags: combinatorics, dp, probabilities
Correct Solution:
```
n, m = map(int, input().split())
a = list(map(int, input().split()))
prob = [(n+1)*[None] for _ in range(m+1)]
for k in range(1, m+1):
prob[k][0] = [1.0]
for i in range(1, n+1):
prob[k][i] = (i+1)*[0.0]
for j in range(i):
prob[k][i][j+1] += prob[k][i-1][j]*(1.0/k)
prob[k][i][j] += prob[k][i-1][j]*(1-1.0/k)
dp = [[(n+1)*[0.0] for _ in range(n+1)] for _ in range(m+1)]
dp[m][n][0] = 1.0
for k in range(m, 0, -1):
for i in range(n+1):
for x in range(n+1):
t = dp[k][i][x]
if t == 0.0:
continue
for j in range(i+1):
dp[k-1][i-j][max(x, (j+a[m-k]-1)//a[m-k])] += t*prob[k][i][j]
res = 0
for x in range(n+1):
res += x*dp[0][0][x]
print ("%.13f" % res)
```
| 85,281 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 50) β the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 β€ ai β€ 50). ai means the amount of wash basins in the i-th room.
Output
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Examples
Input
1 1
2
Output
1.00000000000000000000
Input
2 2
1 1
Output
1.50000000000000000000
Input
2 3
1 1 1
Output
1.33333333333333350000
Input
7 5
1 1 2 3 1
Output
2.50216960000000070000
Tags: combinatorics, dp, probabilities
Correct Solution:
```
import sys
MAX_N = 55
line = list(map(int, sys.stdin.readline().split(" ")))
studc = line[0]
roomc = line[1]
arr = list(map(int, sys.stdin.readline().split(" ")))
ncr = [[0 for i in range(MAX_N)] for j in range(MAX_N)]
ncr[0][0] = 1
for i in range(1, MAX_N):
ncr[i][0] = 1;
for j in range(1, MAX_N):
ncr[i][j] = ncr[i - 1][j - 1] + ncr[i - 1][j]
upto = [0 for i in range(MAX_N)] # upto[i] of ways to pick such that no queue exceeds i people
for i in range(1, MAX_N):
dp = [[0 for j in range(MAX_N)] for k in range(MAX_N)]
dp[0][0] = 1
for j in range(roomc):
for k in range(0, min(studc, i * arr[j]) + 1):
for l in range(0, studc - k + 1):
dp[j + 1][k + l] += dp[j][l] * ncr[studc - l][k]
upto[i] = dp[roomc][studc]
ans = 0;
for i in range(1, MAX_N):
ans += (upto[i] - upto[i - 1]) * i
print('%.12f' % (ans / (roomc ** studc)))
```
| 85,282 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n students living in the campus. Every morning all students wake up at the same time and go to wash. There are m rooms with wash basins. The i-th of these rooms contains ai wash basins. Every student independently select one the rooms with equal probability and goes to it. After all students selected their rooms, students in each room divide into queues by the number of wash basins so that the size of the largest queue is the least possible. Calculate the expected value of the size of the largest queue among all rooms.
Input
The first line contains two positive integers n and m (1 β€ n, m β€ 50) β the amount of students and the amount of rooms. The second line contains m integers a1, a2, ... , am (1 β€ ai β€ 50). ai means the amount of wash basins in the i-th room.
Output
Output single number: the expected value of the size of the largest queue. Your answer must have an absolute or relative error less than 10 - 9.
Examples
Input
1 1
2
Output
1.00000000000000000000
Input
2 2
1 1
Output
1.50000000000000000000
Input
2 3
1 1 1
Output
1.33333333333333350000
Input
7 5
1 1 2 3 1
Output
2.50216960000000070000
Tags: combinatorics, dp, probabilities
Correct Solution:
```
from sys import stdin
input = stdin.buffer.readline
def c(n, k):
if k > n:
return 0
a = b = 1
for i in range(n - k + 1, n + 1):
a *= i
for i in range(1, k + 1):
b *= i
return a // b
n, m = map(int, input().split())
*a, = map(int, input().split())
dp = [[[0 for k in range(n + 1)] for j in range(m + 1)] for i in range(n + 1)]
p = [[[0 for x in range(n + 1)] for j in range(m + 1)] for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
for x in range(i + 1):
p[i][j][x] = c(i, x) * (1 / j) ** x * ((j - 1) / j) ** (i - x)
for i in range(n + 1):
for j in range(1, m + 1):
for k in range(n + 1):
if i == 0:
dp[i][j][k] = k
continue
if j == 1:
dp[i][j][k] = max(k, (i + a[0] - 1) // a[0])
continue
if j == 0:
continue
for x in range(i + 1):
dp[i][j][k] += p[i][j][x] * (dp[i - x][j - 1][max(k, (x + a[j - 1] - 1) // a[j - 1])])
print(dp[n][m][0])
# print(dp[0], dp[1], dp[2], sep='\n')
```
| 85,283 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
arr = map(int, input().split())
s, j, all_res = 0, 0, []
for i, q in enumerate(arr, 1):
if s - j * (n - i) * q < k:
all_res.append(str(i))
else:
s += q * j
j += 1
print('\n'.join(all_res))
```
| 85,284 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
f = lambda: map(int, input().split())
n, k = f()
j = 0
for i, q in enumerate(f(), 1):
if j * (i - n) * q < k: print(i)
else:
k -= q * j
j += 1
```
| 85,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
c, m, l, r = 0, 0, [], 0
for e in [int(i) for i in input().split()]:
d = m - c * (n - c - 1) * e
r+= 1
if d < k:
n -= 1
l += [r]
else:
m += c * e
c += 1
l.sort()
for e in l: print(e)
```
| 85,286 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
from sys import stdin,stdout
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
for _ in range(1):#nmbr()):
n,k=lst()
a=lst()
removed=0
positive_term=0
for i in range(1,n):
negative_term=(i-removed)*a[i]*(n-i-1)
if (positive_term-negative_term)<k:
removed+=1
stdout.write(str(i+1)+'\n')
else:positive_term += (i - removed) * a[i]
```
| 85,287 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
c, v = 0, []
for i, a in enumerate(map(int, input().split())):
j = i + 1 - len(v)
d = c - (j - 1) * (n - j) * a
if d < k:
v.append(i + 1)
n -= 1
else:
c += a * (j - 1)
print('\n'.join(map(str, v)))
```
| 85,288 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
a = [int(x) for x in input().split()]
rmv = 0
ss = 0
for ii in range(n):
i = ii-rmv
if ss - (n-rmv-i-1)*a[ii]*i < k:
rmv += 1
print(ii+1)
else:
ss += a[ii]*i
```
| 85,289 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
S = D = i = 0
ans = []
for val in map(int, input().split()):
f = (n - i - 1) * val * (i - D)
if S - f < k:
D += 1
ans.append(i + 1)
else: S += val * (i - D)
i += 1
print(' '.join(map(str, ans)))
```
| 85,290 |
Provide tags and a correct Python 3 solution for this coding contest problem.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Tags: implementation
Correct Solution:
```
r = lambda: map(int, input().split())
n, k = r()
data = list(r())
alc = 0
total = 0
for i in range(n):
d = alc - total * (n - (i - total) - total - 1) * data[i]
if d >= k:
alc += total * data[i]
total += 1
else:
print(i + 1)
```
| 85,291 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
n, k = map(int, input().split())
s = 0
rem, i = 0, 1
ans = []
for cur in map(int, input().split()):
add = (n - i) * cur * (i - rem - 1)
if s - add < k:
rem += 1
ans.append(i)
else:
s += cur * (i - rem - 1)
i += 1
print(' '.join(map(str, ans)))
```
Yes
| 85,292 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = j = 0
for i, q in enumerate(f(), 1):
if s - j * (n - i) * q < k: print(i)
else:
s += q * j
j += 1
```
Yes
| 85,293 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
from sys import stdin,stdout
nmbr = lambda: int(stdin.readline())
lst = lambda: list(map(int,stdin.readline().split()))
def fn(a):
print('a',a)
n=len(a)
pos1=[0]
for i in range(1,n):
pos1+=[pos1[-1]+a[i]*i]
print('pos1',pos1)
neg=[]
for i in range(n):
neg+=[i*(n-i-1)*a[i]]
print('neg',neg)
d=[]
for i in range(1,n+1):
sm=0
for j in range(1,i):
sm+=a[j-1]*(j-1)-(n-i)*a[i-1]
d+=[sm]
print('d',d);
print('================================')
p=-1
for i in range(1,n):
if pos1[i-1]-neg[i]<k:
p=i
break
if p==-1:return
a.pop(p)
fn(a)
for _ in range(1):#nmbr()):
n,k=lst()
a=lst()
# fn(a)
# exit(0)
pos = [0]
for i in range(1, n):
pos += [pos[-1] + a[i] * i]
removed=0
positive_term=0
for i in range(1,n):
negative_term=(i-removed)*a[i]*(n-i-1)
# print(positive_term,positive_term-negative_term)
if (positive_term-negative_term)<k:
removed+=1
stdout.write(str(i+1)+'\n')
else:positive_term += (i - removed) * a[i]
```
Yes
| 85,294 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
tot = 0
nn = n
ii = 1
for i in range(n):
di = tot - (ii-1)*(nn-ii)*a[i]
if i == 0:
di = 0
# print(i, di)
if di < k:
print(i+1)
nn -= 1
else:
tot += a[i]*(ii-1)
ii += 1
```
Yes
| 85,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
def IO():
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
###################### MAIN PROGRAM #####################
def main():
# IO()
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = list()
run = int(0)
deleted = 0
for i in range(n):
ratingCh = run - a[i] * (n - i - 1) * (i)
if (ratingCh < k):
deleted += 1
ans.append(i)
else:
run += a[i] * i
for e in ans:
print(f"{e+1} ")
##################### END OF PROGRAM ####################
if __name__ == "__main__":
main()
```
No
| 85,296 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
def IO():
import sys
sys.stdout = open('output.txt', 'w')
sys.stdin = open('input.txt', 'r')
###################### MAIN PROGRAM #####################
def main():
#IO()
n, k = map(int, input().split())
a = list(map(int, input().split()))
ans = list()
run = int(0)
deleted = 0
for i in range(n):
ratingCh = run - a[i] * (n - i - 1) * (i - deleted)
if (ratingCh < k):
deleted += 1
ans.append(i)
else:
run += a[i] * i
for e in ans:
print(f"{e+1} ")
##################### END OF PROGRAM ####################
if __name__ == "__main__":
main()
```
No
| 85,297 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
n, k = map(int, input().split())
S, D, i = 0, 0, 0
ans = []
for val in map(int, input().split()):
f = (n - i + 1) * val * (i - D)
if S - f < k:
D += 1
ans.append(i + 1)
else: S += val * (i - D)
i += 1
print(' '.join(map(str, ans)))
```
No
| 85,298 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
During the last Sereja's Codesecrof round the server crashed many times, so the round was decided to be made unrated for some participants.
Let's assume that n people took part in the contest. Let's assume that the participant who got the first place has rating a1, the second place participant has rating a2, ..., the n-th place participant has rating an. Then changing the rating on the Codesecrof site is calculated by the formula <image>.
After the round was over, the Codesecrof management published the participants' results table. They decided that if for a participant di < k, then the round can be considered unrated for him. But imagine the management's surprise when they found out that the participants' rating table is dynamic. In other words, when some participant is removed from the rating, he is removed from the results' table and the rating is recalculated according to the new table. And of course, all applications for exclusion from the rating are considered in view of the current table.
We know that among all the applications for exclusion from the rating the first application to consider is from the participant with the best rank (the rank with the minimum number), for who di < k. We also know that the applications for exclusion from rating were submitted by all participants.
Now Sereja wonders, what is the number of participants to be excluded from the contest rating, and the numbers of the participants in the original table in the order of their exclusion from the rating. Pay attention to the analysis of the first test case for a better understanding of the statement.
Input
The first line contains two integers n, k (1 β€ n β€ 2Β·105, - 109 β€ k β€ 0). The second line contains n space-separated integers a1, a2, ..., an (1 β€ ai β€ 109) β ratings of the participants in the initial table.
Output
Print the numbers of participants in the order in which they were removed from the table. Print the initial numbers of the participants, that is, the numbers that the participants had in the initial table.
Examples
Input
5 0
5 3 4 1 2
Output
2
3
4
Input
10 -10
5 5 1 7 5 1 2 4 9 2
Output
2
4
5
7
8
9
Note
Consider the first test sample.
1. Initially the sequence of the contest participants' ratings equals [5, 3, 4, 1, 2]. You can use this sequence to calculate the sequence of rating changes: [0, -9, -13, 8, 14]. According to the problem statement, the application of the participant who won the second place will be considered first.
2. As soon as the second place winner is out from the ratings, the participants' rating sequence will equal [5, 4, 1, 2]. By this sequence you can count the new sequence of rating changes: [0, -8, 2, 6]. According to the problem statement, the application of the participant who won the second place will be considered. Initially this participant won third place.
3. The new rating sequence equals [5, 1, 2], the new sequence of rating changes equals [0, -1, 1]. The second place participant's application is taken into consideration, initially this participant won the fourth place.
4. The new rating sequence equals [5, 2], the new sequence of rating changes equals [0, 0]. No more applications will be considered.
Thus, you should print 2, 3, 4.
Submitted Solution:
```
f = lambda: map(int, input().split())
n, k = f()
s = j = 0
for i, q in enumerate(f(), 1):
if s - j * (n - i) * q < k: print(i)
else:
s += q * (i - 1)
j += 1
```
No
| 85,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.