message stringlengths 2 433k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 113 108k | cluster float64 12 12 | __index_level_0__ int64 226 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | instruction | 0 | 15,125 | 12 | 30,250 |
Tags: implementation
Correct Solution:
```
n = int(input())
m_list = list(map(int, input().split()))
m_min = min(m_list)
m_max = max(m_list)
m_list.remove(m_min)
m_list.remove(m_max)
if len(m_list) == 0:
print(0)
else:
new_min = min(m_list)
new_max = max(m_list)
print(min(m_max - new_min, new_max - m_min))
``` | output | 1 | 15,125 | 12 | 30,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | instruction | 0 | 15,126 | 12 | 30,252 |
Tags: implementation
Correct Solution:
```
n=int(input())
lis=list(map(int,input().split()))
lis.sort()
ans=min(lis[n-2]-lis[0],lis[n-1]-lis[1])
print(ans)
``` | output | 1 | 15,126 | 12 | 30,253 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | instruction | 0 | 15,127 | 12 | 30,254 |
Tags: implementation
Correct Solution:
```
def stabilizirovanie(lst):
if len(lst) == 2:
return 0
a = sorted(lst)
return min(a[len(lst) - 1] - a[1], a[len(lst) - 2] - a[0])
n = int(input())
b = [int(i) for i in input().split()]
print(stabilizirovanie(b))
``` | output | 1 | 15,127 | 12 | 30,255 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | instruction | 0 | 15,128 | 12 | 30,256 |
Tags: implementation
Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
b = a.copy()
c = a.copy()
b.remove(max(b))
c.remove(min(c))
print(min(max(b)-min(b),max(c)-min(c)))
``` | output | 1 | 15,128 | 12 | 30,257 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an array a consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly. | instruction | 0 | 15,129 | 12 | 30,258 |
Tags: implementation
Correct Solution:
```
from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
from __builtin__ import xrange as range
from future_builtins import ascii, filter, hex, map, oct, zip
def main():
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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
n=int(input())
arr=[int(x) for x in input().split()]
arr.sort()
print(min(arr[len(arr)-2]-arr[0],arr[len(arr)-1]-arr[1]))
``` | output | 1 | 15,129 | 12 | 30,259 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
a.sort()
b=[]
x=a[-2]-a[0]
b.append(x)
x=a[-1]-a[1]
b.append(x)
print(min(b))
``` | instruction | 0 | 15,130 | 12 | 30,260 |
Yes | output | 1 | 15,130 | 12 | 30,261 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
import sys
t = int(input())
tab = list(map(int, sys.stdin.readline().split()))
tab.sort(reverse=True)
print(min(tab[1]-tab[t-1], tab[0]-tab[t-2]))
``` | instruction | 0 | 15,131 | 12 | 30,262 |
Yes | output | 1 | 15,131 | 12 | 30,263 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n,a=int(input()),list(map(int,input().split()))
ma=max(a)
mi=min(a)
a.sort()
x=min((a[n-2]-mi),(ma-a[1]))
if x<0:
print(0)
else:
print(x)
``` | instruction | 0 | 15,132 | 12 | 30,264 |
Yes | output | 1 | 15,132 | 12 | 30,265 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
a.sort()
if (a[1]-a[0] < a[n-1]-a[n-2]): #remove last
ans = a[n-2]-a[0]
else: #remove first
ans = a[n-1]-a[1]
print(ans)
``` | instruction | 0 | 15,133 | 12 | 30,266 |
Yes | output | 1 | 15,133 | 12 | 30,267 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().split()))
sorted(l)
print(min(l[n-1] - l[1], l[n-2] - l[0]))
``` | instruction | 0 | 15,134 | 12 | 30,268 |
No | output | 1 | 15,134 | 12 | 30,269 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
#529_B
l = int(input())
ln = [int(i) for i in input().split(" ")]
mn = 10000000
mn2 = 10000000
omn = mn
mx = 0
mx2 = 0
omx = mx
for i in range(0, len(ln)):
if ln[i] < mn:
mn2 = mn
mn = ln[i]
elif ln[i] < mn2:
mn2 = ln[i]
if ln[i] > mx:
mx2 = mx
mx = ln[i]
elif ln[i] > mx2:
mx2 = ln[i]
print(mx, mx2, mn2, mn)
if len(ln) == 2:
print(0)
elif mx2 - mn < mx - mn2:
print(mx2 - mn)
else:
print(mx - mn2)
``` | instruction | 0 | 15,135 | 12 | 30,270 |
No | output | 1 | 15,135 | 12 | 30,271 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
l.sort()
del l[-1]
print(l[n-2]-l[0])
``` | instruction | 0 | 15,136 | 12 | 30,272 |
No | output | 1 | 15,136 | 12 | 30,273 |
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 consisting of n integer numbers.
Let instability of the array be the following value: max_{i = 1}^{n} a_i - min_{i = 1}^{n} a_i.
You have to remove exactly one element from this array to minimize instability of the resulting (n-1)-elements array. Your task is to calculate the minimum possible instability.
Input
The first line of the input contains one integer n (2 β€ n β€ 10^5) β the number of elements in the array a.
The second line of the input contains n integers a_1, a_2, ..., a_n (1 β€ a_i β€ 10^5) β elements of the array a.
Output
Print one integer β the minimum possible instability of the array if you have to remove exactly one element from the array a.
Examples
Input
4
1 3 3 7
Output
2
Input
2
1 100000
Output
0
Note
In the first example you can remove 7 then instability of the remaining array will be 3 - 1 = 2.
In the second example you can remove either 1 or 100000 then instability of the remaining array will be 100000 - 100000 = 0 and 1 - 1 = 0 correspondingly.
Submitted Solution:
```
n=int(input())
l=list(map(int,input().split()))
l.sort()
l=l[0:len(l)-1]
print(max(l)-min(l))
``` | instruction | 0 | 15,137 | 12 | 30,274 |
No | output | 1 | 15,137 | 12 | 30,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,214 | 12 | 30,428 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
import sys
input = sys.stdin.readline
print = sys.stdout.write
MAX = 2*(10**5) + 1
def divisors(a, ans):
div = []
t1 = int(a**.5)
for i in range(1, min(t1+1,ans)):
if a % i == 0:
div.append(i)
div.append(int(a/i))
div.sort()
return div
for ti in range(int(input())):
n = int(input())
p = [int(x)-1 for x in input().split()]
c = [int(x) for x in input().split()]
ans = float('inf')
visited = [0]*n
for i in range(n):
m = 0
cycle = []
cn = i
while(not visited[cn]):
visited[cn] = 1
cycle.append(c[cn])
cn = p[cn]
m += 1
for fi in divisors(m, ans):
for fj in range(fi):
valid = True
for ci in range(fj, m, fi):
valid &= (cycle[ci] == cycle[fj])
if(valid):
ans = min(ans, fi)
print(str(ans))
print('\n')
``` | output | 1 | 15,214 | 12 | 30,429 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,215 | 12 | 30,430 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
import sys
def bestval(pp, cc):
# print("BESTVAL:")
# print(pp)
# print(cc)
k = len(pp)
k_2 = k//2+1
for f in range(1, k_2):
if k % f == 0:
for offs in range(f):
good = True
num = cc[offs]
# print(f"{f}, {offs}, {num}: ")
upp = (k//f)//2+1
for j in range(1, upp):
v1 = f*j
v2 = k - v1 + offs
v1 += offs
# print(pp[v1], pp[v2])
if cc[v1] != num or cc[v2] != num:
good = False
break
if good:
return f
return k
for q in range(int(sys.stdin.readline())):
n = int(sys.stdin.readline())
p = [int(j)-1 for j in sys.stdin.readline().split()]
c = [int(j)-1 for j in sys.stdin.readline().split()]
fnd = [0]*n
ans = n+1
for i in range(n):
if not fnd[i]:
ppp = [i]
ccc = [c[i]]
fnd[i] = 1
j = p[i]
while j != i:
fnd[j] = 1
ppp.append(j)
ccc.append(c[j])
j = p[j]
# bb =
# print(bb)
ans = min(ans, bestval(ppp, ccc))
sys.stdout.write(str(ans) + '\n')
``` | output | 1 | 15,215 | 12 | 30,431 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,216 | 12 | 30,432 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
def uoc(x):
i=1
arr=[]
while i*i<=x:
if x%i==0:
arr.append(i)
if i*i!=x:
arr.append(x//i)
i+=1
return sorted(arr)
def is_ok(arr, n, u):
#assert u is divide by n
for i in range(u):
cur=i
flg=True
for j in range(n//u):
if arr[cur] != arr[(cur+u)%n]:
flg=False
break
cur+=u
if flg==True:
return True
return False
def min_period(arr):
n = len(arr)
u_arr = uoc(n)
for u in u_arr:
if is_ok(arr, n, u):
return u
for _ in range(int(input())):
n = int(input())
p = [-1] + list(map(int, input().split()))
c = [-1] + list(map(int, input().split()))
used=[0]*(n+1)
ans=float('inf')
for x in range(1, n+1):
if used[x]==0:
arr=[c[x]]
used[x]=1
while used[p[x]]==0:
x=p[x]
used[x]=1
arr.append(c[x])
ans=min(ans, min_period(arr))
print(ans)
``` | output | 1 | 15,216 | 12 | 30,433 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,217 | 12 | 30,434 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
from itertools import combinations
from collections import Counter
MOD = 998244353
def divs(cnt):
res = set()
firstdiv = -1
lastdiv = cnt
for i in range(2, int(cnt ** 0.5 + 1)):
if i > lastdiv:
break
if cnt % i == 0:
res.add(i)
res.add(cnt // i)
if firstdiv == -1:
firstdiv = i
lastdiv = cnt // i
return sorted(res)
def go():
n = int(input())
p = list(map(lambda x: int(x) - 1, input().split()))
c = list(map(int, input().split()))
done = [False] * n
perms = {}
colhist = {}
colmax={}
for i in range(n):
if not done[i]:
colhist_i = Counter()
done[i] = True
colhist_i[c[i]] += 1
j = p[i]
cnt = 1
while j != i:
done[j] = True
colhist_i[c[j]] += 1
j = p[j]
cnt += 1
colhist[i] = colhist_i
colmax[i]= max(colhist_i.values())
perms[i] = cnt
if len(colhist_i) == 1:
return 1
# print(perms)
# print(colhist)
revperms = {}
lim = n
for pp, cnt in perms.items():
revperms.setdefault(cnt, []).append(pp)
lim = min(lim, cnt)
for cnt in sorted(revperms.keys()):
divisors = divs(cnt)
for divisor in divisors:
if divisor>=lim:
break
for perm in revperms[cnt]:
if colmax[perm]<cnt//divisor:
continue
cols=[-1]*divisor
i=perm
for ind in range(divisor):
cols[ind]=c[i]
i=p[i]
for ind in range(divisor,cnt):
if c[i]!=cols[ind%divisor]:
cols[ind%divisor]=-1
i=p[i]
if any(col!=-1 for col in cols):
lim=divisor
break
return lim
t = int(input())
# t=1
# n,k=map(int,input().split())
ans = []
for _ in range(t):
ans.append(str(go()))
# go()
print('\n'.join(ans))
#
# print (divs(24))
# print (divs(2))
# print (divs(21))
``` | output | 1 | 15,217 | 12 | 30,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,218 | 12 | 30,436 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from math import sqrt
t=int(input())
for tests in range(t):
n=int(input())
P=list(map(int,input().split()))
C=list(map(int,input().split()))
for i in range(n):
P[i]-=1
USE=[0]*n
ANS=n
for i in range(n):
if USE[i]==1:
continue
cy=i
CYCLE=[]
while USE[cy]!=1:
USE[cy]=1
cy=P[cy]
CYCLE.append(cy)
#print(CYCLE)
LEN=len(CYCLE)
x=LEN
xr=int(sqrt(x))+1
LIST=[]
for k in range(1,xr+1):
if x%k==0:
LIST.append(k)
LIST.append(x//k)
for l in LIST:
if ANS<=LEN//l:
continue
COLORS=[-1]*(LEN//l)
ind=0
for k in range(LEN):
if COLORS[ind]==-1:
COLORS[ind]=C[cy]
elif COLORS[ind]==C[cy]:
True
else:
COLORS[ind]=0
cy=P[cy]
ind+=1
if ind==LEN//l:
ind=0
for c in COLORS:
if c!=0:
ANS=LEN//l
break
#print(CYCLE,l,COLORS)
print(ANS)
``` | output | 1 | 15,218 | 12 | 30,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,219 | 12 | 30,438 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
from sys import stdin
input = stdin.readline
q = int(input())
for rwerew in range(q):
n = int(input())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
for i in range(n):
p[i] -= 1
przyn = [0] * n
grupa = []
i = 0
while i < n:
if przyn[i] == 1:
i += 1
else:
nowa_grupa = [i]
j = p[i]
przyn[i] = 1
while j != i:
przyn[j] = 1
nowa_grupa.append(j)
j = p[j]
grupa.append(nowa_grupa)
grupacol = []
for i in grupa:
cyk = []
for j in i:
cyk.append(c[j])
grupacol.append(cyk)
#print(grupacol)
mini = 234283742834
for cykl in grupacol:
dziel = []
d = 1
while d**2 <= len(cykl):
if len(cykl)%d == 0:
dziel.append(d)
d += 1
dodat = []
for d in dziel:
dodat.append(len(cykl)/d)
dziel_ost = list(map(int,dziel + dodat))
#print(dziel_ost, len(cykl))
for dzielnik in dziel_ost:
for i in range(dzielnik):
indeks = i
secik = set()
chuj = True
while indeks < len(cykl):
secik.add(cykl[indeks])
indeks += dzielnik
if len(secik) > 1:
chuj = False
break
if chuj:
mini = min(mini, dzielnik)
print(mini)
``` | output | 1 | 15,219 | 12 | 30,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,220 | 12 | 30,440 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
import sys
readline = sys.stdin.readline
readlines = sys.stdin.readlines
int1 = lambda x: int(x) - 1
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int1, readline().split()))
prn = lambda x: print(*x, sep='\n')
def solve():
n = ni()
p = nl()
c = nl()
ans = n
use = [0]*n
for i in range(n):
if use[i]:
continue
v = i
cc = [c[v]]
use[v] = 1
while not use[p[v]]:
v = p[v]
cc.append(c[v])
use[v] = 1
m = len(cc)
ans = min(ans, m)
flag = 0
for j in range(1, min(m//2 + 1, ans)):
if m % j:
continue
ok = [True]*m
for k in range(j):
if len(set(cc[k::j])) == 1:
ans = min(ans, j)
flag = 1
break
if flag:
break
print(ans)
return
# solve()
T = ni()
for _ in range(T):
solve()
``` | output | 1 | 15,220 | 12 | 30,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4. | instruction | 0 | 15,221 | 12 | 30,442 |
Tags: brute force, dfs and similar, graphs, math, number theory
Correct Solution:
```
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
print = sys.stdout.write
def divisors(a, ans):
div = []
t1 = int(a**.5)
for i in range(1, min(t1+1,ans)):
if a % i == 0:
div.append(i)
div.append(int(a/i))
div.sort()
return div
for _ in range(int(input())):
n = int(input())
p = [int(i)-1 for i in input().split()]
c = list(map(int, input().split()))
alive = [True]*n
cycle = []
ans = n
for i in p:
if alive[i]:
cycle.append([])
while True:
if alive[i]:
alive[i] = False
cycle[-1].append(i)
i = p[i]
else:
break
for i in cycle:
t2 = len(i)
div = divisors(t2, ans)
for j in div:
if j >= ans:
break
for q in range(j):
t4 = c[i[q]]
for r in range(q+j,t2,j):
if t4 != c[i[r]]:
break
else:
ans = min(ans, j)
print(str(ans) + '\n')
``` | output | 1 | 15,221 | 12 | 30,443 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
import sys;input=sys.stdin.readline
def divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
divisors.sort()
return divisors
def check(p):
m = len(p)
for k in divisors(m):
for i in range(k):
ty = None
for j in range(m//k):
# print(j)
# print(j, p[i+j*k])
y = Y[p[i+j*k]-1]
if ty == None:
ty = y
elif y != ty:
break
else:
return k
t, = map(int, input().split())
for _ in range(t):
n = int(input())
X = list(map(int, input().split()))
Y = list(map(int, input().split()))
vs = set()
ps = []
for i in range(1, n+1):
if i in vs:
continue
vs.add(i)
stack = [i]
path = [i]
while stack:
v = stack.pop()
u = X[v-1]
if u in vs:
continue
path.append(u)
vs.add(u)
stack.append(u)
ps.append(path)
m = n
for p in ps:
m = min(m, check(p))
print(m)
``` | instruction | 0 | 15,222 | 12 | 30,444 |
Yes | output | 1 | 15,222 | 12 | 30,445 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
import sys
input = sys.stdin.readline
input_list = lambda: list(map(int, input().split()))
def factorize(n):
a = []
i = 1
while i*i<=n:
if n % i == 0:
a.append(i)
if i*i != n:
a.append(n//i)
i += 1
return a
def main():
t = int(input())
while t>0:
t -= 1
n = int(input())
p = input_list()
c = input_list()
ans = len(p)
used = [False]*(len(p) + 1)
length = len(p)
for i in range(length):
if used[i]:continue
used[i] = True
j = p[i] - 1
temp = [j]
while j!=i:
j = p[j] - 1
used[j] = True
temp.append(j)
t_len = len(temp)
factors = factorize(t_len)
ans = min(ans, t_len)
for k in factors:
for l in range(k):
index = (l + k)%t_len
while(index != l and c[temp[(index - k + t_len)%t_len]] == c[temp[index]]):
index = (index + k)%t_len
if (index == l):
ans = min(ans, k)
print(ans)
#stop = timeit.default_timer()
#print(stop - start)
def exp(a, n):
if n==0: return 1
result = a
residue = 1
while n>1:
if n%2==1: residue = residue * result % MOD
result = result * result % MOD
return result * residue % MOD
# call to the main function
main()
``` | instruction | 0 | 15,223 | 12 | 30,446 |
Yes | output | 1 | 15,223 | 12 | 30,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
t = int(input())
def find_loops():
seen = [0] * n
loops = []
for i in range(n):
if seen[i]:
continue
j = i
l = []
while 1:
if seen[j]:
break
l.append(j)
seen[j] = 1
j = p[j] - 1
loops.append(l)
return loops
def get_factors(number):
factors = []
i = 1
while i ** 2 <= number:
if number % i == 0:
factors.append(i)
if i ** 2 != number:
factors.append(int(number / i))
i = i + 1
return factors
def process_loop(loop):
length = len(loop)
# print("in process loop, loop is {}, length is {}, factors are {}".format(loop, length, get_factors(length)))
min_factor = length
for i in get_factors(length):
# print("checking factors, factor is: {}".format(i))
is_ok = [1] * i
for j in range(length):
# print("color of the {}th element of loop is {}".format(j, c[loop[j]]))
if c[loop[j]] != c[loop[j % i]]:
is_ok[j % i] = 0
for a in is_ok:
if a == 1:
min_factor = min(min_factor, i)
return min_factor
for x in range(t):
n = int(input())
p = list(map(int, input().strip().split()))
c = list(map(int, input().strip().split()))
loops = find_loops()
min_k = n
for loop in loops:
min_k = min(min_k, process_loop(loop))
if min_k == 1:
break
print(min_k)
``` | instruction | 0 | 15,224 | 12 | 30,448 |
Yes | output | 1 | 15,224 | 12 | 30,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI1(): return list(map(int1, sys.stdin.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def SI(): return sys.stdin.readline()[:-1]
def main():
def factor(a):
res=[]
for d in range(1,a+1):
if d**2>a:break
if a%d==0:
res.append(d)
if d**2!=a:res.append(a//d)
return res
def solve(ans):
for f in ff:
if f>=ans:return ans
for sj in range(f):
pc = colors[sj]
for j in range(sj + f, cn, f):
c = colors[j]
if c != pc: break
pc = c
else:return f
q=II()
for _ in range(q):
n=II()
pp=LI1()
cc=LI()
fin=[False]*n
ans=10**9
for i in range(n):
if fin[i]:continue
colors=[]
while not fin[i]:
fin[i]=True
colors.append(cc[i])
i=pp[i]
cn=len(colors)
ff=factor(cn)
ff.sort()
ans=solve(ans)
print(ans)
main()
``` | instruction | 0 | 15,225 | 12 | 30,450 |
Yes | output | 1 | 15,225 | 12 | 30,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
from sys import stdin
input = stdin.readline
q = int(input())
for rwerew in range(q):
n = int(input())
p = list(map(int,input().split()))
c = list(map(int,input().split()))
for i in range(n):
p[i] -= 1
przyn = [0] * n
grupa = []
i = 0
while i < n:
if przyn[i] == 1:
i += 1
else:
nowa_grupa = [i]
j = p[i]
przyn[i] = 1
while j != i:
przyn[j] = 1
nowa_grupa.append(j)
j = p[j]
grupa.append(nowa_grupa)
grupacol = []
for i in grupa:
cyk = []
for j in i:
cyk.append(c[j])
grupacol.append(cyk)
#print(grupacol)
mini = 234283742834
for cykl in grupacol:
dziel = []
d = 1
while d**2 <= len(cykl):
if len(cykl)%d == 0:
dziel.append(d)
d += 1
dodat = []
for d in dziel:
dodat.append(len(cykl)/d)
dziel_ost = list(map(int,dziel + dodat))
#print(dziel_ost, len(cykl))
for dzielnik in dziel_ost:
indeks = dzielnik - 1
secik = set()
chuj = True
while indeks < len(cykl):
secik.add(cykl[indeks])
indeks += dzielnik
if len(secik) > 1:
chuj = False
break
if chuj:
mini = min(mini, dzielnik)
print(mini)
``` | instruction | 0 | 15,226 | 12 | 30,452 |
No | output | 1 | 15,226 | 12 | 30,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
# n = int(input())
# a = list(map(int, input().split()))
# n, k = map(int, input().split())
MOD = 998244353
T = 1
T = int(input())
for t in range(1, T + 1):
# print('Case #' + str(t) + ': ', end = '')
n = int(input())
p = list(map(int, input().split()))
colour = list(map(int, input().split()))
child = {}
parent = {}
for i in p:
child[i] = p[i - 1]
parent[child[i]] = i
visited = set([])
min_dist = MOD
for i in p:
cycle = []
curr = i
while(curr not in visited):
visited.add(curr)
cycle.append(curr)
curr = child[curr]
cycle = 2 * cycle
prev = {}
for i in range(len(cycle)):
if colour[parent[cycle[i]] - 1] in prev:
min_dist = min(i - prev[colour[parent[cycle[i]] - 1]], min_dist)
prev[colour[parent[cycle[i]] - 1]] = i
print(min_dist)
``` | instruction | 0 | 15,227 | 12 | 30,454 |
No | output | 1 | 15,227 | 12 | 30,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
answers = []
for _ in range(int(input())):
n = int(input())
P = [0] + list(map(int, input().split()))
C = [0] + list(map(int, input().split()))
ccl = []
used = [0] * (n+1)
for v in range(1, n + 1):
if used[v] == 0:
used[v] = 1
x = P[v]
kk = [C[v]]
while used[x] == 0:
kk.append(C[x])
used[x] = 1
x = P[x]
ccl.append(kk)
ans = n
for i in range(1, n + 1):
if i == P[i]:
ans = 1
for p in ccl:
g = len(p)
for h in range(1, int(g**0.5)+1):
if g % h == 0:
hh = g // h
for Q in [h, hh]:
can = 0
for st in range(Q):
color = p[st]
cac = 1
for z in range(1, g // Q):
if p[st + h * z] != color:
cac = 0
if cac == 1:
can = 1
if can:
ans = min(ans, Q)
print(ans)
``` | instruction | 0 | 15,228 | 12 | 30,456 |
No | output | 1 | 15,228 | 12 | 30,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a colored permutation p_1, p_2, ..., p_n. The i-th element of the permutation has color c_i.
Let's define an infinite path as infinite sequence i, p[i], p[p[i]], p[p[p[i]]] ... where all elements have same color (c[i] = c[p[i]] = c[p[p[i]]] = ...).
We can also define a multiplication of permutations a and b as permutation c = a Γ b where c[i] = b[a[i]]. Moreover, we can define a power k of permutation p as p^k=\underbrace{p Γ p Γ ... Γ p}_{k times}.
Find the minimum k > 0 such that p^k has at least one infinite path (i.e. there is a position i in p^k such that the sequence starting from i is an infinite path).
It can be proved that the answer always exists.
Input
The first line contains single integer T (1 β€ T β€ 10^4) β the number of test cases.
Next 3T lines contain test cases β one per three lines. The first line contains single integer n (1 β€ n β€ 2 β
10^5) β the size of the permutation.
The second line contains n integers p_1, p_2, ..., p_n (1 β€ p_i β€ n, p_i β p_j for i β j) β the permutation p.
The third line contains n integers c_1, c_2, ..., c_n (1 β€ c_i β€ n) β the colors of elements of the permutation.
It is guaranteed that the total sum of n doesn't exceed 2 β
10^5.
Output
Print T integers β one per test case. For each test case print minimum k > 0 such that p^k has at least one infinite path.
Example
Input
3
4
1 3 4 2
1 2 2 3
5
2 3 4 5 1
1 2 3 4 5
8
7 4 5 6 1 8 3 2
5 3 6 4 7 5 8 4
Output
1
5
2
Note
In the first test case, p^1 = p = [1, 3, 4, 2] and the sequence starting from 1: 1, p[1] = 1, ... is an infinite path.
In the second test case, p^5 = [1, 2, 3, 4, 5] and it obviously contains several infinite paths.
In the third test case, p^2 = [3, 6, 1, 8, 7, 2, 5, 4] and the sequence starting from 4: 4, p^2[4]=8, p^2[8]=4, ... is an infinite path since c_4 = c_8 = 4.
Submitted Solution:
```
from sys import stdin
Pr = [1]
Cm = set()
for i in range(2, 450):
if i in Cm:
continue
Pr.append(i)
for j in range(i, 450, i):
Cm.add(j)
seen = [False for _ in range(200000)]
def check(S,f):
for seq in S:
ln = len(seq)
if ln%f:
continue
for s in range(f):
C = seq[s]
for i in range(s,ln,f):
if seq[i]!= C:
break
else:
return True
T = int(stdin.readline().strip())
ans = []
for _ in range(T):
n = int(stdin.readline().strip())
p = list(map(int, stdin.readline().split()))
c = list(map(int, stdin.readline().split()))
pd,m = 1,n
S = []
for i in range(n):
seen[i] = False
for i in range(n):
if seen[i]:
continue
u,seq = i,[]
while not seen[u]:
seen[u] = True
seq.append(c[u])
u = p[u]-1
S.append(seq)
pd,m = pd*len(seq),min(m,len(seq))
for pr in Pr:
if pr >= m:
ans.append(str(m))
break
if pd%pr==0 and check(S,pr):
ans.append(str(pr))
break
print('\n'.join(ans))
``` | instruction | 0 | 15,229 | 12 | 30,458 |
No | output | 1 | 15,229 | 12 | 30,459 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i β t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x β [l_i, r_i] and x β [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 β€ l_i β€ r_i β€ 10^9; t_i β \{1, 2\}) β description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5 | instruction | 0 | 15,246 | 12 | 30,492 |
Tags: data structures, dp, graph matchings, sortings
Correct Solution:
```
class LazySegmentTree():
def __init__(self,n,init,merge_func=max,ide_ele=-10**18):
self.n=(n-1).bit_length()
self.merge_func=merge_func
self.ide_ele=ide_ele
self.data=[0 for i in range(1<<(self.n+1))]
self.lazy=[0 for i in range(1<<(self.n+1))]
for i in range(n):
self.data[2**self.n+i]=init[i]
for i in range(2**self.n-1,0,-1):
self.data[i]=self.merge_func(self.data[2*i],self.data[2*i+1])
def propagate_above(self,i):
m=i.bit_length()-1
for bit in range(m,0,-1):
v=i>>bit
add=self.lazy[v]
self.lazy[v]=0
self.data[2*v]+=add
self.data[2*v+1]+=add
self.lazy[2*v]+=add
self.lazy[2*v+1]+=add
def remerge_above(self,i):
while i:
i>>=1
self.data[i]=self.merge_func(self.data[2*i],self.data[2*i+1])+self.lazy[i]
def update(self,l,r,x):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
while l<r:
self.data[l]+=x*(l&1)
self.lazy[l]+=x*(l&1)
l+=(l&1)
self.data[r-1]+=x*(r&1)
self.lazy[r-1]+=x*(r&1)
l>>=1
r>>=1
self.remerge_above(l0)
self.remerge_above(r0)
def query(self,l,r):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
self.propagate_above(l0)
self.propagate_above(r0)
res=self.ide_ele
while l<r:
if l&1:
res=self.merge_func(res,self.data[l])
l+=1
if r&1:
res=self.merge_func(res,self.data[r-1])
l>>=1
r>>=1
return res
import sys
input=sys.stdin.buffer.readline
n=int(input())
a=[]
b=[]
val=set()
for i in range(n):
l,r,t=map(int,input().split())
if t==1:
a.append((l,r))
else:
b.append((l,r))
val.add(l)
val.add(r)
val=sorted(list(val))
comp={i:e for e,i in enumerate(val)}
N=len(val)
querya=[[] for i in range(N)]
queryb=[[] for i in range(N)]
for i in range(len(a)):
l,r=a[i]
a[i]=(comp[l],comp[r])
querya[comp[r]].append(comp[l])
for i in range(len(b)):
l,r=b[i]
b[i]=(comp[l],comp[r])
queryb[comp[r]].append(comp[l])
init=[0]*N
LSTA=LazySegmentTree(N,init)
LSTB=LazySegmentTree(N,init)
dp=[0]*N
for i in range(N):
for l in querya[i]:
LSTA.update(0,l+1,1)
for l in queryb[i]:
LSTB.update(0,l+1,1)
temp1=LSTA.query(0,i+1)
temp2=LSTB.query(0,i+1)
dp[i]=max(temp1,temp2)
if i!=N-1:
LSTA.update(i+1,i+2,dp[i])
LSTB.update(i+1,i+2,dp[i])
print(dp[N-1])
``` | output | 1 | 15,246 | 12 | 30,493 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given n segments [l_1, r_1], [l_2, r_2], ..., [l_n, r_n]. Each segment has one of two colors: the i-th segment's color is t_i.
Let's call a pair of segments i and j bad if the following two conditions are met:
* t_i β t_j;
* the segments [l_i, r_i] and [l_j, r_j] intersect, embed or touch, i. e. there exists an integer x such that x β [l_i, r_i] and x β [l_j, r_j].
Calculate the maximum number of segments that can be selected from the given ones, so that there is no bad pair among the selected ones.
Input
The first line contains a single integer n (1 β€ n β€ 2 β
10^5) β number of segments.
The next n lines contains three integers l_i, r_i, t_i (1 β€ l_i β€ r_i β€ 10^9; t_i β \{1, 2\}) β description of the i-th segment.
Output
Print the maximum number of segments that can be selected, so that there is no bad pair among the selected segments.
Examples
Input
3
1 3 1
4 6 2
2 5 1
Output
2
Input
5
5 8 1
1 3 2
3 4 2
6 6 1
2 10 2
Output
4
Input
7
19 20 1
13 15 2
6 11 2
4 10 1
14 17 1
13 13 2
5 9 1
Output
5 | instruction | 0 | 15,247 | 12 | 30,494 |
Tags: data structures, dp, graph matchings, sortings
Correct Solution:
```
from operator import add
class LazySegmentTree():
def __init__(self,n,init,merge=max,merge_unit=-10**18,operate=add,operate_unit=0):
self.merge=merge
self.merge_unit=merge_unit
self.operate=operate
self.operate_unit=operate_unit
self.n=(n-1).bit_length()
self.data=[0 for i in range(1<<(self.n+1))]
self.lazy=[0 for i in range(1<<(self.n+1))]
for i in range(n):
self.data[2**self.n+i]=init[i]
for i in range(2**self.n-1,0,-1):
self.data[i]=self.merge(self.data[2*i],self.data[2*i+1])
def propagate_above(self,i):
m=i.bit_length()-1
for bit in range(m,0,-1):
v=i>>bit
add=self.lazy[v]
self.lazy[v]=0
self.data[2*v]=self.operate(self.data[2*v],add)
self.data[2*v+1]=self.operate(self.data[2*v+1],add)
self.lazy[2*v]=self.operate(self.lazy[2*v],add)
self.lazy[2*v+1]=self.operate(self.lazy[2*v+1],add)
def remerge_above(self,i):
while i:
i>>=1
self.data[i]=self.operate(self.merge(self.data[2*i],self.data[2*i+1]),self.lazy[i])
def update(self,l,r,x):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
while l<r:
if l&1:
self.data[l]=self.operate(self.data[l],x)
self.lazy[l]=self.operate(self.lazy[l],x)
l+=1
if r&1:
self.data[r-1]=self.operate(self.data[r-1],x)
self.lazy[r-1]=self.operate(self.lazy[r-1],x)
l>>=1
r>>=1
self.remerge_above(l0)
self.remerge_above(r0)
def query(self,l,r):
l+=1<<self.n
r+=1<<self.n
l0=l//(l&-l)
r0=r//(r&-r)-1
self.propagate_above(l0)
self.propagate_above(r0)
res=self.merge_unit
while l<r:
if l&1:
res=self.merge(res,self.data[l])
l+=1
if r&1:
res=self.merge(res,self.data[r-1])
l>>=1
r>>=1
return res
import sys
input=sys.stdin.buffer.readline
n=int(input())
a=[]
b=[]
val=set()
for i in range(n):
l,r,t=map(int,input().split())
if t==1:
a.append((l,r))
else:
b.append((l,r))
val.add(l)
val.add(r)
val=sorted(list(val))
comp={i:e for e,i in enumerate(val)}
N=len(val)
querya=[[] for i in range(N)]
queryb=[[] for i in range(N)]
for i in range(len(a)):
l,r=a[i]
a[i]=(comp[l],comp[r])
querya[comp[r]].append(comp[l])
for i in range(len(b)):
l,r=b[i]
b[i]=(comp[l],comp[r])
queryb[comp[r]].append(comp[l])
init=[0]*N
LSTA=LazySegmentTree(N,init)
LSTB=LazySegmentTree(N,init)
dp=[0]*N
for i in range(N):
for l in querya[i]:
LSTA.update(0,l+1,1)
for l in queryb[i]:
LSTB.update(0,l+1,1)
temp1=LSTA.query(0,i+1)
temp2=LSTB.query(0,i+1)
dp[i]=max(temp1,temp2)
if i!=N-1:
LSTA.update(i+1,i+2,dp[i])
LSTB.update(i+1,i+2,dp[i])
print(dp[N-1])
``` | output | 1 | 15,247 | 12 | 30,495 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,273 | 12 | 30,546 |
Tags: greedy, implementation
Correct Solution:
```
for _ in range(int(input())):
n = int(input())
a = [*map(int,input().split())]
d = dict()
if(len(set(a))==1):
print(0)
continue
elif(len(set(a))==n):
print(1)
continue
t = []
for i in range(n):
if(i==0):
t.append(a[i])
else:
if(t[-1]==a[i]):
continue
t.append(a[i])
d = dict()
for i in t:
try:
d[i]+=1
except KeyError:
d[i] = 1
vis =dict()
cnt = 0
mn = int(1e9)
for i in t:
try:
if(vis[i]):
continue
except KeyError:
ans = 0
vis[i] = 1
if(cnt==0):
if(t[-1]==i):
ans = max(0,d[i]-1)
else:
ans = d[i]
else:
if (t[-1] == i):
ans = max(0, d[i])
else:
ans = d[i]+1
cnt+=1
mn = min(mn,ans)
print(mn)
``` | output | 1 | 15,273 | 12 | 30,547 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,274 | 12 | 30,548 |
Tags: greedy, implementation
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
mp={}
if len(set(arr))==1:
print(0)
else:
for i in range(n):
if arr[i] in mp:
mp[arr[i]]=mp[arr[i]]+[i]
else:
mp[arr[i]]=[i]
ans = 10**9
for i in mp:
curr = 0
if mp[i][0]!=0:
curr+=1
if mp[i][-1]!=n-1:
curr+=1
for j in range(1,len(mp[i])):
if mp[i][j]!=mp[i][j-1]+1:
curr+=1
ans=min(ans,curr)
print (ans)
``` | output | 1 | 15,274 | 12 | 30,549 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,275 | 12 | 30,550 |
Tags: greedy, implementation
Correct Solution:
```
t = int(input())
def solve():
n = int(input())
arr = list(map(int, input().split()))
d = dict()
for i in range(n):
el = arr[i]
if not (el in d.keys()):
d[el] = []
d[el].append(i)
ans = 2 ** 31
for i in d.keys():
regions = 0
a = d[i]
for i in range(len(a)):
if(i == 0):
if(a[i] > 0):
regions += 1
if(i == len(a) - 1):
if(a[i] < n - 1):
regions += 1
if(i != len(a) - 1):
if(a[i + 1] - a[i] > 1):
regions += 1
ans = min(ans, regions)
print(ans)
for i in range(t):
solve()
``` | output | 1 | 15,275 | 12 | 30,551 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,276 | 12 | 30,552 |
Tags: greedy, implementation
Correct Solution:
```
T = int(input())
for t in range(T):
n = int(input())
l = list(map(int, input().split()))
new_l = [l[0]]
prev = l[0]
counts = {l[0]: 1}
for i in range(1, n):
cur = l[i]
if cur != prev:
new_l.append(cur)
r = counts.get(cur, 0)
counts[cur] = r + 1
prev = cur
# print(new_l)
# print("counts", counts)
counts[new_l[0]] = counts.get(new_l[0]) - 1
counts[new_l[-1]] = counts.get(new_l[-1]) - 1
# print("counts 2", counts)
print(min(counts.values()) + 1)
``` | output | 1 | 15,276 | 12 | 30,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,277 | 12 | 30,554 |
Tags: greedy, implementation
Correct Solution:
```
from collections import Counter
def unique(lis):
prev = -1
res = []
for i in lis:
if i != prev:
res.append(i)
prev = i
return res
for _ in range(int(input())):
n = int(input())
lis = list(map(int, input().split()))
lis = unique(lis)
dic = Counter(lis)
mi = float('inf')
for i in dic:
ans = dic[i] + 1
if lis[0] == i:
ans -= 1
if lis[-1] == i:
ans -= 1
mi = min(mi, ans)
print(mi)
``` | output | 1 | 15,277 | 12 | 30,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,278 | 12 | 30,556 |
Tags: greedy, implementation
Correct Solution:
```
import sys
import math
import collections
t=int(input())
for w in range(t):
n=int(input())
l=[int(i) for i in input().split()]
d={}
for i in range(n):
if(l[i] in d):
d[l[i]]+=[i]
else:
d[l[i]]=[-1,i]
for i in d:
d[i].append(n)
m=20000000
for i in d:
c=0
for j in range(1,len(d[i])):
if(d[i][j]-d[i][j-1]>1):
c+=1
m=min(m,c)
print(m)
``` | output | 1 | 15,278 | 12 | 30,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,279 | 12 | 30,558 |
Tags: greedy, implementation
Correct Solution:
```
#import sys, math
#input = sys.stdin.readline
import os
import sys
from io import BytesIO, IOBase
import heapq as h
import bisect
from types import GeneratorType
BUFSIZE = 8192
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index+1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
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")
import collections as col
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 = 10**9+7
mod=10**9+7
t=int(input())
#t=1
p=10**9+7
def ncr_util():
inv[0]=inv[1]=1
fact[0]=fact[1]=1
for i in range(2,300001):
inv[i]=(inv[i%p]*(p-p//i))%p
for i in range(1,300001):
inv[i]=(inv[i-1]*inv[i])%p
fact[i]=(fact[i-1]*i)%p
def z_array(s1):
n = len(s1)
z=[0]*(n)
l, r, k = 0, 0, 0
for i in range(1,n):
# if i>R nothing matches so we will calculate.
# Z[i] using naive way.
if i > r:
l, r = i, i
# R-L = 0 in starting, so it will start
# checking from 0'th index. For example,
# for "ababab" and i = 1, the value of R
# remains 0 and Z[i] becomes 0. For string
# "aaaaaa" and i = 1, Z[i] and R become 5
while r < n and s1[r - l] == s1[r]:
r += 1
z[i] = r - l
r -= 1
else:
# k = i-L so k corresponds to number which
# matches in [L,R] interval.
k = i - l
# if Z[k] is less than remaining interval
# then Z[i] will be equal to Z[k].
# For example, str = "ababab", i = 3, R = 5
# and L = 2
if z[k] < r - i + 1:
z[i] = z[k]
# For example str = "aaaaaa" and i = 2,
# R is 5, L is 0
else:
# else start from R and check manually
l = i
while r < n and s1[r - l] == s1[r]:
r += 1
z[i] = r - l
r -= 1
return z
'''
MAXN1=100001
spf=[0]*MAXN1
def sieve():
spf[1]=1
for i in range(2,MAXN1):
spf[i]=i
for i in range(4,MAXN1,2):
spf[i]=2
for i in range(3,math.ceil(math.sqrt(MAXN1))):
if spf[i]==i:
for j in range(i*i,MAXN1,i):
if spf[j]==j:
spf[j]=i
def factor(x):
d1={}
x1=x
while x!=1:
d1[spf[x]]=d1.get(spf[x],0)+1
x//=spf[x]
return d1
'''
def solve():
d={}
for i in l:
d[i]=[]
for i in range(n):
d[l[i]].append(i)
mini=n+1
for i in d:
cnt=0
if d[i][0]!=0:
cnt+=1
if d[i][-1]!=n-1:
cnt+=1
for j in range(len(d[i])-1):
if d[i][j+1]-d[i][j]>1:
cnt+=1
mini=min(mini,cnt)
return mini
for _ in range(t):
#x=int(input())
#d={}
#x,y=map(int,input().split())
n=int(input())
#s=input()
#s2=input()
l=list(map(int,input().split()))
#l.sort()
#l.sort(revrese=True)
#l2=list(map(int,input().split()))
#l=str(n)
#l.sort(reverse=True)
#l2.sort(reverse=True)
#l1.sort(reverse=True)
#(solve())
print(solve())
``` | output | 1 | 15,279 | 12 | 30,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3 | instruction | 0 | 15,280 | 12 | 30,560 |
Tags: greedy, implementation
Correct Solution:
```
from collections import Counter
def main(xs):
xs2 = [xs[0]]
# remove consequtive
for i in range(1, len(xs)):
if xs2[-1] != xs[i]:
xs2.append(xs[i])
counter = Counter(xs2)
for k, v in counter.items():
counter[k] += 1
counter[xs2[0]] -= 1
counter[xs2[-1]] -= 1
first = True
for k, v in counter.items():
if first:
m = v
first = False
else:
if v < m:
m = v
if m < 0:
return 0
else:
return m
if __name__ == "__main__":
t = int(input())
for _ in range(t):
input()
as_ = [int(x) for x in input().split()]
res = main(as_)
print(res)
def test1():
assert True == False
def test2():
assert True == False
def test_min():
assert True == False
def test_max():
assert True == False
``` | output | 1 | 15,280 | 12 | 30,561 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
t=int(input())
for i in range(t):
n=int(input())
dic={}
x = list(map(int,input().split()))
#x=(list(x[0])+x).append(x[-1])
for j in range(1,n+1):
dic.setdefault(x[j-1],[0,2,0])
dic[x[j-1]][0]+=1
dic[x[j - 1]][2] += 1
for j in range(1,n):
if(x[j]==x[j-1]):
dic[x[j]][2]-=1
#print(dic)
z=0
for key, val in dic.items():
dic[key][2] += 1
if(n==val[0]):
print(0)
z=1
break
if(x[0]==key and val[2]>1):
dic[key][2]-=1
if (x[-1] == key and val[2] > 1):
dic[key][2] -= 1
min=n
if(z==0):
for key, val in dic.items():
if(val[2]<min):
min=val[2]
#print(key,val)
print(min)
``` | instruction | 0 | 15,281 | 12 | 30,562 |
Yes | output | 1 | 15,281 | 12 | 30,563 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
# fuck les dict qui prennent plus de temps que des array wtf
import sys
input=sys.stdin.readline
def main():
n = int(input())
for _ in range(n):
size = int(input())
arr = [*map(int,input().split())]
counter = 9**9
optim = [[] for i in range(size)]
for i, val in enumerate(arr):
optim[val-1].append(i)
for val in optim:
if len(val)==0:
continue
count = 0
if val[0]!=0:count=1
for val1, val2 in zip(val[:-1],val[1:]):
if val2-val1>1:count+=1
if val[-1]!=size-1:count+=1
counter=min(counter,count)
print(counter)
'''
for val in set(arr):
#arr2 = []
count = 0
#dist = 0
b=0
for num in arr:
if num!=val and b == 0:count+=1;b = 1
elif num==val:
b = 0
#if dist>0:arr2 += [j]
#dist=-1
#dist += 1
counter = min(counter,count)
print(counter)
'''
main()
``` | instruction | 0 | 15,282 | 12 | 30,564 |
Yes | output | 1 | 15,282 | 12 | 30,565 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
"""
Author: Enivar
Date:
"""
from sys import exit, stderr
from collections import defaultdict
def debug(*args):
for i in args:
stderr.write(str(i)+' ')
stderr.write('\n')
for _ in range(int(input())):
n = int(input())
a = [int(x) for x in input().split()]
st = set(a)
if len(st)==1:
print(0)
continue
d = defaultdict(list)
narr = []
for i in range(n):
try:
prev = d[a[i]][-1]
#debug('prien i',i,prev)
if i-prev==1: d[a[i]][-1] = i
else: d[a[i]].append(i)
continue
except:
d[a[i]].append(i)
continue
mn = 10**18
fg = True
for ke in d:
ln = len(d[ke])
#debug(ke,d[ke])
if ln==1:
if d[ke][0]==0 or d[ke][0]==n-1 or a[0] == ke:
fg = False
print(1)
break
else: mn = min(mn, 2)
else:
if d[ke][-1]==n-1: ln-=1
if a[0]==ke: ln-=1
mn = min(mn,ln+1)
# debug(d[ke])
if fg: print(mn)
``` | instruction | 0 | 15,283 | 12 | 30,566 |
Yes | output | 1 | 15,283 | 12 | 30,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
"""
Author - Satwik Tiwari .
24th NOV , 2020 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def solve(case):
n = int(inp())
a = lis()
pos = {}
for i in range(n):
if(a[i] not in pos):
pos[a[i]] = [i]
else:
pos[a[i]].append(i)
# print(pos)
ans = inf
for i in pos:
temp = 0
# temp+=len(pos[i])-1
if(pos[i][0] !=0):
temp+=1
if(pos[i][len(pos[i])-1] != n-1):
temp+=1
for j in range(1,len(pos[i])):
if(pos[i][j] != pos[i][j-1] + 1):
temp+=1
ans = min(ans,temp)
print(ans)
# testcase(1)
testcase(int(inp()))
``` | instruction | 0 | 15,284 | 12 | 30,568 |
Yes | output | 1 | 15,284 | 12 | 30,569 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
t = int(input())
for i in range(t):
n = int(input())
seq = list(map(int, input().split()))
str_seq = ",".join(list(map(str, seq)))
if i == 679:
print(seq[5])
x = set(seq)
mn = float("inf")
if len(x) == 1:
print(0)
else:
for num in x:
y = [j for j in str_seq.split(str(num)) if j != "" and j != ","]
mn = min(mn, len(y))
print(mn)
``` | instruction | 0 | 15,285 | 12 | 30,570 |
No | output | 1 | 15,285 | 12 | 30,571 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
for _ in range(int(input())):
n=int(input())
arr=list(map(int,input().split()))
d={}
k={}
for i in range(n):
if arr[i] in d:
if arr[i-1]!=arr[i]:
d[arr[i]].append(i)
k[arr[i]].append(i)
else:
d[arr[i]]=[i]
k[arr[i]]=[i]
m=n
for j in d:
out=len(d[j])+1
for i in k[j]:
if i==0:
out-=1
elif i==n-1:
out-=1
m=min(out,m)
print(m)
``` | instruction | 0 | 15,286 | 12 | 30,572 |
No | output | 1 | 15,286 | 12 | 30,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
def counts(arr):
stat = []
n = len(arr)
for i in arr:
if i not in stat:
stat.append(i)
minislands = n
if len(stat) == 1:
return 0
elif len(stat) == n:
return 1
for x in stat:
islands = 0
changed = False
for i in range(n):
if arr[i] == x:
if changed:
changed = False
elif not changed:
islands += 1
changed = True
minislands = min(minislands, islands)
if not minislands or minislands == 2:
return minislands
return minislands
def main():
t = int(input())
for _ in range(t):
n = int(input())
arr = list(map(int, input().strip().split()))
ind = counts(arr)
print(ind)
if __name__ == "__main__":
main()
``` | instruction | 0 | 15,287 | 12 | 30,574 |
No | output | 1 | 15,287 | 12 | 30,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a sequence a, initially consisting of n integers.
You want to transform this sequence so that all elements in it are equal (i. e. it contains several occurrences of the same element).
To achieve this, you choose some integer x that occurs at least once in a, and then perform the following operation any number of times (possibly zero): choose some segment [l, r] of the sequence and remove it. But there is one exception: you are not allowed to choose a segment that contains x. More formally, you choose some contiguous subsequence [a_l, a_{l + 1}, ..., a_r] such that a_i β x if l β€ i β€ r, and remove it. After removal, the numbering of elements to the right of the removed segment changes: the element that was the (r+1)-th is now l-th, the element that was (r+2)-th is now (l+1)-th, and so on (i. e. the remaining sequence just collapses).
Note that you can not change x after you chose it.
For example, suppose n = 6, a = [1, 3, 2, 4, 1, 2]. Then one of the ways to transform it in two operations is to choose x = 1, then:
1. choose l = 2, r = 4, so the resulting sequence is a = [1, 1, 2];
2. choose l = 3, r = 3, so the resulting sequence is a = [1, 1].
Note that choosing x is not an operation. Also, note that you can not remove any occurrence of x.
Your task is to find the minimum number of operations required to transform the sequence in a way described above.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 β€ t β€ 2 β
10^4) β the number of test cases. Then t test cases follow.
The first line of the test case contains one integer n (1 β€ n β€ 2 β
10^5) β the number of elements in a. The second line of the test case contains n integers a_1, a_2, β¦, a_n (1 β€ a_i β€ n), where a_i is the i-th element of a.
It is guaranteed that the sum of n does not exceed 2 β
10^5 (β n β€ 2 β
10^5).
Output
For each test case, print the answer β the minimum number of operations required to transform the given sequence in a way described in the problem statement. It can be proven that it is always possible to perform a finite sequence of operations so the sequence is transformed in the required way.
Example
Input
5
3
1 1 1
5
1 2 3 4 5
5
1 2 3 2 1
7
1 2 3 1 2 3 1
11
2 2 1 2 3 2 1 2 3 1 2
Output
0
1
1
2
3
Submitted Solution:
```
from sys import stdin, stdout, stderr, maxsize
# mod = int(1e9 + 7)
# import re # can use multiple splits
tup = lambda: map(int, stdin.buffer.readline().split())
I = lambda: int(stdin.buffer.readline())
lint = lambda: [int(x) for x in stdin.buffer.readline().split()]
S = lambda: stdin.readline().replace('\n', '').strip()
# def grid(r, c): return [lint() for i in range(r)]
# def debug(*args, c=6): print('\033[3{}m'.format(c), *args, '\033[0m', file=stderr)
stpr = lambda x: stdout.write(f'{x}' + '\n')
star = lambda x: print(' '.join(map(str, x)))
# from math import ceil, floor
from collections import defaultdict
# from bisect import bisect_left, bisect_right
#popping from the end is less taxing,since you don't have to shift any elements
#from collections import Counter
for _ in range(I()):
n = I()
ls = lint()
if _ == 679:
print(*ls )
t = set(ls)
m = maxsize
x = ''.join(map(str , ls))
for i in t:
a = x.split(str(i))
s = sum(map(lambda x : 1 if len(x) > 0 else 0, a))
#print(s,a)
m = min(m , s)
print(m)
``` | instruction | 0 | 15,288 | 12 | 30,576 |
No | output | 1 | 15,288 | 12 | 30,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.
Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
Input
The first line of the input contains one integer n (2 β€ n β€ 150 000) β the length of the sequence.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 150 000) β the initial sequence. It's guaranteed that the given sequence is not nice.
Output
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
Examples
Input
5
2 8 4 7 7
Output
2
Input
4
200 150 100 50
Output
1
Input
10
3 2 1 4 1 4 1 4 1 4
Output
8
Input
9
1 2 3 4 5 6 7 8 9
Output
0
Note
In the first sample, there are two ways to get a nice sequence with one swap:
1. Swap t2 = 8 with t4 = 7.
2. Swap t1 = 2 with t5 = 7.
In the second sample, there is only one way β Limak should swap t1 = 200 with t4 = 50. | instruction | 0 | 15,509 | 12 | 31,018 |
Tags: brute force, implementation
Correct Solution:
```
#!/usr/bin/python3
def needs_rep(t, i):
if i % 2 == 0:
return t[i] >= t[i+1]
else:
return t[i] <= t[i+1]
def would_need_rep(t, i, j1, j2):
n = len(t)
if i < 0:
return False
if i >= n-1:
return False
tj1 = t[j2]
tj2 = t[j1]
ti = t[i]
if i == j1:
ti = tj1
if i == j2:
ti = tj2
ti1 = t[i+1]
if i+1 == j1:
ti1 = tj1
if i+1 == j2:
ti1 = tj2
if i % 2 == 0:
return ti >= ti1
else:
return ti <= ti1
def main():
n = int(input())
t = [int(i) for i in input().split()]
# rep = [False]*(n-1)
rep = []
for i in range(n-1):
if needs_rep(t, i):
rep.append(i)
if(len(rep) > 4):
print(0)
return
# print(rep)
# to_try = [rep[0]]
# if rep[0] < n-1:
# to_try.append(rep[0] + 1)
to_try = [rep[0], rep[0] + 1]
s = set()
for i in to_try:
for j in range(n):
if i == j: continue
if would_need_rep(t, i, i, j):
continue
if would_need_rep(t, i-1, i, j):
continue
if would_need_rep(t, j, i, j):
continue
if would_need_rep(t, j-1, i, j):
continue
bad = False
for r in rep:
if would_need_rep(t, r, i, j):
bad = True
if bad: continue
# print(i, j)
# print(would_need_rep(t, 2, i, j))
if (i, j) not in s and (j, i) not in s:
# print('Adding {}'.format((i, j)))
s.add((i, j))
print(len(s))
if __name__ == '__main__':
main()
``` | output | 1 | 15,509 | 12 | 31,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.
Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
Input
The first line of the input contains one integer n (2 β€ n β€ 150 000) β the length of the sequence.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 150 000) β the initial sequence. It's guaranteed that the given sequence is not nice.
Output
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
Examples
Input
5
2 8 4 7 7
Output
2
Input
4
200 150 100 50
Output
1
Input
10
3 2 1 4 1 4 1 4 1 4
Output
8
Input
9
1 2 3 4 5 6 7 8 9
Output
0
Note
In the first sample, there are two ways to get a nice sequence with one swap:
1. Swap t2 = 8 with t4 = 7.
2. Swap t1 = 2 with t5 = 7.
In the second sample, there is only one way β Limak should swap t1 = 200 with t4 = 50. | instruction | 0 | 15,510 | 12 | 31,020 |
Tags: brute force, implementation
Correct Solution:
```
n = int(input())
t = list(map(int, input().split()))
t = [-1] + t
badIdx = []
nice = []
def getBadIdx():
for i in range(1,n):
if ((i%2 == 0) and (t[i] <= t[i+1])) or ((i%2 == 1) and (t[i] >= t[i+1])):
badIdx.append((i,i+1))
def checkBad(k):
if ((k <= (n-1)) and (((k%2 == 0) and (t[k] <= t[k+1])) or ((k%2 == 1) and (t[k] >= t[k+1])))) \
or ((k-1) >= 1 and (((k-1)%2 == 0) and (t[k-1] <= t[k]) or ((k-1)%2 == 1) and (t[k-1] >= t[k]))):
return True
for (i,j) in badIdx:
if ((i%2 == 0) and (t[i] <= t[j])) or ((i%2 == 1) and (t[i] >= t[j])):
return True
return False
def swap(i,j):
ith = t[i]
t[i] = t[j]
t[j] = ith
getBadIdx()
if len(badIdx) > 4:
print(0)
else:
(i,j) = badIdx[0]
#for (i,j) in badIdx:
for k in range(1,n+1):
if i != k and t[i] != t[k]:
swap(i,k)
if not(checkBad(k)):
nice.append((i,k))
swap(i,k)
else:
swap(i,k)
if j != k and t[j] != t[k]:
swap(j,k)
if not(checkBad(k)):
nice.append((j,k))
swap(j,k)
else:
swap(j,k)
print(len(set([tuple(sorted(t)) for t in nice])))
``` | output | 1 | 15,510 | 12 | 31,021 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The life goes up and down, just like nice sequences. Sequence t1, t2, ..., tn is called nice if the following two conditions are satisfied:
* ti < ti + 1 for each odd i < n;
* ti > ti + 1 for each even i < n.
For example, sequences (2, 8), (1, 5, 1) and (2, 5, 1, 100, 99, 120) are nice, while (1, 1), (1, 2, 3) and (2, 5, 3, 2) are not.
Bear Limak has a sequence of positive integers t1, t2, ..., tn. This sequence is not nice now and Limak wants to fix it by a single swap. He is going to choose two indices i < j and swap elements ti and tj in order to get a nice sequence. Count the number of ways to do so. Two ways are considered different if indices of elements chosen for a swap are different.
Input
The first line of the input contains one integer n (2 β€ n β€ 150 000) β the length of the sequence.
The second line contains n integers t1, t2, ..., tn (1 β€ ti β€ 150 000) β the initial sequence. It's guaranteed that the given sequence is not nice.
Output
Print the number of ways to swap two elements exactly once in order to get a nice sequence.
Examples
Input
5
2 8 4 7 7
Output
2
Input
4
200 150 100 50
Output
1
Input
10
3 2 1 4 1 4 1 4 1 4
Output
8
Input
9
1 2 3 4 5 6 7 8 9
Output
0
Note
In the first sample, there are two ways to get a nice sequence with one swap:
1. Swap t2 = 8 with t4 = 7.
2. Swap t1 = 2 with t5 = 7.
In the second sample, there is only one way β Limak should swap t1 = 200 with t4 = 50. | instruction | 0 | 15,511 | 12 | 31,022 |
Tags: brute force, implementation
Correct Solution:
```
def main():
n, l = int(input()), list(map(int, input().split()))
if not (n & 1):
l.append(0)
l.append(150001)
a, i, j, fails = l[0], 0, 1, set()
try:
while True:
b = l[j]
if a >= b:
fails.add(i)
fails.add(j)
if len(fails) > 6:
break
i += 2
a = l[i]
if a >= b:
fails.add(i)
fails.add(j)
if len(fails) > 6:
break
j += 2
print(0)
return
except IndexError:
tmp, res = [], 0
for b in sorted(fails):
tmp.append("><"[b & 1] if b - a == 1 else "and ")
tmp.append("l[{:n}]".format(b))
a = b
check = compile("".join(tmp[1:]), "<string>", "eval")
for i in fails:
a = l[i]
for j in fails:
l[i], l[j] = l[j], a
if eval(check):
res -= 1
l[j] = l[i]
for j in range(0, n, 2):
l[i], l[j] = l[j], a
if l[j - 1] > a < l[j + 1] and eval(check):
res += 2
l[j] = l[i]
for j in range(1, n, 2):
l[i], l[j] = l[j], a
if l[j - 1] < a > l[j + 1] and eval(check):
res += 2
l[j] = l[i]
l[i] = a
print(res // 2)
if __name__ == '__main__':
main()
``` | output | 1 | 15,511 | 12 | 31,023 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.