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.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them. | instruction | 0 | 82,322 | 14 | 164,644 |
Tags: brute force, implementation
Correct Solution:
```
# cook your dish here
import sys
import bisect
import math
from itertools import permutations
m=1000000007
#a=list(map(int,input().strip().split(' ')))
#n,k,s= map(int, sys.stdin.readline().split(' '))
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect.bisect_left(a, x)
if i:
return a[i-1]
else: return -1
n=int(input())
ans=0
for i in range(1,n):
if((n-i)%i==0):ans+=1
print(ans)
``` | output | 1 | 82,322 | 14 | 164,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
n = int(input())
cnt = 0
for i in range (1,(n//2+1)):
if (((n-i)%i) < 1):
cnt+=1
print(cnt)
``` | instruction | 0 | 82,323 | 14 | 164,646 |
Yes | output | 1 | 82,323 | 14 | 164,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
workers = int(input())
res = 0
for i in range(1, int((workers - workers % 2)/2) + 1):
if (workers - i) % i == 0:
res = res + 1
print(res)
``` | instruction | 0 | 82,324 | 14 | 164,648 |
Yes | output | 1 | 82,324 | 14 | 164,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
n = int(input())
ans = 0
for i in range(1, n):
d = n - i
if(d % i == 0):
ans += 1
print(ans)
``` | instruction | 0 | 82,325 | 14 | 164,650 |
Yes | output | 1 | 82,325 | 14 | 164,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
"""
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
inputCopy
2
outputCopy
1
inputCopy
10
outputCopy
3
Note
In the second sample Fafa has 3 ways:
choose only 1 employee as a team leader with 9 employees under his responsibility.
choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
"""
n = int(input())
ans=1
for i in range(2,int(n/2)+1):
if (n-i)% i ==0:
ans+=1
print(ans)
``` | instruction | 0 | 82,326 | 14 | 164,652 |
Yes | output | 1 | 82,326 | 14 | 164,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
n = int(input())
k = 0
for i in range(1,n-1):
if n % i == 0:
k+=1
print(k)
``` | instruction | 0 | 82,327 | 14 | 164,654 |
No | output | 1 | 82,327 | 14 | 164,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
import math
n = int(input(""))
tot = 0
for i in range(1, int(math.sqrt(n))+1):
if n%1 == 0:
tot += 1
print(tot)
``` | instruction | 0 | 82,328 | 14 | 164,656 |
No | output | 1 | 82,328 | 14 | 164,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
# import sys
# sys.stdin=open("test.in","r")
# sys.stdout=open("test.out","w")
n=int(input())
c=0
for i in range (1,int(n/2)+1):
if n-i%i==0:
c+=1
print(c)
``` | instruction | 0 | 82,329 | 14 | 164,658 |
No | output | 1 | 82,329 | 14 | 164,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fafa owns a company that works on huge projects. There are n employees in Fafa's company. Whenever the company has a new project to start working on, Fafa has to divide the tasks of this project among all the employees.
Fafa finds doing this every time is very tiring for him. So, he decided to choose the best l employees in his company as team leaders. Whenever there is a new project, Fafa will divide the tasks among only the team leaders and each team leader will be responsible of some positive number of employees to give them the tasks. To make this process fair for the team leaders, each one of them should be responsible for the same number of employees. Moreover, every employee, who is not a team leader, has to be under the responsibility of exactly one team leader, and no team leader is responsible for another team leader.
Given the number of employees n, find in how many ways Fafa could choose the number of team leaders l in such a way that it is possible to divide employees between them evenly.
Input
The input consists of a single line containing a positive integer n (2 ≤ n ≤ 105) — the number of employees in Fafa's company.
Output
Print a single integer representing the answer to the problem.
Examples
Input
2
Output
1
Input
10
Output
3
Note
In the second sample Fafa has 3 ways:
* choose only 1 employee as a team leader with 9 employees under his responsibility.
* choose 2 employees as team leaders with 4 employees under the responsibility of each of them.
* choose 5 employees as team leaders with 1 employee under the responsibility of each of them.
Submitted Solution:
```
n = int(input())
cnt = 0
for i in range(1,n+1):
if (n - i) % i == 0:
cnt += 1
print(cnt)
``` | instruction | 0 | 82,330 | 14 | 164,660 |
No | output | 1 | 82,330 | 14 | 164,661 |
Provide a correct Python 3 solution for this coding contest problem.
Problem Statement
The Animal School is a primary school for animal children. You are a fox attending this school.
One day, you are given a problem called "Arithmetical Restorations" from the rabbit teacher, Hanako. Arithmetical Restorations are the problems like the following:
* You are given three positive integers, $A$, $B$ and $C$.
* Several digits in these numbers have been erased.
* You should assign a digit in each blank position so that the numbers satisfy the formula $A+B=C$.
* The first digit of each number must not be zero. It is also the same for single-digit numbers.
You are clever in mathematics, so you immediately solved this problem. Furthermore, you decided to think of a more difficult problem, to calculate the number of possible assignments to the given Arithmetical Restorations problem. If you can solve this difficult problem, you will get a good grade.
Shortly after beginning the new task, you noticed that there may be too many possible assignments to enumerate by hand. So, being the best programmer in the school as well, you are now trying to write a program to count the number of possible assignments to Arithmetical Restoration problems.
Input
The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows.
> $A$
> $B$
> $C$
Each dataset consists of three strings, $A$, $B$ and $C$. They indicate that the sum of $A$ and $B$ should be $C$. Each string consists of digits (`0`-`9`) and/or question mark (`?`). A question mark (`?`) indicates an erased digit. You may assume that the first character of each string is not `0` and each dataset has at least one `?`.
It is guaranteed that each string contains between 1 and 50 characters, inclusive. You can also assume that the lengths of three strings are equal.
The end of input is indicated by a line with a single zero.
Output
For each dataset, output the number of possible assignments to the given problem modulo 1,000,000,007. Note that there may be no way to solve the given problems because Ms. Hanako is a careless rabbit.
Sample Input
3?4
12?
5?6
?2?4
5?7?
?9?2
?????
?????
?????
0
Output for the Sample Input
2
40
200039979
Note
The answer of the first dataset is 2. They are shown below.
* 384 + 122 = 506
* 394 + 122 = 516
Example
Input
3?4
12?
5?6
?2?4
5?7?
?9?2
?????
?????
?????
0
Output
2
40
200039979 | instruction | 0 | 82,524 | 14 | 165,048 |
"Correct Solution:
```
INF = 10 ** 10
MOD = 10 ** 9 + 7
def solve(A,B,C):
A = A[::-1]
B = B[::-1]
C = C[::-1]
before =[1,0,0]
N = len(A)
for i in range(N):
dp = [0]*3
s = 0
if i == N - 1:
s += 1
for j in range(3):
for a in range(s,10):
if A[i] != '?' and int(A[i]) != a:
continue
for b in range(s,10):
if B[i] != '?' and int(B[i]) != b:
continue
for c in range(s,10):
if C[i] != '?' and int(C[i]) != c:
continue
if (j + a + b)%10 != c:
continue
dp[(j + a + b)//10] += before[j]
dp[(j + a + b)//10] %= MOD
before = dp
ans = before[0]
print(ans)
def main():
while True:
A = input()
if A == '0':
return
B = input()
C = input()
solve(A,B,C)
if __name__ == '__main__':
main()
``` | output | 1 | 82,524 | 14 | 165,049 |
Provide a correct Python 3 solution for this coding contest problem.
Problem Statement
The Animal School is a primary school for animal children. You are a fox attending this school.
One day, you are given a problem called "Arithmetical Restorations" from the rabbit teacher, Hanako. Arithmetical Restorations are the problems like the following:
* You are given three positive integers, $A$, $B$ and $C$.
* Several digits in these numbers have been erased.
* You should assign a digit in each blank position so that the numbers satisfy the formula $A+B=C$.
* The first digit of each number must not be zero. It is also the same for single-digit numbers.
You are clever in mathematics, so you immediately solved this problem. Furthermore, you decided to think of a more difficult problem, to calculate the number of possible assignments to the given Arithmetical Restorations problem. If you can solve this difficult problem, you will get a good grade.
Shortly after beginning the new task, you noticed that there may be too many possible assignments to enumerate by hand. So, being the best programmer in the school as well, you are now trying to write a program to count the number of possible assignments to Arithmetical Restoration problems.
Input
The input is a sequence of datasets. The number of datasets is less than 100. Each dataset is formatted as follows.
> $A$
> $B$
> $C$
Each dataset consists of three strings, $A$, $B$ and $C$. They indicate that the sum of $A$ and $B$ should be $C$. Each string consists of digits (`0`-`9`) and/or question mark (`?`). A question mark (`?`) indicates an erased digit. You may assume that the first character of each string is not `0` and each dataset has at least one `?`.
It is guaranteed that each string contains between 1 and 50 characters, inclusive. You can also assume that the lengths of three strings are equal.
The end of input is indicated by a line with a single zero.
Output
For each dataset, output the number of possible assignments to the given problem modulo 1,000,000,007. Note that there may be no way to solve the given problems because Ms. Hanako is a careless rabbit.
Sample Input
3?4
12?
5?6
?2?4
5?7?
?9?2
?????
?????
?????
0
Output for the Sample Input
2
40
200039979
Note
The answer of the first dataset is 2. They are shown below.
* 384 + 122 = 506
* 394 + 122 = 516
Example
Input
3?4
12?
5?6
?2?4
5?7?
?9?2
?????
?????
?????
0
Output
2
40
200039979 | instruction | 0 | 82,525 | 14 | 165,050 |
"Correct Solution:
```
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools
sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7
dd = [(-1,0),(0,1),(1,0),(0,-1)]
ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)]
def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)
def main():
rr = []
while True:
a = S()
if a == '0':
break
b = S()
c = S()
ml = max([len(a),len(b),len(c)])
if len(a) < ml:
a = '0' * (ml-len(a)) + a
if len(b) < ml:
b = '0' * (ml-len(b)) + b
if len(c) < ml:
c = '0' * (ml-len(c)) + c
r = [[0,0] for _ in range(ml+1)]
r[0][0] = 1
for i in range(ml):
ai = a[ml-i-1]
bi = b[ml-i-1]
ci = c[ml-i-1]
r0 = [0,0]
r1 = [0,0]
si = 0
if i == ml - 1:
si = 1
al = range(si,10)
if ai != '?':
al = [int(ai)]
bl = range(si,10)
if bi != '?':
bl = [int(bi)]
cl = range(si,10)
if ci != '?':
cl = [int(ci)]
for ac,bc,cc in itertools.product(al,bl,cl):
abc = ac+bc
if abc % 10 == cc:
if abc > 9:
r0[1] += 1
else:
r0[0] += 1
elif (abc+1) % 10 == cc:
if abc > 8:
r1[1] += 1
else:
r1[0] += 1
r[i+1][0] += r0[0] * r[i][0]
r[i+1][0] += r1[0] * r[i][1]
r[i+1][1] += r0[1] * r[i][0]
r[i+1][1] += r1[1] * r[i][1]
rr.append(r[ml][0] % mod)
return '\n'.join(map(str,rr))
print(main())
``` | output | 1 | 82,525 | 14 | 165,051 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,858 | 14 | 165,716 |
Tags: dfs and similar, dsu
Correct Solution:
```
n, m = map(int, input().split())
q = [[] for i in range(n + 1)]
r, s = [0] * (m + 1), 0
for i in range(1, n + 1):
t = list(map(int, input().split()))
if t[0]:
t = t[1: ]
d = set([r[j] for j in t])
if 0 in d: d.remove(0)
if len(d):
for j in d:
for k in q[j]:
r[k] = i
q[i].extend(q[j])
q[j] = []
t = [j for j in t if r[j] == 0]
for k in t:
r[k] = i
q[i].extend(t)
else:
for k in t:
r[k] = i
q[i] = t
else: s += 1
print(s + max(sum(len(i) > 0 for i in q) - 1, 0))
``` | output | 1 | 82,858 | 14 | 165,717 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,859 | 14 | 165,718 |
Tags: dfs and similar, dsu
Correct Solution:
```
def root(ids, u):
if ids[u] < 0: return u
ids[u] = root(ids, ids[u])
return ids[u]
def union(ids, u, v):
if ids[u] > ids[v]:
u, v = v, u
ids[u] += ids[v]
ids[v] = u
n, m = list(map(int, input().split()))
langs = [[] for _ in range(m)]
hasLang = False
for i in range(n):
data = list(map(int, input().split()))
if data[0] > 0:
hasLang = True
else: continue
for x in data[1:]:
langs[x-1].append(i)
if not hasLang:
print(n)
exit()
ids = [-1] * n
for _, lang in enumerate(langs):
for i in range(1, len(lang)):
u, v = lang[i-1], lang[i]
u = root(ids, u)
v = root(ids, v)
if u != v:
union(ids, u, v)
cnt = 0
for x in ids:
if x < 0: cnt += 1
print(cnt-1)
``` | output | 1 | 82,859 | 14 | 165,719 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,860 | 14 | 165,720 |
Tags: dfs and similar, dsu
Correct Solution:
```
def dfs(i,v,vi,lan,emp,bn):
if bn:
vi[i]=1
for j in lan[i]:
if not v[j]: dfs(j,v,vi,lan,emp,(bn+1)%2)
else:
v[i]=1
for j in emp[i]:
if not vi[j]: dfs(j,v,vi,lan,emp,(bn+1)%2)
def main():
emp={}
lan={}
num0=ans=0
n,m=list(map(int,input().split()))
for i in range(m): lan[i]=set()
for i in range(n):
emp[i]=set()
k=list(map(int,input().split()))
for j in range(1,k[0]+1):
emp[i].add(k[j]-1)
lan[k[j]-1].add(i)
if not k[0]: num0+=1
v=[0]*n
vi=[0]*m
for i in range(n):
if not v[i]:
v[i]=1
for j in emp[i]:
if not vi[j]: dfs(j,v,vi,lan,emp,1)
ans+=1
if num0==n: print(n)
else: print(ans-1)
if __name__=='__main__': main()
``` | output | 1 | 82,860 | 14 | 165,721 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,861 | 14 | 165,722 |
Tags: dfs and similar, dsu
Correct Solution:
```
parent=[i for i in range(200005)]
size=[1 for i in range(200005)]
def find(v):
if v == parent[v]:
return v
parent[v]=find(parent[v])
return parent[v]
def union(a,b):
a=find(a)
b=find(b)
if a is not b:
if size[a] < size[b]:
a,b=b,a
parent[b]=a
size[a] += size[b]
########################
########################
n,m=map(int,input().split())
a=[[False for i in range(110)]for j in range(110)]
for i in range(n):
k=list(map(int,input().split()))
for j in range(1,len(k)):
a[i][k[j]-1]=True
flag=False
for i in range(n):
for j in range(m):
if a[i][j]:
flag=True
if flag == False:
print(n)
else:
for i in range(n):
for j in range(i+1,n):
for k in range(m):
if a[i][k] and a[j][k]:
union(i,j)
cnt=0
for i in range(n):
if find(i)==i:
cnt += 1
print(cnt-1)
``` | output | 1 | 82,861 | 14 | 165,723 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,862 | 14 | 165,724 |
Tags: dfs and similar, dsu
Correct Solution:
```
def find(i):
if dsu[i] == i:
return i
dsu[i] = find(dsu[i])
return dsu[i]
if __name__ == '__main__':
dsu = [0]
visited = set()
iss = set()
ans = 0
N, M = map(int, input().split())
for i in range(1, M + 1):
dsu += [0]
dsu[i] = i
for i in range(N):
parent = 0
val = input().split()
if int(val[0]) == 0:
ans += 1
for j in range(len(val)-1):
if j == 0:
iss.add(int(val[j+1]))
parent = int(val[j+1])
continue
a = find(parent)
b = find(int(val[j+1]))
dsu[b] = a
f = 0
for i in range(1,M+1):
if i not in iss:
continue
f = 1
a = find(i)
if a not in visited:
ans += 1
visited.add(a)
print(ans-f)
``` | output | 1 | 82,862 | 14 | 165,725 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,863 | 14 | 165,726 |
Tags: dfs and similar, dsu
Correct Solution:
```
from collections import defaultdict
def bfs(G, node):
Q = [node]
while Q:
node = Q.pop(0)
U.remove(node)
for neighbor in G[node]:
if neighbor in Q: # already queued up
continue
elif neighbor not in U: # already visited
continue
Q.append(neighbor)
n, m = [int(i) for i in input().split()]
E = [[int(i) for i in input().split()] for _ in range(n)]
G = defaultdict(list)
l = 1 # whether someone knows a language
for i, e in enumerate(E, start=1):
n, langs = e[0], e[1:]
G[m+i].extend(langs)
for lang in langs:
l = 0
G[lang].append(m+i)
U = set(G.keys())
c = 0
while U:
node = next(iter(U))
bfs(G, node)
c += 1
print(c-1+l)
``` | output | 1 | 82,863 | 14 | 165,727 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,864 | 14 | 165,728 |
Tags: dfs and similar, dsu
Correct Solution:
```
n,m = map(int,input().split())
sets = list(range(n+m+1))
for i in range(n):
l = list(map(int,input().split()))
for j in range(1,len(l)):
sp = sets[i+1]
sl = sets[l[j]+n]
for k in range(len(sets)):
if sets[k]==sp:
sets[k] = sl
if len(l)<2:
sets[i+1] = 0
dic = {}
#print(sets)
for id in range(1,n+1):
dic[sets[id]] = 0
for id in range(1,n+1):
dic[sets[id]] += 1
#print(dic)
nl = dic.pop(0,0)
if len(dic)>0:
nl += len(dic)-1
print(nl)
``` | output | 1 | 82,864 | 14 | 165,729 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The "BerCorp" company has got n employees. These employees can use m approved official languages for the formal correspondence. The languages are numbered with integers from 1 to m. For each employee we have the list of languages, which he knows. This list could be empty, i. e. an employee may know no official languages. But the employees are willing to learn any number of official languages, as long as the company pays their lessons. A study course in one language for one employee costs 1 berdollar.
Find the minimum sum of money the company needs to spend so as any employee could correspond to any other one (their correspondence can be indirect, i. e. other employees can help out translating).
Input
The first line contains two integers n and m (2 ≤ n, m ≤ 100) — the number of employees and the number of languages.
Then n lines follow — each employee's language list. At the beginning of the i-th line is integer ki (0 ≤ ki ≤ m) — the number of languages the i-th employee knows. Next, the i-th line contains ki integers — aij (1 ≤ aij ≤ m) — the identifiers of languages the i-th employee knows. It is guaranteed that all the identifiers in one list are distinct. Note that an employee may know zero languages.
The numbers in the lines are separated by single spaces.
Output
Print a single integer — the minimum amount of money to pay so that in the end every employee could write a letter to every other one (other employees can help out translating).
Examples
Input
5 5
1 2
2 2 3
2 3 4
2 4 5
1 5
Output
0
Input
8 7
0
3 1 2 3
1 1
2 5 4
2 6 7
1 3
2 7 4
1 1
Output
2
Input
2 2
1 2
0
Output
1
Note
In the second sample the employee 1 can learn language 2, and employee 8 can learn language 4.
In the third sample employee 2 must learn language 2. | instruction | 0 | 82,865 | 14 | 165,730 |
Tags: dfs and similar, dsu
Correct Solution:
```
n, m = [int(x) for x in input().split()]
l = [[]] * n
for i in range(n):
l[i] = set(int(x) for x in input().split()[1:])
while True:
for i in range(len(l)):
for j in range(i):
if l[i] & l[j]:
l[j] |= l[i]
l = l[:i] + l[i + 1:]
break
else:
continue
break
else:
break
ans = len(l)
for s in l:
if s:
ans -= 1
break
print(ans)
``` | output | 1 | 82,865 | 14 | 165,731 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input
Input consists of a single integer n (2 ≤ n ≤ 105).
Output
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Examples
Input
2
Output
0 1 0
Input
3
Output
-1
Input
4
Output
0 1 3 2 0
Input
16
Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0 | instruction | 0 | 82,890 | 14 | 165,780 |
Tags: combinatorics, dfs and similar, dsu, graphs, greedy
Correct Solution:
```
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
``` | output | 1 | 82,890 | 14 | 165,781 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input
Input consists of a single integer n (2 ≤ n ≤ 105).
Output
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Examples
Input
2
Output
0 1 0
Input
3
Output
-1
Input
4
Output
0 1 3 2 0
Input
16
Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0 | instruction | 0 | 82,891 | 14 | 165,782 |
Tags: combinatorics, dfs and similar, dsu, graphs, greedy
Correct Solution:
```
# METO Bot 0.9.9
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
``` | output | 1 | 82,891 | 14 | 165,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Piegirl found the red button. You have one last chance to change the inevitable end.
The circuit under the button consists of n nodes, numbered from 0 to n - 1. In order to deactivate the button, the n nodes must be disarmed in a particular order. Node 0 must be disarmed first. After disarming node i, the next node to be disarmed must be either node (2·i) modulo n or node (2·i) + 1 modulo n. The last node to be disarmed must be node 0. Node 0 must be disarmed twice, but all other nodes must be disarmed exactly once.
Your task is to find any such order and print it. If there is no such order, print -1.
Input
Input consists of a single integer n (2 ≤ n ≤ 105).
Output
Print an order in which you can to disarm all nodes. If it is impossible, print -1 instead. If there are multiple orders, print any one of them.
Examples
Input
2
Output
0 1 0
Input
3
Output
-1
Input
4
Output
0 1 3 2 0
Input
16
Output
0 1 2 4 9 3 6 13 10 5 11 7 15 14 12 8 0 | instruction | 0 | 82,892 | 14 | 165,784 |
Tags: combinatorics, dfs and similar, dsu, graphs, greedy
Correct Solution:
```
# METO Bot 0.9.9.1
n=int(input())
if n&1:
print(-1)
else:
D,R=[False]*(10**6),[0]*(10**6)
i,j=0,0
while True:
D[j]=True
R[i]=j
i+=1
if not D[(j+n)>>1]:
j=(j+n)>>1
elif not D[j>>1]:
j=j>>1
else:
break
print(" ".join(str(R[i]) for i in range(n,-1,-1)))
``` | output | 1 | 82,892 | 14 | 165,785 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.
There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).
However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:
1. Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.
2. Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company.
At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.
Help the crisis manager and answer all of his queries.
Input
The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has.
Next q lines contain the queries of the crisis manager. Each query looks like type x y, where <image>. If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.
Output
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
Examples
Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Output
NO
YES
YES
Submitted Solution:
```
def dfs(svyaz, a, b, used):
global check
used[a] = True
for i in svyaz[a]:
if not used[i]:
#print(i, b)
if i == b:
print('YES')
check = True
dfs(svyaz, i, b, used)
vertey, n = map(int, input().split())
svyaz = [[] for i in range(vertey)]
for i in range(n):
key, a, b = map(int, input().split())
if key == 1 and a != b:
svyaz[a - 1].append(b - 1)
svyaz[b - 1].append(a - 1)
if key == 2 and a != b:
for j in range(a - 1, b - 1):
svyaz[j].append(j + 1)
svyaz[j + 1].append(j)
if key == 3:
check = False
dfs(svyaz, a - 1, b - 1, [False] * vertey)
if check == False:
print('NO')
``` | instruction | 0 | 82,974 | 14 | 165,948 |
No | output | 1 | 82,974 | 14 | 165,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.
There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).
However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:
1. Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.
2. Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company.
At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.
Help the crisis manager and answer all of his queries.
Input
The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has.
Next q lines contain the queries of the crisis manager. Each query looks like type x y, where <image>. If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.
Output
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
Examples
Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Output
NO
YES
YES
Submitted Solution:
```
line=input()
uf = dict()
def find(a):
if a in uf:
find(uf[a])
else:
return(a)
def union(a,b):
ra = find(a)
rb = find(b)
if ra == rb:
uf[ra] = rb
else:
()
n,q = map(int, line.split(' '))
for i in range(1,q):
if len(line.split(' ')) < 3:
continue
else:
x,y,z = map(int, line.split(' '))
if x == 1:
union(y,z)
elif x==2:
for j in range(y,z):
union(y,j)
else:
if find(y)==find(z):
print('YES')
else:
print('NO')
``` | instruction | 0 | 82,975 | 14 | 165,950 |
No | output | 1 | 82,975 | 14 | 165,951 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.
There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).
However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:
1. Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.
2. Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company.
At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.
Help the crisis manager and answer all of his queries.
Input
The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has.
Next q lines contain the queries of the crisis manager. Each query looks like type x y, where <image>. If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.
Output
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
Examples
Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Output
NO
YES
YES
Submitted Solution:
```
n,q = map(int, input().split(' '))
uf = dict()
def find(l,start):
if l in uf:
return find(uf[l],start)
else:
if start != l:
uf[start] = l
return l
def union(l,r):
fl = find(l,l)
fr = find(r,r)
if fl != fr:
uf[fl] = fr
def union_list(l,r):
for i in range(l,r):
union(i,i+1)
for i in range(0,q):
t,l,r = map(int, input().split(' '))
if t == 3:
if find(l,l) == find(r,r):
print('YES')
else:
print('no')
if t == 1:
union(l,r)
if t == 2:
union_list(l,r)
``` | instruction | 0 | 82,976 | 14 | 165,952 |
No | output | 1 | 82,976 | 14 | 165,953 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Even the most successful company can go through a crisis period when you have to make a hard decision — to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following model of a company.
There are n people working for the Large Software Company. Each person belongs to some department. Initially, each person works on his own project in his own department (thus, each company initially consists of n departments, one person in each).
However, harsh times have come to the company and the management had to hire a crisis manager who would rebuild the working process in order to boost efficiency. Let's use team(person) to represent a team where person person works. A crisis manager can make decisions of two types:
1. Merge departments team(x) and team(y) into one large department containing all the employees of team(x) and team(y), where x and y (1 ≤ x, y ≤ n) — are numbers of two of some company employees. If team(x) matches team(y), then nothing happens.
2. Merge departments team(x), team(x + 1), ..., team(y), where x and y (1 ≤ x ≤ y ≤ n) — the numbers of some two employees of the company.
At that the crisis manager can sometimes wonder whether employees x and y (1 ≤ x, y ≤ n) work at the same department.
Help the crisis manager and answer all of his queries.
Input
The first line of the input contains two integers n and q (1 ≤ n ≤ 200 000, 1 ≤ q ≤ 500 000) — the number of the employees of the company and the number of queries the crisis manager has.
Next q lines contain the queries of the crisis manager. Each query looks like type x y, where <image>. If type = 1 or type = 2, then the query represents the decision of a crisis manager about merging departments of the first and second types respectively. If type = 3, then your task is to determine whether employees x and y work at the same department. Note that x can be equal to y in the query of any type.
Output
For each question of type 3 print "YES" or "NO" (without the quotes), depending on whether the corresponding people work in the same department.
Examples
Input
8 6
3 2 5
1 2 5
3 2 5
2 4 7
2 1 2
3 1 7
Output
NO
YES
YES
Submitted Solution:
```
dico = dict()
def union(a, b):
ra = find(a)
rb = find(b)
if ra != rb:
dico[x] = rb
def find(x):
if x not in dico:
return x
else:
return find(dico[x])
def unionList(x, y):
for i in range(x, y):
union(i, i+1)
n, q = map(int, input().split(' '))
for i in range(0, q):
typeQuery, x, y = map(int, input().split(' '))
if typeQuery == 3:
if find(x) == find(y):
print("YES")
else:
print("NO")
else:
if(typeQuery == 1):
union(x, y)
else:
if(typeQuery == 2):
unionList(x, y)
``` | instruction | 0 | 82,977 | 14 | 165,954 |
No | output | 1 | 82,977 | 14 | 165,955 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,994 | 14 | 165,988 |
Tags: combinatorics, math
Correct Solution:
```
def fact(a):
ans = 1
for i in range(2, a + 1):
ans *= i
return ans
n = int(input())
ans = 0
for i in range(5, 8):
ans += fact(n) // fact(i) // fact(n - i)
print(ans)
``` | output | 1 | 82,994 | 14 | 165,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,995 | 14 | 165,990 |
Tags: combinatorics, math
Correct Solution:
```
from math import factorial
n = int(input())
a = n * (n - 1) * (n - 2) * (n - 3) * (n - 4)
ans = a // factorial(5)
a *= (n - 5)
ans += a // factorial(6)
a *= (n - 6)
ans += a // factorial(7)
print(ans)
``` | output | 1 | 82,995 | 14 | 165,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,996 | 14 | 165,992 |
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
def fact(k):
if k < 2:
return 1
else:
return int(k * fact(k - 1))
def nb(k):
result = int(1)
f = fact(k)
for i in range(k):
result *= int(n - i)
result /= f
return int(result)
result = 0
for i in range(5, 8):
result += nb(i)
print(int(result))
``` | output | 1 | 82,996 | 14 | 165,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,997 | 14 | 165,994 |
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
dp = [[0 for i in range(n+1)] for i in range(n+1)]
dp[0][0] = 1
dp[1][0] = 1
dp[1][1] = 1
for i in range(1,n+1):
for j in range(0,i+1):
if j == 0:
dp[i][0] = 1
dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
# print(*dp)
# print(dp)
print(dp[n][5]+dp[n][6]+dp[n][7])
``` | output | 1 | 82,997 | 14 | 165,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,998 | 14 | 165,996 |
Tags: combinatorics, math
Correct Solution:
```
n = int(input())
c5 = 1;
c6 = 1;
c7 = 1;
for i in range(n - 5 + 1, n + 1):
c5 *= i;
c5 //= (2 * 3 * 4 * 5)
for i in range(n - 6 + 1, n + 1):
c6 *= i;
c6 //= (2 * 3 * 4 * 5 * 6)
for i in range(n - 7 + 1, n + 1):
c7 *= i;
c7 //= (2 * 3 * 4 * 5 * 6 * 7)
print(c5 + c6 + c7)
``` | output | 1 | 82,998 | 14 | 165,997 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 82,999 | 14 | 165,998 |
Tags: combinatorics, math
Correct Solution:
```
while True:
try:
n = int(input())
print(n * (n - 1) * (n - 2) * (n - 3) * (n - 4) // 120
+ n * (n - 1) * (n - 2) * (n - 3) * (n - 4) * (n - 5) // 720
+ n * (n - 1) * (n - 2) * (n - 3) * (n - 4) * (n - 5) * (n - 6) // 5040)
except:
break
``` | output | 1 | 82,999 | 14 | 165,999 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 83,000 | 14 | 166,000 |
Tags: combinatorics, math
Correct Solution:
```
from math import factorial as f
gh=lambda x,y:f(x)//(f(x-y)*f(y))
a=int(input())
print(gh(a,5)+gh(a,6)+gh(a,7))
``` | output | 1 | 83,000 | 14 | 166,001 |
Provide tags and a correct Python 3 solution for this coding contest problem.
One company of IT City decided to create a group of innovative developments consisting from 5 to 7 people and hire new employees for it. After placing an advertisment the company received n resumes. Now the HR department has to evaluate each possible group composition and select one of them. Your task is to count the number of variants of group composition to evaluate.
Input
The only line of the input contains one integer n (7 ≤ n ≤ 777) — the number of potential employees that sent resumes.
Output
Output one integer — the number of different variants of group composition.
Examples
Input
7
Output
29 | instruction | 0 | 83,001 | 14 | 166,002 |
Tags: combinatorics, math
Correct Solution:
```
p = [1] * 800;
for i in range(1, 800):
p[i] = i * p[i - 1];
n = int(input());
print(p[n] // (p[7] * p[n - 7]) + p[n] // (p[6] * p[n - 6]) + p[n] // (p[5] * p[n - 5]));
``` | output | 1 | 83,001 | 14 | 166,003 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,693 | 14 | 167,386 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
n,d=map(int,input().split())
arr=list(map(int,input().split()))
#arr.sort()
if n<3:
print(0)
else:
i=0
j=2
count=0
while i<len(arr):
while (j<len(arr) and (arr[j]-arr[i])<=d):
j+=1
count+=((j-i-1)*(j-i-2))//2
i+=1
print(count)
``` | output | 1 | 83,693 | 14 | 167,387 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,694 | 14 | 167,388 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
import math
import sys
import collections
import bisect
import string
import time
def get_ints():return map(int, sys.stdin.readline().strip().split())
def get_list():return list(map(int, sys.stdin.readline().strip().split()))
def get_string():return sys.stdin.readline().strip()
for t in range(1):
n,d=get_ints()
arr=get_list()
ans=0
for i in range(n-2):
starting=arr[i]
start_point=i
maxim=starting+d
extreme_point=bisect.bisect_right(arr,maxim)
end_point=extreme_point-1
gap=end_point-start_point
ans+=(gap*(gap-1)//2)
print(ans)
``` | output | 1 | 83,694 | 14 | 167,389 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,695 | 14 | 167,390 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
######### ## ## ## #### ##### ## # ## # ##
# # # # # # # # # # # # # # # # # # #
# # # # ### # # # # # # # # # # # #
# ##### # # # # ### # # # # # # # # #####
# # # # # # # # # # # # # # # # # #
######### # # # # ##### # ##### # ## # ## # #
"""
PPPPPPP RRRRRRR OOOO VV VV EEEEEEEEEE
PPPPPPPP RRRRRRRR OOOOOO VV VV EE
PPPPPPPPP RRRRRRRRR OOOOOOOO VV VV EE
PPPPPPPP RRRRRRRR OOOOOOOO VV VV EEEEEE
PPPPPPP RRRRRRR OOOOOOOO VV VV EEEEEEE
PP RRRR OOOOOOOO VV VV EEEEEE
PP RR RR OOOOOOOO VV VV EE
PP RR RR OOOOOO VV VV EE
PP RR RR OOOO VVVV EEEEEEEEEE
"""
"""
Perfection is achieved not when there is nothing more to add, but rather when there is nothing more to take away.
"""
import sys
input = sys.stdin.readline
read = lambda: map(int, input().split())
read_float = lambda: map(float, input().split())
# from bisect import bisect_left as lower_bound;
# from bisect import bisect_right as upper_bound;
# from math import ceil, factorial;
def ceil(x):
if x != int(x):
x = int(x) + 1
return x
def factorial(x, m):
val = 1
while x>0:
val = (val * x) % m
x -= 1
return val
def fact(x):
val = 1
while x > 0:
val *= x
x -= 1
return val
# swap_array function
def swaparr(arr, a,b):
temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
## gcd function
def gcd(a,b):
if b == 0:
return a;
return gcd(b, a % b);
## lcm function
def lcm(a, b):
return (a * b) // math.gcd(a, b)
## nCr function efficient using Binomial Cofficient
def nCr(n, k):
if k > n:
return 0
if(k > n - k):
k = n - k
res = 1
for i in range(k):
res = res * (n - i)
res = res / (i + 1)
return int(res)
## upper bound function code -- such that e in a[:i] e < x;
## prime factorization
def primefs(n):
## if n == 1 ## calculating primes
primes = {}
while(n%2 == 0 and n > 0):
primes[2] = primes.get(2, 0) + 1
n = n//2
for i in range(3, int(n**0.5)+2, 2):
while(n%i == 0 and n > 0):
primes[i] = primes.get(i, 0) + 1
n = n//i
if n > 2:
primes[n] = primes.get(n, 0) + 1
## prime factoriazation of n is stored in dictionary
## primes and can be accesed. O(sqrt n)
return primes
## MODULAR EXPONENTIATION FUNCTION
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
## DISJOINT SET UNINON FUNCTIONS
def swap(a,b):
temp = a
a = b
b = temp
return a,b;
# find function with path compression included (recursive)
# def find(x, link):
# if link[x] == x:
# return x
# link[x] = find(link[x], link);
# return link[x];
# find function with path compression (ITERATIVE)
def find(x, link):
p = x;
while( p != link[p]):
p = link[p];
while( x != p):
nex = link[x];
link[x] = p;
x = nex;
return p;
# the union function which makes union(x,y)
# of two nodes x and y
def union(x, y, link, size):
x = find(x, link)
y = find(y, link)
if size[x] < size[y]:
x,y = swap(x,y)
if x != y:
size[x] += size[y]
link[y] = x
## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES
def sieve(n):
prime = [True for i in range(n+1)]
prime[0], prime[1] = False, False
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
# Euler's Toitent Function phi
def phi(n) :
result = n
p = 2
while(p * p<= n) :
if (n % p == 0) :
while (n % p == 0) :
n = n // p
result = result * (1.0 - (1.0 / (float) (p)))
p = p + 1
if (n > 1) :
result = result * (1.0 - (1.0 / (float)(n)))
return (int)(result)
def is_prime(n):
if n == 0:
return False
if n == 1:
return True
for i in range(2, int(n ** (1 / 2)) + 1):
if not n % i:
return False
return True
#### PRIME FACTORIZATION IN O(log n) using Sieve ####
MAXN = int(1e5 + 5)
def spf_sieve():
spf[1] = 1;
for i in range(2, MAXN):
spf[i] = i;
for i in range(4, MAXN, 2):
spf[i] = 2;
for i in range(3, ceil(MAXN ** 0.5), 2):
if spf[i] == i:
for j in range(i*i, MAXN, i):
if spf[j] == j:
spf[j] = i;
## function for storing smallest prime factors (spf) in the array
################## un-comment below 2 lines when using factorization #################
spf = [0 for i in range(MAXN)]
# spf_sieve();
def factoriazation(x):
res = []
for i in range(2, int(x ** 0.5) + 1):
while x % i == 0:
res.append(i)
x //= i
if x != 1:
res.append(x)
return res
## this function is useful for multiple queries only, o/w use
## primefs function above. complexity O(log n)
def factors(n):
res = []
for i in range(1, int(n ** 0.5) + 1):
if n % i == 0:
res.append(i)
res.append(n // i)
return list(set(res))
## taking integer array input
def int_array():
return list(map(int, input().strip().split()));
def float_array():
return list(map(float, input().strip().split()));
## taking string array input
def str_array():
return input().strip().split();
def binary_search(low, high, w, h, n):
while low < high:
mid = low + (high - low) // 2
# print(low, mid, high)
if check(mid, w, h, n):
low = mid + 1
else:
high = mid
return low
## for checking any conditions
def check(councils, a, k):
summ = 0
for x in a:
summ += min(x, councils)
return summ // councils >= k
#defining a couple constants
MOD = int(1e9)+7;
CMOD = 998244353;
INF = float('inf'); NINF = -float('inf');
################### ---------------- TEMPLATE ENDS HERE ---------------- ###################
from itertools import permutations
import math
import bisect as bis
import random
import sys
def solve():
n, d = read()
coordinates = list(read())
m = {}
s = 0
for i in range(n - 2):
a = bis.bisect_right(coordinates, coordinates[i] + d) - i - 2
s += a * (a + 1) // 2
print(s)
if __name__ == '__main__':
for _ in range(1):
solve()
# fin_time = datetime.now()
# print("Execution time (for loop): ", (fin_time-init_time))
``` | output | 1 | 83,695 | 14 | 167,391 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,696 | 14 | 167,392 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
# Upsolve from Dukkha
n, d = map(int, input().split())
x = list(map(int, input().split()))
output = 0
j = 0
for i in range(n):
while j < n and x[j] - x[i] <= d:
j += 1
k = j - i - 1
output += (k/2)*(k-1)
print(int(output))
``` | output | 1 | 83,696 | 14 | 167,393 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,697 | 14 | 167,394 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
import math
import random
from queue import Queue
import time
def main(arr,d):
ans=0
for i in range(len(arr)):
start=i
end=len(arr)-1
mid=(start+end)//2
best_val=mid
while start<=end:
mid=(start+end)//2
if arr[mid]-arr[i]==d:
best_val=mid
break
elif arr[mid]-arr[i]>d:
end=mid-1
best_val=end
else:
start=mid+1
best_val=mid
ans+=(best_val-i-1)*(best_val-i)//2
return ans
n,d=list(map(int,input().split()))
print(main(list(map(int,input().split())),d))
``` | output | 1 | 83,697 | 14 | 167,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,698 | 14 | 167,396 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
import sys
import string
import math
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
from fractions import Fraction
def mi(s):
return map(int, s.strip().split())
def lmi(s):
return list(mi(s))
def tmi(s):
return tuple(mi(s))
def mf(f, s):
return map(f, s)
def lmf(f, s):
return list(mf(f, s))
def js(lst):
return " ".join(str(d) for d in lst)
def jsns(lst):
return "".join(str(d) for d in lst)
def line():
return sys.stdin.readline().strip()
def linesp():
return line().split()
def iline():
return int(line())
def mat(n):
matr = []
for _ in range(n):
matr.append(linesp())
return matr
def matns(n):
mat = []
for _ in range(n):
mat.append([c for c in line()])
return mat
def mati(n):
mat = []
for _ in range(n):
mat.append(lmi(line()))
return mat
def pmat(mat):
for row in mat:
print(js(row))
def main():
_, d = mi(line())
arr = lmi(line())
begin = 0
ans = 0
for e, n in enumerate(arr):
while n - arr[begin] > d:
begin += 1
# If n is the largest element of the pairs,
# then what is the best we can do?
elems = e - begin + 1
if elems < 3:
continue
else:
ans += (elems - 1) * (elems - 2) // 2
print(ans)
main()
``` | output | 1 | 83,698 | 14 | 167,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
Note that the order of the points inside the group of three chosen points doesn't matter.
Input
The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
It is guaranteed that the coordinates of the points in the input strictly increase.
Output
Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
4 3
1 2 3 4
Output
4
Input
4 2
-3 -2 -1 0
Output
2
Input
5 19
1 10 20 30 50
Output
1
Note
In the first sample any group of three points meets our conditions.
In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
In the third sample only one group does: {1, 10, 20}. | instruction | 0 | 83,699 | 14 | 167,398 |
Tags: binary search, combinatorics, two pointers
Correct Solution:
```
# Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. Now Petya is wondering in how many ways he can choose three distinct points so that the distance between the two farthest of them doesn't exceed d.
# Note that the order of the points inside the group of three chosen points doesn't matter.
# Input
# The first line contains two integers: n and d (1 ≤ n ≤ 105; 1 ≤ d ≤ 109). The next line contains n integers x1, x2, ..., xn, their absolute value doesn't exceed 109 — the x-coordinates of the points that Petya has got.
# It is guaranteed that the coordinates of the points in the input strictly increase.
# Output
# Print a single integer — the number of groups of three points, where the distance between two farthest points doesn't exceed d.
# Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
# Examples
# inputCopy
# 4 3
# 1 2 3 4
# outputCopy
# 4
# inputCopy
# 4 2
# -3 -2 -1 0
# outputCopy
# 2
# inputCopy
# 5 19
# 1 10 20 30 50
# outputCopy
# 1
# Note
# In the first sample any group of three points meets our conditions.
# In the seconds sample only 2 groups of three points meet our conditions: {-3, -2, -1} and {-2, -1, 0}.
# In the third sample only one group does: {1, 10, 20}.
# ***************Solution Approach*****************
# Let's select the rightmost point of our triplet. In order to do this we can iterate over all points in ascending order of their X-coordinate. At the same time we'll maintain a pointer to the leftmost point which lays on the distance not greater than d from the current rightmost point. We can easily find out the number of points in the segment between two pointers, excluding the rightmost point. Let's call this number k. Then there exist exactly k * (k - 1) / 2 triplets of points with the fixed rightmost point. The only thing left is to sum up these values for all rightmost points.
n, k = map(int, input().split())
list1 = [int(x) for x in input().split()]
flag = False
if n<3:
print(0)
else:
list1.sort()
i =0
j = 2
total = 0
while j<len(list1):
while i<=j and list1[j]- list1[i]>k:
i+=1
choices = j-i
total+=((choices)*(choices-1))//2
j+=1
print(total)
``` | output | 1 | 83,699 | 14 | 167,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alexandra has a paper strip with n numbers on it. Let's call them ai from left to right.
Now Alexandra wants to split it into some pieces (possibly 1). For each piece of strip, it must satisfy:
* Each piece should contain at least l numbers.
* The difference between the maximal and the minimal number on the piece should be at most s.
Please help Alexandra to find the minimal number of pieces meeting the condition above.
Input
The first line contains three space-separated integers n, s, l (1 ≤ n ≤ 105, 0 ≤ s ≤ 109, 1 ≤ l ≤ 105).
The second line contains n integers ai separated by spaces ( - 109 ≤ ai ≤ 109).
Output
Output the minimal number of strip pieces.
If there are no ways to split the strip, output -1.
Examples
Input
7 2 2
1 3 1 2 4 1 2
Output
3
Input
7 2 2
1 100 1 100 1 100 1
Output
-1
Note
For the first sample, we can split the strip into 3 pieces: [1, 3, 1], [2, 4], [1, 2].
For the second sample, we can't let 1 and 100 be on the same piece, so no solution exists. | instruction | 0 | 83,780 | 14 | 167,560 |
Tags: binary search, data structures, dp, two pointers
Correct Solution:
```
def split(a,n,s,l):
pieces = []
i = 1
tmpmin = a[0]
tmpmax = a[0]
tmppc = [a[0]]
while i<n:
if abs(a[i]-tmpmin)<=s and abs(a[i]-tmpmax)<=s:
tmppc.append(a[i])
if a[i]<tmpmin: tmpmin=a[i]
elif a[i]>tmpmax: tmpmax = a[i]
else:
pieces.append(tmppc)
tmppc = [a[i]]
tmpmin = a[i]
tmpmax = a[i]
i += 1
pieces.append(tmppc)
fail = False
for j in range(len(pieces)):
if len(pieces[j])<l:
if j>0:
prevpc = pieces[j-1]
minj = min(pieces[j])
maxj = max(pieces[j])
while len(pieces[j])<l:
tmp = prevpc.pop()
if abs(tmp-minj)<=s and abs(tmp-maxj)<=s:
pieces[j].insert(0,tmp)
if tmp<minj: minj=tmp
elif tmp>maxj: maxj=tmp
else:
return -1
if len(prevpc)<l:
return -1
else:
return -1
return len(pieces)
n,s,l = [int(s) for s in input().split()]
a = [int(s) for s in input().split()]
res = split(a,n,s,l)
if res<0:
a.reverse()
res = split(a,n,s,l)
print(res)
``` | output | 1 | 83,780 | 14 | 167,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,784 | 14 | 167,568 |
Tags: flows
Correct Solution:
```
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
if e[0] not in self.graph:
self.graph[e[0]] = []
if e[1] not in self.graph:
self.graph[e[1]] = []
#to #cap #reveser edge
self.graph[e[0]].append([e[1], e[2], len(self.graph[e[1]])])
self.graph[e[1]].append([e[0], 0, len(self.graph[e[0]])-1])
self.N = len(self.graph.keys())
def bfs(self):
self.dist = {}
self.dist[self.s] = 0
self.curIter = {node:[] for node in self.graph}
Q = deque([self.s])
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
# Chỉ add vào các node kế tiếp nếu dung lượng cạnh > 0 và chưa được visit trước đấy
if e[1] > 0 and e[0] not in self.dist:
self.dist[e[0]] = self.dist[cur] + 1
# add vào danh sách node kế tiếp của node hiện tại
self.curIter[cur].append(index)
Q.append(e[0])
def findPath(self, cur, f):
if cur == self.t:
return f
while len(self.curIter[cur]) > 0:
indexEdge = self.curIter[cur][-1]
nextNode = self.graph[cur][indexEdge][0]
remainCap = self.graph[cur][indexEdge][1]
indexPreEdge = self.graph[cur][indexEdge][2]
if remainCap > 0 and self.dist[nextNode] > self.dist[cur]:
#self.next[cur] = indexEdge
flow = self.findPath(nextNode, min(f, remainCap))
if flow > 0:
self.path.append(cur)
self.graph[cur][indexEdge][1] -= flow
self.graph[nextNode][indexPreEdge][1] += flow
#if cur == self.s:
# print(self.path, flow)
return flow
#else:
#self.path.pop()
self.curIter[cur].pop()
return 0
def maxFlow(self):
maxflow = 0
flow = []
while(True):
self.bfs()
if self.t not in self.dist:
break
while(True):
self.path = []
f = self.findPath(self.s, self.maxCap)
#print('iter', self.curIter)
if f == 0:
break
flow.append(f)
maxflow += f
return maxflow
# Tìm tập node thuộc S và T
# sau khi đã tìm được max flow
def residualBfs(self):
Q = deque([self.s])
side = {self.s:'s'}
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
if e[1] > 0 and e[0] not in side:
Q.append(e[0])
side[e[0]] = 's'
S = []
T = []
for x in self.graph:
if x in side:
S.append(x)
else:
T.append(x)
return set(S), set(T)
def push(G, u, v):
if u not in G:
G[u]=[]
if v not in G:
G[v]=[]
G[u].append(v)
G[v].append(u)
def bfs(u, used, G):
l, r = G[u][0], G[u][1]
used[u]=1
used[l]=1
used[r]=1
S=[l,u,r]
i=2
while i < len(S):
cur=S[i]
if cur in G:
for v in G[cur]:
if used[v]==0:
used[v]=1
S.append(v)
i+=1
return S
max_ = 20001
prime = [1] * max_
for i in range(2, max_):
if prime[i] == 1:
for j in range(2*i, max_, i):
prime[j] = 0
n = int(input())
a = list(map(int, input().split()))
diff = 0
for x in a:
if x%2==0:
diff+=1
else:
diff-=1
flg=True
if diff != 0:
flg=False
else:
edge = []
for i in range(n):
if a[i]%2==1:
edge.append([i,'t', 2])
continue
edge.append(['s', i, 2])
for j in range(n):
if a[j]%2==1 and prime[a[i]+a[j]] == 1:
edge.append([i, j, 1])
g = Dinic(edge, 's', 't')
F = g.maxFlow()
if F != n:
flg=False
else:
G = {}
for u, es in g.graph.items():
if u in ['s', 't'] or a[u] % 2 == 1:
continue
for e in es:
v, remain = e[0], e[1]
if isinstance(v, int) == True and remain == 0:
push(G, u, v)
used = [0]*n
comp = []
for i in range(n):
if a[i]%2==0 and used[i]==0:
comp.append(bfs(i, used, G))
if flg==False:
print('Impossible')
else:
print(len(comp))
for nodes in comp:
for i in range(len(nodes)):
nodes[i] += 1
arr = [len(nodes)] + nodes
print(' '.join([str(x) for x in arr]))
``` | output | 1 | 83,784 | 14 | 167,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,785 | 14 | 167,570 |
Tags: flows
Correct Solution:
```
N = int(input())
L = list(map(int, input().split(' ')))
def isPrime(x) :
for i in range(2, int(x**0.5)+2) :
if x % i == 0 : return False
return True
odd = []
even = []
for i in range(N) :
if L[i]%2 == 0 :
even.append(i)
else :
odd.append(i)
if len(odd) != len(even) :
print("Impossible")
exit()
cap = [[0]*(N+2) for i in range(N+2)]
for i in odd :
cap[N][i] = 2
for i in even :
cap[i][N+1] = 2
for i in odd :
for j in even :
if isPrime(L[i]+L[j]) :
cap[i][j] = 1
def send(x, flow) :
global visited, N
if x == N+1 or flow == 0: return flow
visited[x] = True
ret = 0
for nxt in range(N+2) :
if visited[nxt] : continue
if cap[x][nxt] == 0 : continue
n_flow = min(cap[x][nxt], flow)
n_flow = send(nxt, n_flow)
flow -= n_flow
ret += n_flow
cap[x][nxt] -= n_flow
cap[nxt][x] += n_flow
return ret
flow = 0
while True :
visited = [False]*(N+2)
f = send(N, N)
if f == 0 : break
flow += f
if flow != N :
print("Impossible")
exit()
def dfs(x, path) :
global visited, N, edge
visited[x] = True
ret = 1
path.append(x)
for nxt in edge[x] :
if visited[nxt] : continue
ret += dfs(nxt, path)
return ret
visited = [False]*N
edge = [[] for i in range(N)]
for i in odd :
for j in even :
if cap[j][i] == 1 :
edge[i].append(j)
edge[j].append(i)
cnt = []
ans = []
for i in range(N) :
if visited[i] == True : continue
ans.append([])
cnt.append(dfs(i, ans[-1]))
print(len(cnt))
for i in range(len(cnt)) :
print(cnt[i], end = ' ')
for j in ans[i] :
print(j+1, end = ' ')
print()
``` | output | 1 | 83,785 | 14 | 167,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,786 | 14 | 167,572 |
Tags: flows
Correct Solution:
```
#E
def main():
sieve = [False, True] * 10001
for i in range(3, 140, 2):
if sieve[i]:
j, k = i * 2, i * i
le = (20001 - k) // j + 1
sieve[k::j] = [False] * le
n = int(input())
aa = list(map(int, input().split()))
pp = [-1] * n
def dget(v):
if dsu[v]!=v:
dsu[v] = dget(dsu[v])
return dsu[v]
def dfs(v):
if free[v]:
free[v], a, pv = False, aa[v], pp[v]
for i, p in enumerate(pp):
if sieve[a + aa[i]] and pv != i and (p == -1 or dfs(p)):
pp[i] = v
return True
return False
for i in range(n):
free = [True] * n
if not dfs(i):
print('Impossible')
return
dsu = list(range(n))
for i, p in enumerate(pp):
i, p = dget(i), dget(p)
dsu[p] = i
print(sum(dget(i)==i for i in range(n)))
for i in range(n):
if dget(i) == i:
row = [sum(dget(j) == i for j in range(n)), i + 1]
j = pp[i]
while j != i:
row.append(j + 1)
j = pp[j]
print(*row)
main()
``` | output | 1 | 83,786 | 14 | 167,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,787 | 14 | 167,574 |
Tags: flows
Correct Solution:
```
import math
def ip(x):
for i in range(2,1 + int(math.sqrt(x))):
if not x % i:
return False
return True
def add(x, y, z):
cap[x][y] = z
def send(x, flow):
if x == n + 1:
return flow
if vis[x]:
return 0
vis[x] = 1
ret = 0
for i in range(n + 2):
if cap[x][i]:
tmp = send(i, min(cap[x][i], flow))
ret += tmp
cap[x][i] -= tmp
cap[i][x] += tmp
flow -= tmp
if not flow:
return ret
return ret
def flow():
global vis
ret = 0
while(True):
vis = [0 for i in range(n + 2)]
tmp = send(n, n)
ret += tmp
if not tmp:
break
return ret
n = int(input())
a = [int(x) for x in input().split()]
odd = [1 if x % 2 else 0 for x in a]
even = [0 if x % 2 else 1 for x in a]
cap = [[0 for i in range(n+2)] for j in range(n+2)]
w = [[0 for i in range(n+2)] for j in range(n+2)]
if sum(odd) - sum(even):
print("Impossible")
exit()
for i in range(n):
if odd[i]:
add(n, i, 2)
for j in range(n):
if ip(a[i] + a[j]):
add(i, j, 1)
else:
add(i, n + 1, 2)
if flow() == n:
for i in range(n):
for j in range(n):
if odd[i] and cap[j][i]:
w[i][j] = 1
w[j][i] = 1
ans = []
vis = [0 for i in range(n)]
for i in range(n):
if not vis[i]:
cur = i
ans.append([])
while not vis[cur]:
ans[-1].append(cur + 1)
vis[cur] = 1
for j in range(n):
if w[cur][j] and not vis[j]:
cur = j
break
print(len(ans))
for x in ans:
print("%d %s" % (len(x), " ".join([str(_) for _ in x])))
else:
print("Impossible")
``` | output | 1 | 83,787 | 14 | 167,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,788 | 14 | 167,576 |
Tags: flows
Correct Solution:
```
def main():
sieve = [False, True] * 10001
for i in range(3, 140, 2):
if sieve[i]:
j, k = i * 2, i * i
le = (20001 - k) // j + 1
sieve[k::j] = [False] * le
n = int(input())
aa = list(map(int, input().split()))
pp = [-1] * n
def dsu_get(v):
if dsu[v] != v:
dsu[v] = dsu_get(dsu[v])
return dsu[v]
def dfs(v):
if free[v]:
free[v], a, pv = False, aa[v], pp[v]
for i, p in enumerate(pp):
if sieve[a + aa[i]] and pv != i and (p == -1 or dfs(p)):
pp[i] = v
return True
return False
for i in range(n):
free = [True] * n
if not dfs(i):
print('Impossible')
return
dsu = list(range(n))
for i, p in enumerate(pp):
i, p = dsu_get(i), dsu_get(p)
dsu[p] = i
print(sum(dsu_get(i) == i for i in range(n)))
for i in range(n):
if dsu_get(i) == i:
row = [sum(dsu_get(j) == i for j in range(n)), i + 1]
j = pp[i]
while j != i:
row.append(j + 1)
j = pp[j]
print(*row)
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | output | 1 | 83,788 | 14 | 167,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number. | instruction | 0 | 83,789 | 14 | 167,578 |
Tags: flows
Correct Solution:
```
def main():
sieve = [False, True] * 10001
for i in range(3, 140, 2):
if sieve[i]:
j, k = i * 2, i * i
le = (20001 - k) // j + 1
sieve[k::j] = [False] * le
n = int(input())
aa = list(map(int, input().split()))
pp = [-1] * n
def dsu_get(v):
if dsu[v] != v:
dsu[v] = dsu_get(dsu[v])
return dsu[v]
def dfs(v):
if free[v]:
free[v], a, pv = False, aa[v], pp[v]
for i, p in enumerate(pp):
if sieve[a + aa[i]] and pv != i and (p == -1 or dfs(p)):
pp[i] = v
return True
return False
for i in range(n):
free = [True] * n
if not dfs(i):
print('Impossible')
return
dsu = list(range(n))
for i, p in enumerate(pp):
i, p = dsu_get(i), dsu_get(p)
dsu[p] = i
print(sum(dsu_get(i) == i for i in range(n)))
for i in range(n):
if dsu_get(i) == i:
row = [sum(dsu_get(j) == i for j in range(n)), i + 1]
j = pp[i]
while j != i:
row.append(j + 1)
j = pp[j]
print(*row)
if __name__ == '__main__':
main()
``` | output | 1 | 83,789 | 14 | 167,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number.
Submitted Solution:
```
from collections import deque
class Dinic():
def __init__(self, listEdge, s, t):
self.s = s
self.t = t
self.graph = {}
self.maxCap = 1000000
# dict các node lân cận
# e[0]: from, e[1]: to, e[2]: dung luong
for e in listEdge:
if e[0] not in self.graph:
self.graph[e[0]] = []
if e[1] not in self.graph:
self.graph[e[1]] = []
#to #cap #reveser edge
self.graph[e[0]].append([e[1], e[2], len(self.graph[e[1]])])
self.graph[e[1]].append([e[0], 0, len(self.graph[e[0]])-1])
self.N = len(self.graph.keys())
def bfs(self):
self.dist = {}
self.dist[self.s] = 0
self.curIter = {node:[] for node in self.graph}
Q = deque([self.s])
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
# Chỉ add vào các node kế tiếp nếu dung lượng cạnh > 0 và chưa được visit trước đấy
if e[1] > 0 and e[0] not in self.dist:
self.dist[e[0]] = self.dist[cur] + 1
# add vào danh sách node kế tiếp của node hiện tại
self.curIter[cur].append(index)
Q.append(e[0])
def findPath(self, cur, f):
if cur == self.t:
return f
while len(self.curIter[cur]) > 0:
indexEdge = self.curIter[cur][-1]
nextNode = self.graph[cur][indexEdge][0]
remainCap = self.graph[cur][indexEdge][1]
indexPreEdge = self.graph[cur][indexEdge][2]
if remainCap > 0 and self.dist[nextNode] > self.dist[cur]:
#self.next[cur] = indexEdge
flow = self.findPath(nextNode, min(f, remainCap))
if flow > 0:
self.path.append(cur)
self.graph[cur][indexEdge][1] -= flow
self.graph[nextNode][indexPreEdge][1] += flow
#if cur == self.s:
# print(self.path, flow)
return flow
#else:
#self.path.pop()
self.curIter[cur].pop()
return 0
def maxFlow(self):
maxflow = 0
flow = []
while(True):
self.bfs()
if self.t not in self.dist:
break
while(True):
self.path = []
f = self.findPath(self.s, self.maxCap)
#print('iter', self.curIter)
if f == 0:
break
flow.append(f)
maxflow += f
return maxflow
# Tìm tập node thuộc S và T
# sau khi đã tìm được max flow
def residualBfs(self):
Q = deque([self.s])
side = {self.s:'s'}
while(len(Q) > 0):
cur = Q.popleft()
for index,e in enumerate(self.graph[cur]):
if e[1] > 0 and e[0] not in side:
Q.append(e[0])
side[e[0]] = 's'
S = []
T = []
for x in self.graph:
if x in side:
S.append(x)
else:
T.append(x)
return set(S), set(T)
def push(G, u, v):
if u not in G:
G[u]=[]
if v not in G:
G[v]=[]
G[u].append(v)
G[v].append(u)
def bfs(u, used, G):
l, r = G[u][0], G[u][1]
used[u]=1
used[l]=1
used[r]=1
S=[l,u,r]
i=2
while i < len(S):
cur=S[i]
if cur in G:
for v in G[cur]:
if used[v]==0:
used[v]=1
S.append(v)
i+=1
return S
max_ = 20001
prime = [1] * max_
for i in range(2, max_):
if prime[i] == 1:
for j in range(2*i, max_, i):
prime[j] = 0
n = int(input())
a = list(map(int, input().split()))
diff = 0
for x in a:
if x%2==0:
diff+=1
else:
diff-=1
flg=True
if diff != 0:
flg=False
else:
edge = []
for i in range(n):
if a[i]%2==1:
edge.append([i,'t', 2])
continue
edge.append(['s', i, 2])
for j in range(n):
if a[j]%2==1 and prime[a[i]+a[j]] == 1:
edge.append([i, j, 1])
g = Dinic(edge, 's', 't')
F = g.maxFlow()
if F != n:
flg=False
else:
G = {}
for u, es in g.graph.items():
if u in ['s', 't'] or a[u] % 2 == 1:
continue
for e in es:
v, remain = e[0], e[1]
if isinstance(v, int) == True and remain == 0:
push(G, u, v)
used = [0]*n
comp = []
for i in range(0, n, 2):
if a[i]%2==0 and used[i]==0:
comp.append(bfs(i, used, G))
if flg==False:
print('Impossible')
else:
print(len(comp))
for nodes in comp:
for i in range(len(nodes)):
nodes[i] += 1
arr = [len(nodes)] + nodes
print(' '.join([str(x) for x in arr]))
``` | instruction | 0 | 83,790 | 14 | 167,580 |
No | output | 1 | 83,790 | 14 | 167,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is participating in a party in Prime Kingdom. There are n foxes there (include Fox Ciel). The i-th fox is ai years old.
They will have dinner around some round tables. You want to distribute foxes such that:
1. Each fox is sitting at some table.
2. Each table has at least 3 foxes sitting around it.
3. The sum of ages of any two adjacent foxes around each table should be a prime number.
If k foxes f1, f2, ..., fk are sitting around table in clockwise order, then for 1 ≤ i ≤ k - 1: fi and fi + 1 are adjacent, and f1 and fk are also adjacent.
If it is possible to distribute the foxes in the desired manner, find out a way to do that.
Input
The first line contains single integer n (3 ≤ n ≤ 200): the number of foxes in this party.
The second line contains n integers ai (2 ≤ ai ≤ 104).
Output
If it is impossible to do this, output "Impossible".
Otherwise, in the first line output an integer m (<image>): the number of tables.
Then output m lines, each line should start with an integer k -=– the number of foxes around that table, and then k numbers — indices of fox sitting around that table in clockwise order.
If there are several possible arrangements, output any of them.
Examples
Input
4
3 4 8 9
Output
1
4 1 2 4 3
Input
5
2 2 2 2 2
Output
Impossible
Input
12
2 3 4 5 6 7 8 9 10 11 12 13
Output
1
12 1 2 3 6 5 12 9 8 7 10 11 4
Input
24
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Output
3
6 1 2 3 6 5 4
10 7 8 9 12 15 14 13 16 11 10
8 17 18 23 22 19 20 21 24
Note
In example 1, they can sit around one table, their ages are: 3-8-9-4, adjacent sums are: 11, 17, 13 and 7, all those integers are primes.
In example 2, it is not possible: the sum of 2+2 = 4 is not a prime number.
Submitted Solution:
```
import math
def prost(x):
for i in range(2, int(math.sqrt(x))+1):
if x % i == 0:
return False
return True
n = int(input())
a = input().split()
for i in range(n):
a[i] = [int(a[i]), False]
stud = []
now = 0
a[0][1] = True
dop = -1
while dop != 0:
dop = 0
for i in range(1,n):
if a[i][1] == False and prost(a[i][0] + a[now][0]):
stud.append([now, a[now][0], '+'])
a[i][1] = True
now = i
dop += 1
#break
no = []
l = 0
if dop == 0:
stud.append([now, a[now][0], '+'])
for i in range(n):
if a[i][1] == False:
no.append([i, a[i][0], False])
l += 1
if l==n-1:
print('Impossible')
elif l==0:
print(1)
print(n, end=' ')
for i in stud:
print(i[0]+1, end=' ')
else:
x = 0
new = []
ch = 0
now = no[ch]
no[ch][2] = True
while True:
for j in range(n-l-1, -1, -1):
if stud[j][2]=='+' and prost(now[1]+stud[j][1])==True:
new.append(now)
now = stud[j]
stud[j][2] = '-'
x += 1
break
for i in range(l):
if no[i][2] == False and prost(no[i][1]+now[1]):
new.append(now)
now = no[i]
no[i][2] = True
x += 1
if x>=l and x>=3 and prost(now[1] + stud[0][1]) and prost(new[0][1] + new[x-1][1]):
break
if x == n-1:
x = 0
new = []
for i in range(l):
no[i][2] = False
for j in range(n-l-1, -1, -1):
stud[j][2] = '+'
ch += 1
now = no[ch]
no[ch][2] = True
print(2)
print(x, end=' ')
for i in range(x-1, -1, -1):
print(new[i][0]+1, end=' ')
print()
print(n-x, end=' ')
for i in range(n-x):
print(stud[i][0]+1, end=' ')
``` | instruction | 0 | 83,791 | 14 | 167,582 |
No | output | 1 | 83,791 | 14 | 167,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.