message stringlengths 2 65.1k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 0 108k | cluster float64 14 14 | __index_level_0__ int64 0 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,534 | 14 | 41,068 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
for _ in range(int(input())):
n=int(input())
if(n%2==0):
for i in range(1,n+1):
if(i%2==0):
print(i-1,end=" ")
else:
print(i+1,end=" ")
print()
else:
print("3 1 2",end=" ")
for i in range(4,n+1):
if(i%2==0):
print(i+1,end=" ")
else:
print(i-1,end=" ")
print()
``` | output | 1 | 20,534 | 14 | 41,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,535 | 14 | 41,070 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
T = int(input())
for _ in range(T):
n = int(input())
A = []
if n % 2 == 0:
for i in range(n//2):
A.append(1 + 2*i + 1)
A.append(1 + 2*i)
else:
A = [3, 1, 2]
for i in range(1, n//2):
A.append(1 + 2*i + 2)
A.append(1 + 2*i + 1)
print(" ".join(str(a) for a in A))
``` | output | 1 | 20,535 | 14 | 41,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,536 | 14 | 41,072 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
for s in[*open(0)][1:]:
n=int(s)
for i in range(0,n-n%2*3,2):print(i+2,i+1)
if n%2:print(n,n-2,n-1)
``` | output | 1 | 20,536 | 14 | 41,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,537 | 14 | 41,074 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
import sys
#from fractions import Fraction
#import re
#sys.stdin=open('.in','r')
#sys.stdout=open('.out','w')
#import math
#import random
#import time
#sys.setrecursionlimit(int(1e6))
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inara():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t=inp()
for i in range(t):
n=inp()
a=[i for i in range(1,n+1)]
for i in range(1,n,2):
a[i],a[i-1]=a[i-1],a[i]
if n%2:
a[n-3]=n
a[n-2]=n-2
a[n-1]=n-1
print(*a)
``` | output | 1 | 20,537 | 14 | 41,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,538 | 14 | 41,076 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
from functools import reduce
import os
import sys
from collections import *
from decimal import *
from math import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value(): return tuple(map(int, input().split())) # multiple values
def arr(): return [int(i) for i in input().split()] # aay input
def sarr(): return [int(i) for i in input()] #aay from string
def starr(): return [str(x) for x in input().split()] #string aay
def inn(): return int(input()) # integer input
def svalue(): return tuple(map(str, input().split())) #multiple string values
def parr(): return [(value()) for i in range(n)] # aay of pairs
def Ceil(a,b): return a//b+int(a%b>0)
albhabet="abcdefghijklmnopqrstuvwxyz"
mo = 1000000007
inf=1e18
div=998244353
#print("Case #{}:".format(_+1),end=" ")
#print("Case #",z+1,":",sep="",end=" ")
# ----------------------------CODE------------------------------#
for _ in range(inn()):
n=inn()
a=[i for i in range(1,n+1)]
if(n%2==0):
for i in range(0,n,2):
a[i],a[i+1]=a[i+1],a[i]
print(*a)
else:
for i in range(0,n-3,2):
a[i], a[i + 1] = a[i + 1], a[i]
a[n-3],a[n-2],a[n-1]=a[n-2],a[n-1],a[n-3]
print(*a)
``` | output | 1 | 20,538 | 14 | 41,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1]. | instruction | 0 | 20,539 | 14 | 41,078 |
Tags: constructive algorithms, greedy, implementation
Correct Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import random
import heapq,bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10**8)
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=2**51, func=lambda a, b: a & b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: max(a , b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
class TrieNode:
def __init__(self):
self.children = [None] * 26
self.isEndOfWord = False
class Trie:
def __init__(self):
self.root = self.getNode()
def getNode(self):
return TrieNode()
def _charToIndex(self, ch):
return ord(ch) - ord('a')
def insert(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
pCrawl.children[index] = self.getNode()
pCrawl = pCrawl.children[index]
pCrawl.isEndOfWord = True
def search(self, key):
pCrawl = self.root
length = len(key)
for level in range(length):
index = self._charToIndex(key[level])
if not pCrawl.children[index]:
return False
pCrawl = pCrawl.children[index]
return pCrawl != None and pCrawl.isEndOfWord
#-----------------------------------------trie---------------------------------
class Node:
def __init__(self, data):
self.data = data
self.count=0
self.left = None # left node for 0
self.right = None # right node for 1
class BinaryTrie:
def __init__(self):
self.root = Node(0)
def insert(self, pre_xor):
self.temp = self.root
for i in range(31, -1, -1):
val = pre_xor & (1 << i)
if val:
if not self.temp.right:
self.temp.right = Node(0)
self.temp = self.temp.right
self.temp.count+=1
if not val:
if not self.temp.left:
self.temp.left = Node(0)
self.temp = self.temp.left
self.temp.count += 1
self.temp.data = pre_xor
def query(self, xor):
self.temp = self.root
for i in range(31, -1, -1):
val = xor & (1 << i)
if not val:
if self.temp.left and self.temp.left.count>0:
self.temp = self.temp.left
elif self.temp.right:
self.temp = self.temp.right
else:
if self.temp.right and self.temp.right.count>0:
self.temp = self.temp.right
elif self.temp.left:
self.temp = self.temp.left
self.temp.count-=1
return xor ^ self.temp.data
# --------------------------------------------------binary-----------------------------------
for ik in range(int(input())):
n=int(input())
ans=[i for i in range(1,n+1)]
for i in range(1,n,2):
ans[i],ans[i-1]=ans[i-1],ans[i]
if n%2==1:
ans[-1],ans[-2]=ans[-2],ans[-1]
print(*ans)
``` | output | 1 | 20,539 | 14 | 41,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
#!/usr/bin/env pypy3
from sys import stdin, stdout
def input(): return stdin.readline().strip()
def read_int_list(): return list(map(int, input().split()))
def read_int_tuple(): return tuple(map(int, input().split()))
def read_int(): return int(input())
### CODE HERE
def ans(x):
ret = list(range(1, x+1))
if len(ret) % 2 == 0:
for i in range(len(ret)):
if i % 2 == 0:
ret[i], ret[i+1] = ret[i+1], ret[i]
else:
for i in range(3, len(ret)):
if i % 2 == 1:
ret[i], ret[i+1] = ret[i+1], ret[i]
ret[0] = 3
ret[1] = 1
ret[2] = 2
return " ".join(map(str, ret))
for _ in range(read_int()):
print(ans(read_int()))
``` | instruction | 0 | 20,540 | 14 | 41,080 |
Yes | output | 1 | 20,540 | 14 | 41,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
arr=[]
if n%2==0:
i=1
while i<n:
arr.append(i+1)
arr.append(i)
i+=2
else:
i=4
arr=[2,3,1]
while i<n:
arr.append(i+1)
arr.append(i)
i+=2
print(*arr)
``` | instruction | 0 | 20,541 | 14 | 41,082 |
Yes | output | 1 | 20,541 | 14 | 41,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
n = int(input())
for i in range(n):
number = int(input())
cats = list(range(1, number + 1))
if number % 2 == 0:
for cat in cats:
if cat % 2 != 0:
cats[cat - 1] += 1
else:
cats[cat - 1] -= 1
else:
for cat1 in cats[:-3]:
if cat1 % 2 != 0:
cats[cat1 - 1] += 1
else:
cats[cat1 - 1] -= 1
cats[-3] += 2
cats[-2] -= 1
cats[-1] -= 1
print(*cats)
``` | instruction | 0 | 20,542 | 14 | 41,084 |
Yes | output | 1 | 20,542 | 14 | 41,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
t=int(input())
for _ in range(t):
n=int(input())
a=list(i for i in range(1,n+1))
if n%2==0:
for i in range(0,n-1,2):
a[i],a[i+1]=a[i+1],a[i]
else:
for i in range(1,n-1,2):
a[i],a[i+1]=a[i+1],a[i]
a[0],a[1]=a[1],a[0]
print(*a)
``` | instruction | 0 | 20,543 | 14 | 41,086 |
Yes | output | 1 | 20,543 | 14 | 41,087 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
from itertools import permutations
t=int(input())
for i in range(t):
n=int(input())
a=[]
for i in range(1,n+1):
a.append(i)
c=n//2
if n%2!=0 or n==2:
ans=([a[-1]]+a[0:-1])
else:
l=a[0:c]
r=a[c:]
ans=l[::-1]+r[::-1]
print(*ans)
``` | instruction | 0 | 20,544 | 14 | 41,088 |
No | output | 1 | 20,544 | 14 | 41,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
def solve(n):
ans = []
for i in range(1, n + 1):
ans.append(i)
if n % 2 == 0:
for i in range(0, n, 2):
ans[i], ans[i + 1] = ans[i + 1], ans[i]
return ans
else:
return [ans[-1]] + ans[:-1]
for t in range(int(input())):
n = int(input())
print(*solve(n))
``` | instruction | 0 | 20,545 | 14 | 41,090 |
No | output | 1 | 20,545 | 14 | 41,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
t = input()
t =int(t)
for i in range(0,t):
n = input()
n = int(n)
lst = []
for i in range(0,n-1,2):
lst.append(i+2)
lst.append(i+1)
if n%2==1:
ele = lst[-1]
lst.pop()
lst.append(n)
lst.append(ele)
print(lst)
``` | instruction | 0 | 20,546 | 14 | 41,092 |
No | output | 1 | 20,546 | 14 | 41,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are n cats in a line, labeled from 1 to n, with the i-th cat at position i. They are bored of gyrating in the same spot all day, so they want to reorder themselves such that no cat is in the same place as before. They are also lazy, so they want to minimize the total distance they move. Help them decide what cat should be at each location after the reordering.
For example, if there are 3 cats, this is a valid reordering: [3, 1, 2]. No cat is in its original position. The total distance the cats move is 1 + 1 + 2 = 4 as cat 1 moves one place to the right, cat 2 moves one place to the right, and cat 3 moves two places to the left.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of test cases. Then t test cases follow.
The first and only line of each test case contains one integer n (2 ≤ n ≤ 100) — the number of cats.
It can be proven that under the constraints of the problem, an answer always exist.
Output
Output t answers, one for each test case. Each answer consists of n integers — a permutation with the minimum total distance. If there are multiple answers, print any.
Example
Input
2
2
3
Output
2 1
3 1 2
Note
For the first test case, there is only one possible permutation that satisfies the conditions: [2, 1].
The second test case was described in the statement. Another possible answer is [2, 3, 1].
Submitted Solution:
```
t=int(input())
while(t>0):
t=t-1
n=int(input())
l1=[]
l2=[]
for i in range(1,n+1):
if(i%2==0):
l1.append(i)
else:
l2.append(i)
l2.reverse()
l1.reverse()
l=l1+l2
print(*l,sep=" ")
``` | instruction | 0 | 20,547 | 14 | 41,094 |
No | output | 1 | 20,547 | 14 | 41,095 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,657 | 14 | 41,314 |
Tags: implementation, sortings
Correct Solution:
```
from itertools import permutations
n=int(input())
l=list(map(int,input().split()))
d={}
d2={}
res=[]
c=0
def bf(x,indeks=0):
global c
if c < 3:
if indeks == le:
for i in res:
print(*i,end=" ")
print()
c+=1
else:
for i in permutations(x[indeks],len(x[indeks])):
res.append(i)
bf(x,indeks+1)
res.pop()
if c >= 3:
break
for i in range(len(l)):
try:
d[l[i]].append(i+1)
d2[l[i]]+=1
except:
d[l[i]]=[i+1]
d2[l[i]]=1
r=1
for i in d2.values():
r*=i
if r < 3:
print("NO")
else:
print("YES")
p=dict(sorted(d.items(), key=lambda item: item[0]))
k=list(p.values())
le=len(k)
bf(k)
``` | output | 1 | 20,657 | 14 | 41,315 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,658 | 14 | 41,316 |
Tags: implementation, sortings
Correct Solution:
```
# coding: utf-8
n = int(input())
tmp = [int(i) for i in input().split()]
li = []
for i in range(1,n+1):
li.append([tmp[i-1],i])
li.sort()
seq = [str(i[1]) for i in li]
two = []
three = []
for i in set(tmp):
cnt = tmp.count(i)
if cnt == 2:
two.append(i)
elif cnt >= 3:
three.append(i)
if three:
pos = seq.index(str(tmp.index(three[0])+1))
print('YES')
print(' '.join(seq))
seq[pos], seq[pos+1] = seq[pos+1], seq[pos]
print(' '.join(seq))
seq[pos+1], seq[pos+2] = seq[pos+2], seq[pos+1]
print(' '.join(seq))
elif len(two) >= 2:
pos1 = seq.index(str(tmp.index(two[0])+1))
pos2 = seq.index(str(tmp.index(two[1])+1))
print('YES')
print(' '.join(seq))
seq[pos1], seq[pos1+1] = seq[pos1+1], seq[pos1]
print(' '.join(seq))
seq[pos2], seq[pos2+1] = seq[pos2+1], seq[pos2]
print(' '.join(seq))
else:
print('NO')
``` | output | 1 | 20,658 | 14 | 41,317 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,659 | 14 | 41,318 |
Tags: implementation, sortings
Correct Solution:
```
from random import shuffle
def main():
n = int(input())
a = sorted([(x, i + 1) for i, x in enumerate(map(int, input().split()))])
ways = 1
i = 0
parts = []
while i < n:
j = i
while j < n and a[j][0] == a[i][0]:
j += 1
parts.append(a[i : j])
ways = min(ways * (j - i), 3)
i = j
if ways < 3:
print('NO')
return
print('YES')
outp = set()
for _ in range(3):
while True:
cur = []
for x in parts:
shuffle(x)
cur.extend([t[1] for t in x])
#print(tuple(cur))
if tuple(cur) not in outp:
print(' '.join(map(str, cur)))
outp.add(tuple(cur))
break
main()
``` | output | 1 | 20,659 | 14 | 41,319 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,660 | 14 | 41,320 |
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
h=[[0, i+1] for i in range(n)]
a=list(map(int, input().split()))
for i in range(n):
h[i][0] = a[i]
h.sort(key = lambda x : x[0])
cnt = 0
for i in range(n-1):
if h[i][0]==h[i+1][0]:
cnt+=1
if cnt < 2:
print("NO")
else:
print("YES")
swap1, swap2 = -1, -1
for i in range(n-1):
if swap1 == -1 and h[i][0] == h[i+1][0]:
swap1 = i
elif swap1 != -1 and swap2 == -1 and h[i][0] == h[i+1][0]:
swap2 = i
break
for i in range(n):
print(h[i][1], end=' ')
print('')
for i in range(swap1):
print(h[i][1], end=' ')
print(h[swap1+1][1], h[swap1][1], end=' ')
for i in range(swap1+2, n):
print(h[i][1], end=' ')
print('')
for i in range(swap2):
print(h[i][1], end=' ')
print(h[swap2+1][1], h[swap2][1], end=' ')
for i in range(swap2+2, n):
print(h[i][1], end=' ')
``` | output | 1 | 20,660 | 14 | 41,321 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,661 | 14 | 41,322 |
Tags: implementation, sortings
Correct Solution:
```
def print_permutation(array):
temp = ""
for ar in array:
temp += str(ar[1])+" "
return temp.strip()
n = int(input().strip())
a = list(map(int, input().split()))
for i in range(n):
a[i] = (a[i], i+1)
a.sort(key=lambda t: t[0])
b = a.copy()
index = 0
count = 1
for i in range(n-1):
if b[i][0] == b[i+1][0]:
temp = b[i]
b[i] = b[i+1]
b[i+1] = temp
index = i + 1
count += 1
break
c = b.copy()
for i in range(index, n-1):
if c[i][0] == c[i+1][0]:
temp = c[i]
c[i] = c[i+1]
c[i+1] = temp
count += 1
break
if count == 3:
print("YES")
print(print_permutation(a))
print(print_permutation(b))
print(print_permutation(c))
else:
print("NO")
``` | output | 1 | 20,661 | 14 | 41,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,662 | 14 | 41,324 |
Tags: implementation, sortings
Correct Solution:
```
n,inp = int(input()),input().split(" ")
dict = [ [i,int(inp[i])] for i in range(n)]
dict.sort(key=lambda i: i[1])
val = [i[1] for i in dict]
f = [i[0]+1 for i in dict]
i = p = 0
if len(val) - len(set(val)) < 2:
print("NO")
else:
print("YES")
print(" ".join(map(str,f)))
for i in range(n):
if val[i:].count(val[i]) >= 2:
if p==0:
s = f[:]
s[i],s[i+1] = s[i+1],s[i]
p = 1
print(" ".join(map(str,s)))
else:
t = s[:]
t[i],t[i+1] = t[i+1],t[i]
print(" ".join(map(str,t)))
break
``` | output | 1 | 20,662 | 14 | 41,325 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,663 | 14 | 41,326 |
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
a = [int(i) for i in input().split()]
s = sorted([(a[i],i) for i in range(n)])
f = [s[i][1] for i in range(n)]
swp = []
for i in range(n-1):
if s[i][0] == s[i+1][0]:
swp.append((i,i+1))
if len(swp)==2:
print('YES')
print(' '.join(str(k+1) for k in f))
for i,j in swp:
f[i],f[j]=f[j],f[i]
print(' '.join(str(l+1) for l in f))
exit()
print('NO')
``` | output | 1 | 20,663 | 14 | 41,327 |
Provide tags and a correct Python 3 solution for this coding contest problem.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks. | instruction | 0 | 20,664 | 14 | 41,328 |
Tags: implementation, sortings
Correct Solution:
```
n = int(input())
l = list(map(int, input().split()))
a = []
for i in range(n):
a.append((l[i], i + 1))
a.sort()
cnt = 0
i = 0
maxi = 0;
while i < n:
c = 0
j = i
while i < n:
if a[i][0] == a[j][0]:
c += 1
else:
break
i += 1
if c > 1:
cnt += 1
maxi = max(c, maxi)
if cnt < 1 or (cnt == 1 and maxi < 3):
print("NO")
else:
print("YES")
for i in range(n):
print(a[i][1], end = " ")
print()
for i in range(1, n):
if a[i][0] == a[i - 1][0]:
a[i], a[i - 1] = a[i - 1], a[i]
break
for i in range(n):
print(a[i][1], end = " ")
print()
for i in range(n - 1, 0, -1):
if a[i][0] == a[i - 1][0]:
a[i], a[i - 1] = a[i - 1], a[i]
break
for i in range(n):
print(a[i][1], end = " ")
``` | output | 1 | 20,664 | 14 | 41,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n,a,q,w,r=int(input()),list(map(int,input().split())),[],[],[0]
for i in range(n):q.append([a[i],i+1])
q.sort()
for i in range(1,n):
if q[i][0]==q[i-1][0]:r[0]+=1;r.append(i+1)
if r[0]==2:break
for i in q:w.append(i[1])
if r[0]==2:
print("YES")
print(*w)
for i in range(1,3):w[r[i]-1],w[r[i]-2]=w[r[i]-2],w[r[i]-1];print(*w)
else:print("NO")
``` | instruction | 0 | 20,665 | 14 | 41,330 |
Yes | output | 1 | 20,665 | 14 | 41,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
def main():
n = int(input())
x = [[int(y),0] for y in input().split()] #Lectura de datos
solucion = []
for i in range(len(x)):
x[i][1] = i+1
x.sort()
solucion.append(x)
for i in range(len(x)):
if(i+1 < n and x[i][0] == x[i+1][0]):
x[i+1],x[i] = x[i],x[i+1]
solucion.append([z for z in x])
x[i],x[i+1] = x[i+1],x[i]
if(len(solucion) == 3):
break;
if(len(solucion) == 3):
print("YES")
for i in range(3):
for j in range(len(x)-1):
print(solucion[i][j][1],end=' ')
print(solucion[i][len(x)-1][1])
else:
print("NO")
main()
``` | instruction | 0 | 20,666 | 14 | 41,332 |
Yes | output | 1 | 20,666 | 14 | 41,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
from functools import reduce
from itertools import permutations
from sys import setrecursionlimit
setrecursionlimit(100000)
result = 0
def gen(n, ans = []):
global result
if not n:
print(*ans)
result += 1
return
if result >= 3:
return
for y in permutations(c[-n]):
gen(n - 1, ans + list(y))
if result >= 3:
return
n, a, c = int(input()), list(map(int, input().split())), {}
for i in range(n):
if a[i] not in c:
c[a[i]] = []
c[a[i]].append(i + 1)
c = [c[x] for x in sorted(set(a))]
if reduce(lambda a, b: (a if type(a) == int else len(a)) * (b if type(b) == int else len(b)), c, 1) < 3:
print('NO')
else:
print('YES')
gen(len(c))
``` | instruction | 0 | 20,667 | 14 | 41,334 |
Yes | output | 1 | 20,667 | 14 | 41,335 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n = int(input())
l = list(map(int,input().split()))
ques = []
for i in range (n):
ques.append((i,l[i]))
ques = sorted(ques, key = lambda x: (x[1],x[0]))
check = 0
for i in range (n-1):
if ques[i][1] == ques[i+1][1]:
check += 1
if check == 2:
print('YES')
for j in range (n):
print(ques[j][0]+1,end = ' ')
print()
count = 0
for j in range (n-1):
if ques[j][1] == ques[j+1][1]:
count += 1
ques[j],ques[j+1] = ques[j+1],ques[j]
for k in range (n):
print(ques[k][0]+1,end = ' ')
print()
ques[j],ques[j+1] = ques[j+1],ques[j]
if count == 2:
exit()
print('NO')
``` | instruction | 0 | 20,668 | 14 | 41,336 |
Yes | output | 1 | 20,668 | 14 | 41,337 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n = int(input())
l = list(map(int,input().split()))
q = []
w = []
r = [0]
for i in range(n):
q.append([l[i],i])
q=sorted(q)
for j in range(1,n):
if q[j][0]==q[i-1][0]:
r[0]+=1;
r.append(i)
for i in q:
w.append(i[1])
if r[0]==2:
print("YES")
print(*w)
for k in range(1,3):
w[r[k]-1], w[r[k]-2] = w[r[k]-2], w[r[k]-1]
print(*w)
else:
print("NO")
``` | instruction | 0 | 20,669 | 14 | 41,338 |
No | output | 1 | 20,669 | 14 | 41,339 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n,a=int(input()),sorted(map(int,input().split()))
q,r=[i for i in range(1,n+1)],[0]
for i in range(1,n):
if a[i]==a[i-1]:r[0]+=1;r.append(i+1)
if r[0]==2:break
if r[0]==2:
print("YES")
for i in range(1,3):q[r[i]-1],q[r[i]-2]=q[r[i]-2],q[r[i]-1];print(q)
else:print("NO")
``` | instruction | 0 | 20,670 | 14 | 41,340 |
No | output | 1 | 20,670 | 14 | 41,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n = int(input())
ar = [int(i) for i in input().split()]
new = sorted((ar[i],i+1) for i in range(n))
res = [new[i][1] for i in range(n)]
swap = []
for i in range(n-1):
if new[i][0] == new[i+1][0]:
swap.append((i,i+1))
if len(swap) == 2:
print("YES")
print(" ".join(str(i) for i in res))
for j,k in swap:
res[j],res[k] = res[k],res[j]
print(" ".join(str(i) for i in res))
quit()
print("NO")
print(swap)
``` | instruction | 0 | 20,671 | 14 | 41,342 |
No | output | 1 | 20,671 | 14 | 41,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
It's time polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got down to business. In total, there are n tasks for the day and each animal should do each of these tasks. For each task, they have evaluated its difficulty. Also animals decided to do the tasks in order of their difficulty. Unfortunately, some tasks can have the same difficulty, so the order in which one can perform the tasks may vary.
Menshykov, Uslada and Horace ask you to deal with this nuisance and come up with individual plans for each of them. The plan is a sequence describing the order in which an animal should do all the n tasks. Besides, each of them wants to have its own unique plan. Therefore three plans must form three different sequences. You are to find the required plans, or otherwise deliver the sad news to them by stating that it is impossible to come up with three distinct plans for the given tasks.
Input
The first line contains integer n (1 ≤ n ≤ 2000) — the number of tasks. The second line contains n integers h1, h2, ..., hn (1 ≤ hi ≤ 2000), where hi is the difficulty of the i-th task. The larger number hi is, the more difficult the i-th task is.
Output
In the first line print "YES" (without the quotes), if it is possible to come up with three distinct plans of doing the tasks. Otherwise print in the first line "NO" (without the quotes). If three desired plans do exist, print in the second line n distinct integers that represent the numbers of the tasks in the order they are done according to the first plan. In the third and fourth line print two remaining plans in the same form.
If there are multiple possible answers, you can print any of them.
Examples
Input
4
1 3 3 1
Output
YES
1 4 2 3
4 1 2 3
4 1 3 2
Input
5
2 4 1 4 8
Output
NO
Note
In the first sample the difficulty of the tasks sets one limit: tasks 1 and 4 must be done before tasks 2 and 3. That gives the total of four possible sequences of doing tasks : [1, 4, 2, 3], [4, 1, 2, 3], [1, 4, 3, 2], [4, 1, 3, 2]. You can print any three of them in the answer.
In the second sample there are only two sequences of tasks that meet the conditions — [3, 1, 2, 4, 5] and [3, 1, 4, 2, 5]. Consequently, it is impossible to make three distinct sequences of tasks.
Submitted Solution:
```
n,a=int(input()),sorted(map(int,input().split()))
q,r=[i for i in range(1,n+1)],[0]
for i in range(1,n):
if a[i]==a[i-1]:r[0]+=1;r.append(i+1)
if r[0]==2:break
if r[0]==2:
print("YES")
print(*q)
for i in range(1,3):q[r[i]-1],q[r[i]-2]=q[r[i]-2],q[r[i]-1];print(*q)
else:print("NO")
``` | instruction | 0 | 20,672 | 14 | 41,344 |
No | output | 1 | 20,672 | 14 | 41,345 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely. | instruction | 0 | 21,389 | 14 | 42,778 |
Tags: binary search, math, number theory, two pointers
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from bisect import bisect_left as bsl;import math
def sieve(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * 2, n + 1, p):
prime[i] = False
p += 1
prime[0]= False
prime[1]= False
pp=[]
for p in range(n + 1):
if prime[p]:
pp.append(p)
return pp
primes=sieve(10**6)
t=int(input());vals=list(map(int,input().split()))
for j in range(t):
n=vals[j]
ind1=min(bsl(primes,math.floor(math.sqrt(n))),len(primes)-1)
ind2=min(bsl(primes,n),len(primes)-1)
if primes[ind1]>math.floor(math.sqrt(n)):
ind1-=1
if primes[ind2]>n:
ind2-=1
print(ind2+1-ind1)
``` | output | 1 | 21,389 | 14 | 42,779 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely. | instruction | 0 | 21,390 | 14 | 42,780 |
Tags: binary search, math, number theory, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
import math
import bisect
import heapq
def main():
pass
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def binary(n):
return (bin(n).replace("0b", ""))
def decimal(s):
return (int(s, 2))
def pow2(n):
p = 0
while (n > 1):
n //= 2
p += 1
return (p)
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
l.append(i)
n = n / i
if n > 2:
l.append(int(n))
return (l)
def isPrime(n):
if (n == 1):
return (False)
else:
root = int(n ** 0.5)
root += 1
for i in range(2, root):
if (n % i == 0):
return (False)
return (True)
def maxPrimeFactors(n):
maxPrime = -1
while n % 2 == 0:
maxPrime = 2
n >>= 1
for i in range(3, int(math.sqrt(n)) + 1, 2):
while n % i == 0:
maxPrime = i
n = n / i
if n > 2:
maxPrime = n
return int(maxPrime)
def countcon(s, i):
c = 0
ch = s[i]
for i in range(i, len(s)):
if (s[i] == ch):
c += 1
else:
break
return (c)
def lis(arr):
n = len(arr)
lis = [1] * n
for i in range(1, n):
for j in range(0, i):
if arr[i] > arr[j] and lis[i] < lis[j] + 1:
lis[i] = lis[j] + 1
maximum = 0
for i in range(n):
maximum = max(maximum, lis[i])
return maximum
def isSubSequence(str1, str2):
m = len(str1)
n = len(str2)
j = 0
i = 0
while j < m and i < n:
if str1[j] == str2[i]:
j = j + 1
i = i + 1
return j == m
def maxfac(n):
root = int(n ** 0.5)
for i in range(2, root + 1):
if (n % i == 0):
return (n // i)
return (n)
def p2(n):
c=0
while(n%2==0):
n//=2
c+=1
return c
def seive(n):
primes=[True]*(n+1)
primes[1]=primes[0]=False
for i in range(2,n+1):
if(primes[i]):
for j in range(i+i,n+1,i):
primes[j]=False
p=[]
for i in range(0,n+1):
if(primes[i]):
p.append(i)
return(p)
pr=seive(1000000)
n=int(input())
l=list(map(int,input().split()))
for i in l:
if(i==1):
print(1)
else:
t=i
ind=bisect.bisect(pr,int(i**0.5))
indr=bisect.bisect(pr,i)
print(1+indr-ind)
``` | output | 1 | 21,390 | 14 | 42,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely. | instruction | 0 | 21,392 | 14 | 42,784 |
Tags: binary search, math, number theory, two pointers
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
"""
New numbers are only lonely if prime.
When does a prime stop being lonely
"""
def get_p(n):
""" Returns a list of primes < n """
z = int(n**0.5)+1
for s in range(4,len(sieve),2):
sieve[s] = False
for i in range(3,z,2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((n-i*i-1)//(2*i)+1)
if i <= 1000:
sq_primes.add(i*i)
return
lim = 10**6
sieve = [True]*(lim+1)
sq_primes = set()
sq_primes.add(4)
get_p(lim+1)
ans = [0,1]
for i in range(2,10**6+1):
tmp = ans[-1]
if sieve[i]:
tmp += 1
elif i in sq_primes:
tmp -= 1
ans.append(tmp)
def solve():
T = int(input().strip())
A = [int(s) for s in input().split()]
print(*[ans[A[j]] for j in range(T)])
return
solve()
#print(time.time()-start_time)
``` | output | 1 | 21,392 | 14 | 42,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely. | instruction | 0 | 21,395 | 14 | 42,790 |
Tags: binary search, math, number theory, two pointers
Correct Solution:
```
import math
import sys
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def SieveOfEratosthenes(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
pre=[0]
for j in range(1,n+1):
if prime[j]:
pre.append(pre[-1]+1)
else:
pre.append(pre[-1])
return pre
pre=SieveOfEratosthenes(10**6+1)
t=int(input())
b=list(map(int,input().split()))
for j in b:
print(pre[j]-pre[int(j**0.5)]+1)
``` | output | 1 | 21,395 | 14 | 42,791 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely. | instruction | 0 | 21,396 | 14 | 42,792 |
Tags: binary search, math, number theory, two pointers
Correct Solution:
```
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
################################# fast IO ###############################
input = sys.stdin.buffer.readline
n = int(input())
a = list(map(int,input().split()))
n = max(a)+1
spf = [i for i in range(n)]
for i in range(4,n,2): spf[i] = 2
for i in range(3,int(n**.5)+1,2):
if spf[i]!=i:continue
for j in range(i*i, n, i):
if spf[j]==j:spf[j] = i
cnt = 0
dp = [0]*n
for i in range(1,n):
if spf[i]==i: cnt+=1
dp[i] = cnt
print("\n".join(str(dp[n]-dp[int(n**.5)]+1) for n in a))
``` | output | 1 | 21,396 | 14 | 42,793 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
Submitted Solution:
```
# SHRi GANESHA author: Kunal Verma #
import os,sys
from collections import defaultdict, Counter, deque
from io import BytesIO, IOBase
from math import gcd
def lcm(a,b):
return (a*b)//gcd(a,b)
import math as mt
MAXN = 100001
spf = [0 for i in range(MAXN)]
def getFactorization(x):
ret = list()
while (x != 1):
ret.append(spf[x])
x = x // spf[x]
return ret
import math
def main():
dp = [0] * (1000001)
n = 1000001
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
dp[1] = 1
for i in range(2, n):
if prime[i] == True:
dp[i] = 1
if i * i < n + 1:
dp[i * i] = -1
for i in range(1, n):
dp[i] = dp[i - 1] + dp[i]
n = int(input())
a = [int(x) for x in input().split()]
for j in a:
print(dp[j])
#Fast IO 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")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
``` | instruction | 0 | 21,397 | 14 | 42,794 |
Yes | output | 1 | 21,397 | 14 | 42,795 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
# mandatory imports
import os
import sys
from io import BytesIO, IOBase
from math import log2, ceil, sqrt, gcd, log
# optional imports
# from itertools import permutations
# from functools import cmp_to_key # for adding custom comparator
# from fractions import Fraction
from collections import *
from bisect import *
# from __future__ import print_function # for PyPy2
# from heapq import *
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
g = lambda : input().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
rr = lambda x : reversed(range(x))
mod = int(1e9)+7
inf = float("inf")
n = int(1e6)
p = [1]*(n+1)
p[0] = p[1] = 0
for i in range(2, 1001):
if p[i]:
for j in range(i+i, n+1, i):
p[j] = 0
for i in range(1, n+1):
p[i] += p[i-1]
# print(*p[:11])
g()
for v in gil():
print(p[v] - p[int(sqrt(v))]+1)
``` | instruction | 0 | 21,399 | 14 | 42,798 |
Yes | output | 1 | 21,399 | 14 | 42,799 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
Submitted Solution:
```
import math
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def main():
pass
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
def sieve_of_eratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while p * p <= n:
if prime[p]:
for i in range(p * p, n + 1, p):
prime[i] = False
p += 1
return prime
number = 10**6
check = [0]*(number+1)
p = sieve_of_eratosthenes(number)
p[0], p[1] = False, False
j = 1
for i in p[1:]:
if i:
check[j] = check[j-1] + 1
else:
check[j] = check[j-1]
j += 1
t = int(input())
for i in map(int, input().split()):
x = math.floor(math.sqrt(i))
print(check[i] - check[x] + 1)
``` | instruction | 0 | 21,400 | 14 | 42,800 |
Yes | output | 1 | 21,400 | 14 | 42,801 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
Submitted Solution:
```
import math
n=int(input())
nums=list(map(int, input().rstrip().split()))
for i in nums:
if i<=3:
print(i)
continue
total=0
for j in range(1, i+1):
if j==1:
total+=1
continue
if j%2!=0:
#if j**2>i:
# total+=1
# print(f'j: {j}')
# continue
#if int(math.sqrt(j))!=math.sqrt(j):
# total+=1
# print(f'j: {j}')
# continue
#con1=True
#if j**2<=i or int(math.sqrt(j))==math.sqrt(j):
# con1=False
#if con1:
# total+=1
if j==3:
if 9>i:
total+=1
continue
con=True
for k in range(2, int(math.sqrt(j))+1):
if j%k==0:
con=False
break
if con:
#print(f'j: {j}')
total+=1
print(total)
``` | instruction | 0 | 21,401 | 14 | 42,802 |
No | output | 1 | 21,401 | 14 | 42,803 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
In number world, two different numbers are friends if they have a lot in common, but also each one has unique perks.
More precisely, two different numbers a and b are friends if gcd(a,b), (a)/(gcd(a,b)), (b)/(gcd(a,b)) can form sides of a triangle.
Three numbers a, b and c can form sides of a triangle if a + b > c, b + c > a and c + a > b.
In a group of numbers, a number is lonely if it doesn't have any friends in that group.
Given a group of numbers containing all numbers from 1, 2, 3, ..., n, how many numbers in that group are lonely?
Input
The first line contains a single integer t (1 ≤ t ≤ 10^6) - number of test cases.
On next line there are t numbers, n_i (1 ≤ n_i ≤ 10^6) - meaning that in case i you should solve for numbers 1, 2, 3, ..., n_i.
Output
For each test case, print the answer on separate lines: number of lonely numbers in group 1, 2, 3, ..., n_i.
Example
Input
3
1 5 10
Output
1
3
3
Note
For first test case, 1 is the only number and therefore lonely.
For second test case where n=5, numbers 1, 3 and 5 are lonely.
For third test case where n=10, numbers 1, 5 and 7 are lonely.
Submitted Solution:
```
import sys,functools,collections,bisect,math,heapq
input = sys.stdin.readline
#print = sys.stdout.write
sys.setrecursionlimit(300000)
N = 10**6 + 1
arr = [i for i in range(N)]
p = []
for i in range(2,N):
if arr[i] == i:
p.append(i)
for j in range(i*i,N,i):
arr[j] = i
#print(len(p))
n = int(input())
arr = list(map(int,input().strip().split()))
for ele in arr:
start = bisect.bisect_left(p,ele**0.5)
end = bisect.bisect_right(p,ele)
print(end-start+1)
``` | instruction | 0 | 21,402 | 14 | 42,804 |
No | output | 1 | 21,402 | 14 | 42,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 21,506 | 14 | 43,012 |
Tags: combinatorics
Correct Solution:
```
inp = input().split(' ')
n = int(inp[0])
k = int(inp[1])
print((k**(k-1)*(n-k)**(n-k)) % 1000000007)
``` | output | 1 | 21,506 | 14 | 43,013 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 21,507 | 14 | 43,014 |
Tags: combinatorics
Correct Solution:
```
n,k=map(int,input().split());n-=k;print(k**~-k*n**n%(10**9+7))
``` | output | 1 | 21,507 | 14 | 43,015 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 21,508 | 14 | 43,016 |
Tags: combinatorics
Correct Solution:
```
n, k = map(int, input().split())
d = 1000000007
def f(a, b):
if b == 0: return 1
s, c = 0, b * a
for i in range(1, b + 1):
s += c * f(i, b - i)
c = (a * c * (b - i)) // (i + 1)
return s
print((k * f(1, k - 1) * pow(n - k, n - k, d)) % d)
``` | output | 1 | 21,508 | 14 | 43,017 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 21,509 | 14 | 43,018 |
Tags: combinatorics
Correct Solution:
```
n,k = list(map(int,input().split()))
print(((k**(k-1))*((n-k)**(n-k)))%((10**9)+7))
``` | output | 1 | 21,509 | 14 | 43,019 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little penguin Polo loves his home village. The village has n houses, indexed by integers from 1 to n. Each house has a plaque containing an integer, the i-th house has a plaque containing integer pi (1 ≤ pi ≤ n).
Little penguin Polo loves walking around this village. The walk looks like that. First he stands by a house number x. Then he goes to the house whose number is written on the plaque of house x (that is, to house px), then he goes to the house whose number is written on the plaque of house px (that is, to house ppx), and so on.
We know that:
1. When the penguin starts walking from any house indexed from 1 to k, inclusive, he can walk to house number 1.
2. When the penguin starts walking from any house indexed from k + 1 to n, inclusive, he definitely cannot walk to house number 1.
3. When the penguin starts walking from house number 1, he can get back to house number 1 after some non-zero number of walks from a house to a house.
You need to find the number of ways you may write the numbers on the houses' plaques so as to fulfill the three above described conditions. Print the remainder after dividing this number by 1000000007 (109 + 7).
Input
The single line contains two space-separated integers n and k (1 ≤ n ≤ 1000, 1 ≤ k ≤ min(8, n)) — the number of the houses and the number k from the statement.
Output
In a single line print a single integer — the answer to the problem modulo 1000000007 (109 + 7).
Examples
Input
5 2
Output
54
Input
7 4
Output
1728 | instruction | 0 | 21,511 | 14 | 43,022 |
Tags: combinatorics
Correct Solution:
```
nk=input().split()
n=int(nk[0])
k=int(nk[1])
p=10**9+7
a=pow(k,k-1,p)
b=pow(n-k,n-k,p)
print((a*b)%p)
``` | output | 1 | 21,511 | 14 | 43,023 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,570 | 14 | 43,140 |
Tags: data structures, math, number theory
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
class SegmentTree:
def __init__(self, data, default=0, func=max):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# ------------------------
from math import gcd
from collections import defaultdict
from bisect import bisect_left, bisect_right
n = int(input())
a = list(map(int, input().split()))
store = defaultdict(list)
def findFrequency(left, right, element):
a = bisect_left(store[element], left)
b = bisect_right(store[element], right)
return b - a
for i in range(n):
store[a[i]].append(i+1)
st1 = SegmentTree(a, func=gcd)
st2 = SegmentTree(a, func=min, default=10**10)
for _ in range(int(input())):
x, y = map(int, input().split())
ans1, ans2 = st1.query(x-1, y-1), st2.query(x-1, y-1)
if ans1 != ans2:
print(y-x+1)
else:
print(y+1-x-findFrequency(x, y, ans1))
``` | output | 1 | 21,570 | 14 | 43,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,571 | 14 | 43,142 |
Tags: data structures, math, number theory
Correct Solution:
```
#!/usr/bin/env python3
# from typing import *
import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq
def input():
return sys.stdin.readline()[:-1]
# sys.setrecursionlimit(1000000)
# _INPUT = """5
# 1 3 2 4 2
# 4
# 1 5
# 2 5
# 3 5
# 4 5
# """
# sys.stdin = io.StringIO(_INPUT)
def calc_gcd(v1, v2):
if v1 == -1:
return v2
elif v2 == -1:
return v1
else:
return math.gcd(v1, v2)
def query_gcd(L, R):
l = L + N1
r = R + N1
v = -1
while l < r:
if l & 1:
v = calc_gcd(v, Dat[l])
l += 1
if r & 1:
v = calc_gcd(v, Dat[r-1])
r -= 1
l //= 2
r //= 2
return v
def query_gcd_1(L, R, i, l, r):
if r <= L or R <= l:
return -1
if L <= l and r <= R:
return Dat[i]
d1 = query_gcd_1(L, R, i*2, l, (l+r)//2)
d2 = query_gcd_1(L, R, i*2+1, (l+r)//2, r)
return calc_gcd(d1, d2)
def get_count(L, R, x):
if Pos[x]:
i1 = bisect.bisect_left(Pos[x], L)
i2 = bisect.bisect_left(Pos[x], R)
return i2 - i1
else:
return 0
N = int(input())
S = list(map(int, input().split()))
N1 = 2 ** (N-1).bit_length()
Dat = [0] * N1 + S + [-1] * (N1-N)
for i in reversed(range(1, N1)):
Dat[i] = calc_gcd(Dat[i*2], Dat[i*2+1])
Pos = collections.defaultdict(list)
for i in range(N):
Pos[S[i]].append(i)
d = query_gcd(2, 5)
T = int(input())
for _ in range(T):
L, R = map(int, input().split())
L -= 1
d = query_gcd(L, R)
ans = (R - L) - get_count(L, R, d)
print(ans)
``` | output | 1 | 21,571 | 14 | 43,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,572 | 14 | 43,144 |
Tags: data structures, math, number theory
Correct Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
# import bisect
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
temp = (n*n)
# temp =temp//2
temp %= m
return temp
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return [int(x) for x in input().split()]
def sapin():
return [int(x) for x in input()]
#?############################################################
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class SegmentTree:
def __init__(self, data, default=0, func=min):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
"""func of data[start, stop)"""
start += self._size
stop += self._size
res_left = res_right = self._default
while start < stop:
if start & 1:
res_left = self._func(res_left, self.data[start])
start += 1
if stop & 1:
stop -= 1
res_right = self._func(self.data[stop], res_right)
start >>= 1
stop >>= 1
return self._func(res_left, res_right)
def __repr__(self):
return "SegmentTree({0})".format(self.data)
store = defaultdict(lambda:[])
def ff(left, right, element):
a = lower_bound(store[element], left)
b = upper_bound(store[element], right)
return b - a
n = int(input())
a = mapin()
q = int(input())
s=SegmentTree(a,0,math.gcd)
# ss = SegmentTree(a, 1e12)
for i in range(n):
# if(a[i] not in store):
# store[a[i]] = []
store[a[i]].append(i)
for _ in range(q):
l, r = mapin()
l-=1
r-=1
# mi = []
# if(l == r):
# print(0)
# else:
temp = s.query(l, r+1)
# temp2 = ss.query(l, r)
temp3 = ff(l, r, temp)
print(r-l+1-temp3)
``` | output | 1 | 21,572 | 14 | 43,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,573 | 14 | 43,146 |
Tags: data structures, math, number theory
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
#from collections import defaultdict
from collections import deque
import threading
#sys.setrecursionlimit(300000)
#threading.stack_size(10**8)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
#-------------------------------------------------------------------------
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: math.gcd(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
from collections import defaultdict as dict
from bisect import bisect_left as lower_bound
from bisect import bisect_right as upper_bound
store = dict(list)
def findFrequency(arr, n, left, right, element):
a = lower_bound(store[element], left)
b = upper_bound(store[element], right)
return b - a
n=int(input())
l=list(map(int,input().split()))
for i in range(n):
store[l[i]].append(i + 1)
t=int(input())
st=SegmentTree(l)
d=dict()
for i in range(n):
if l[i] not in d:
d.update({l[i]:1})
else:
d[l[i]]+=1
for i in range(t):
l1,r=map(int,input().split())
g=st.query(l1-1,r-1)
#print(g)
c=findFrequency(l,n,l1,r,g)
print(r-l1+1-c)
``` | output | 1 | 21,573 | 14 | 43,147 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Mole is hungry again. He found one ant colony, consisting of n ants, ordered in a row. Each ant i (1 ≤ i ≤ n) has a strength si.
In order to make his dinner more interesting, Mole organizes a version of «Hunger Games» for the ants. He chooses two numbers l and r (1 ≤ l ≤ r ≤ n) and each pair of ants with indices between l and r (inclusively) will fight. When two ants i and j fight, ant i gets one battle point only if si divides sj (also, ant j gets one battle point only if sj divides si).
After all fights have been finished, Mole makes the ranking. An ant i, with vi battle points obtained, is going to be freed only if vi = r - l, or in other words only if it took a point in every fight it participated. After that, Mole eats the rest of the ants. Note that there can be many ants freed or even none.
In order to choose the best sequence, Mole gives you t segments [li, ri] and asks for each of them how many ants is he going to eat if those ants fight.
Input
The first line contains one integer n (1 ≤ n ≤ 105), the size of the ant colony.
The second line contains n integers s1, s2, ..., sn (1 ≤ si ≤ 109), the strengths of the ants.
The third line contains one integer t (1 ≤ t ≤ 105), the number of test cases.
Each of the next t lines contains two integers li and ri (1 ≤ li ≤ ri ≤ n), describing one query.
Output
Print to the standard output t lines. The i-th line contains number of ants that Mole eats from the segment [li, ri].
Examples
Input
5
1 3 2 4 2
4
1 5
2 5
3 5
4 5
Output
4
4
1
1
Note
In the first test battle points for each ant are v = [4, 0, 2, 0, 2], so ant number 1 is freed. Mole eats the ants 2, 3, 4, 5.
In the second test case battle points are v = [0, 2, 0, 2], so no ant is freed and all of them are eaten by Mole.
In the third test case battle points are v = [2, 0, 2], so ants number 3 and 5 are freed. Mole eats only the ant 4.
In the fourth test case battle points are v = [0, 1], so ant number 5 is freed. Mole eats the ant 4. | instruction | 0 | 21,574 | 14 | 43,148 |
Tags: data structures, math, number theory
Correct Solution:
```
import os, sys
from io import BytesIO, IOBase
from math import gcd
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
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
def build_segment(a, tree, i_tree, left, right):
if left==right:
tree[i_tree]=[a[left],a[left],1]
return
else:
mid=(left+right)//2
build_segment(a,tree,i_tree*2,left,mid)
build_segment(a,tree,i_tree*2+1,mid+1,right)
tree[i_tree][0]=gcd(tree[2*i_tree][0],tree[2*i_tree+1][0])
tree[i_tree][1]=min(tree[2*i_tree][1],tree[2*i_tree+1][1])
if tree[i_tree][1]==tree[2*i_tree][1]:
tree[i_tree][2]+=tree[2*i_tree][2]
if tree[i_tree][1]==tree[2*i_tree+1][1]:
tree[i_tree][2]+=tree[2*i_tree+1][2]
return
def querry(tree, i_tree, left, right, ql, qr,ar):
if right<ql or left>qr:
return
elif ql<=left and right<=qr:
ar[0] = gcd(ar[0],tree[i_tree][0])
if not ar[1]:
t=tree[i_tree][1]
else:
t=min(ar[1],tree[i_tree][1])
if ar[1]!=t:
ar[2]=0
if tree[i_tree][1]==t:
ar[2]+=tree[i_tree][2]
ar[1]=t
else:
mid=(left+right)//2
querry(tree,2*i_tree,left,mid,ql,qr,ar)
querry(tree,2*i_tree+1,mid+1,right,ql,qr,ar)
return
n=int(input())
a=list(map(int,input().split()))
t=[[0,0,0] for _ in range(4*n +1)]
build_segment(a,t,1,0,n-1)
for _ in range(int(input())):
l,r=map(int,input().split())
ar=[0,0,0]
querry(t,1,0,n-1,l-1,r-1,ar)
if ar[0]%ar[1]:
print(r-l+1)
else:
print(r-l+1-ar[2])
``` | output | 1 | 21,574 | 14 | 43,149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.