text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Tags: implementation
Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
c = d = 0
for i in range(n):
add = min(8, c + a[i])
if add >= 8: c = c + a[i] - add
else: c = 0
d += add
if d >= k:
print(i + 1)
break
else:
print(-1)
```
| 9,600 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Tags: implementation
Correct Solution:
```
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
x = 0
y = 0
z = 0
b = 0
for i in a:
b += 1
x += i
if x >= 8:
y += 8
else:
y += x
x -= 8
if x<0:
x = 0
if y >= k:
z = i
break
if z == 0:
print(-1)
else:
print(b)
```
| 9,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
n, k = map(int, input().split())
m = list(map(int, input().split()))
arya = 0
sweet = 0
day = 0
ans = -1
for i in m:
day += 1
if i > 8:
sweet += 8
arya += i - 8
else:
if arya + i >= 8:
sweet += 8
arya -= (8 - i)
else:
sweet += i + arya
arya = 0
if sweet >= k:
ans = day
break
print(ans)
```
Yes
| 9,602 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
from sys import stdin, stdout
n, k = map(int, stdin.readline().split())
values = list(map(int, stdin.readline().split()))
cnt = 0
sweet = 0
for i in range(n):
cnt += values[i]
v = min(min(cnt, 8), k - sweet)
sweet += v
cnt -= v
if sweet == k:
stdout.write(str(i + 1))
break
else:
stdout.write('-1')
```
Yes
| 9,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
n,k=map(int,input().split())
l = map(int,input().split())
l=list(l)
if sum(l)<k or 8*n<k:
print(-1)
else:
s=0
t=True
i=0
d=0
while s<k :
try:
if l[i]>=8:
s+=8
d+=l[i]-8
else:
s+=l[i]+min(d,8-l[i])
d-=min(d,8-l[i])
i+=1
except IndexError:
t=False
print(-1)
break
if t:
print(i)
```
Yes
| 9,604 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
n , k = map(int,input().split())
a = [int(i) for i in input().split()][:n]
d = 0
e = 0
if k > sum(a):
print(-1)
else:
for item in a:
if item+e >= 8:
k-=8
e += (item-8)
else:
k-=item+e
e = 0
d+=1
if k <= 0:
print(d)
break
if d == n:
print(-1)
break
```
Yes
| 9,605 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
x, y = map(int, input().split(" "))
z=input()
a=[]
i=0
while i<x:
a.append(int(z.split(" ")[i]))
i=i+1
if y//x>8 or sum(a)<y or max(a)<8:
print(-1)
else:
j=0
current_sum=0
a.sort(reverse=True)
while j<x:
current_sum=8*(j+1)
if current_sum>=y:
print(j+1)
break
j=j+1
```
No
| 9,606 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
x, y = map(int, input().split(" "))
z=input()
a=[]
i=0
while i<x:
a.append(int(z.split(" ")[i]))
i=i+1
if y//x>8:
print(-1)
else:
print(x)
```
No
| 9,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
nk = list(map(int, input().split()))
a = list(map(int, input().split()))
day = 0
bank = 0
while nk[1] > 0 and day < nk[0]:
day += 1
if a[day - 1] > 8:
bank += a[day - 1] - 8
nk[1] -= 8
else:
nk[1] -= (a[day - 1] + min(bank, 8 - a[day - 1]))
bank -= min(bank, a[day - 1])
if nk[1] > 0:
print(-1)
else:
print(day)
```
No
| 9,608 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bran and his older sister Arya are from the same house. Bran like candies so much, so Arya is going to give him some Candies.
At first, Arya and Bran have 0 Candies. There are n days, at the i-th day, Arya finds ai candies in a box, that is given by the Many-Faced God. Every day she can give Bran at most 8 of her candies. If she don't give him the candies at the same day, they are saved for her and she can give them to him later.
Your task is to find the minimum number of days Arya needs to give Bran k candies before the end of the n-th day. Formally, you need to output the minimum day index to the end of which k candies will be given out (the days are indexed from 1 to n).
Print -1 if she can't give him k candies during n given days.
Input
The first line contains two integers n and k (1 ≤ n ≤ 100, 1 ≤ k ≤ 10000).
The second line contains n integers a1, a2, a3, ..., an (1 ≤ ai ≤ 100).
Output
If it is impossible for Arya to give Bran k candies within n days, print -1.
Otherwise print a single integer — the minimum number of days Arya needs to give Bran k candies before the end of the n-th day.
Examples
Input
2 3
1 2
Output
2
Input
3 17
10 10 10
Output
3
Input
1 9
10
Output
-1
Note
In the first sample, Arya can give Bran 3 candies in 2 days.
In the second sample, Arya can give Bran 17 candies in 3 days, because she can give him at most 8 candies per day.
In the third sample, Arya can't give Bran 9 candies, because she can give him at most 8 candies per day and she must give him the candies within 1 day.
Submitted Solution:
```
n, k = [int(i) for i in input().split()]
a = [int(i) for i in input().split()]
b = 0
c = 0
ans = 0
for i in range(n):
a[i] += c
if a[i] > 8:
c += (a[i] - 8)
b += 8
ans += 1
else:
b += a[i]
ans += 1
if b >= k:
print(ans)
break
if b < k and i + 1 == n:
print('-1')
```
No
| 9,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Tags: dp, probabilities, trees
Correct Solution:
```
import functools
n = int(input())
props = []
def preproc(a):
return float(a)/100.
for i in range(pow(2,n)):
props.append(list(map(preproc, input().split())))
wining_props = [] # list of lists. First index -- number of round, second -- num of team, value -- prop of wining
wining_props_first_round = []
for i in range(0, (2 ** n), 2):
# i, and i+1 teams playing
wining_prop_for_i = props[i][i + 1]
wining_props_first_round.append(wining_prop_for_i)
wining_props_first_round.append(1. - wining_prop_for_i)
wining_props.append(wining_props_first_round)
assert len(wining_props_first_round) == len(props)
for round_num in range(2, n + 1):
# calculate propabilitys for winning in i round for each team
# prop of winning in i round = prop of winning prev round + mo of win this one
# mo win this = for each team we can meet prop of them wining prev * prop we win them
# each team we can meet on round i = all teems // 2^i == we//2^i
this_round_wining_props = []
for team_num in range(2 ** n):
t = team_num // (2 ** round_num) * (2 ** (round_num))
teams_we_meet_this_round = [t + x for x in range(2 ** round_num)]
t = team_num // (2 ** (round_num-1)) * (2 ** (round_num-1))
teams_we_meet_prev_round = [t + x for x in range(2 ** (round_num-1))]
for tt in teams_we_meet_prev_round:
teams_we_meet_this_round.remove(tt)
this_team_wining_props = wining_props[round_num - 2][team_num] # -2 cause numeration
chances_win_i_team = []
for tm in teams_we_meet_this_round:
# chances we meet them * chances we win
chances_win_i_team.append(wining_props[round_num - 2][tm] * props[team_num][tm])
mo_win_this_round = sum(chances_win_i_team)
this_team_wining_props *= mo_win_this_round
this_round_wining_props.append(this_team_wining_props)
#assert 0.99 < sum(this_round_wining_props) < 1.01
wining_props.append(this_round_wining_props)
# now we got props of each win on each round. Lets bet on most propable winer and calculate revenue
#from left to right-1 is playing
@functools.lru_cache(maxsize=None)
def revenue(round_num, teams_left, teams_right, winner=-1):
split = ((teams_left + teams_right) // 2)
# let the strongest team win, we bet, and calculate to the bottom
if round_num == 1:
return wining_props[0][winner] if winner != -1 else max(wining_props[0][teams_left:teams_right])
if winner == -1:
results = []
for winner in range(teams_left, teams_right):
winner_prop = wining_props[round_num - 1][winner]
if winner >= split:
res = sum(
[revenue(round_num - 1, teams_left, split), revenue(round_num - 1, split, teams_right, winner),
winner_prop * (2 ** (round_num - 1))])
else:
res = sum(
[revenue(round_num - 1, teams_left, split, winner), revenue(round_num - 1, split, teams_right),
winner_prop * (2 ** (round_num - 1))])
results.append(res)
return max(results)
else:
winner_prop = wining_props[round_num - 1][winner]
if winner >= split:
res = sum(
[revenue(round_num - 1, teams_left, split), revenue(round_num - 1, split, teams_right, winner),
winner_prop * (2 ** (round_num - 1))])
else:
res = sum(
[revenue(round_num - 1, teams_left, split, winner), revenue(round_num - 1, split, teams_right),
winner_prop * (2 ** (round_num - 1))])
return res
print(revenue(n, 0, (2 ** n)))
```
| 9,610 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Tags: dp, probabilities, trees
Correct Solution:
```
n = int(input())
# Using the same index I would for a tree
m = 2**n
points = [0]*(2*m)
points[1] = 2**(n-1)
for i in range(1,m):
x = points[i]//2
points[2*i] = x
points[2*i+1] = x
P = [[int(x)/100.0 for x in input().split()] for _ in range(m)]
state = [[0.0]*64 for _ in range(2*m)]
for i in range(m):
state[m+i][i] = 1.0
for i in reversed(range(1,m)):
for j in range(m):
for k in range(j+1,m):
# x is probability that team j meets team k in match i
x = state[2*i][j]*state[2*i+1][k]
state[i][j] += P[j][k]*x
state[i][k] += P[k][j]*x
score = [[0]*64 for _ in range(2*m)]
for i in reversed(range(1,m)):
for j in range(m):
for k in range(m):
score[i][j] = max(score[i][j], score[2*i][j]+state[i][j]*points[i] + score[2*i+1][k])
score[i][j] = max(score[i][j], score[2*i+1][j]+state[i][j]*points[i] + score[2*i][k])
print(repr(max(score[1])))
```
| 9,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Tags: dp, probabilities, trees
Correct Solution:
```
n = int(input())
m = 1 << n
p = [list(map(int, input().split())) for i in range(m)]
u, x = [1] * m, [0] * m
v, y = u[:], x[:]
for i in range(n):
d = 1 << i
for j in range(m):
s = d * (j // d ^ 1)
v[j] = u[j] * sum(u[k] * p[j][k] for k in range(s, s + d)) / 100
y[j] = max(x[s: s + d]) + x[j] + v[j] * d
u, v, x, y = v, u, y, x
print(max(x))
```
| 9,612 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Submitted Solution:
```
n = int(input())
props = []
def preproc(a):
return float(a)/100.
for i in range(pow(2,n)):
props.append(list(map(preproc, input().split())))
wining_props = [] # list of lists. First index -- number of round, second -- num of team, value -- prop of wining
wining_props_first_round = []
for i in range(0, (2 ** n), 2):
# i, and i+1 teams playing
wining_prop_for_i = props[i][i + 1]
wining_props_first_round.append(wining_prop_for_i)
wining_props_first_round.append(1. - wining_prop_for_i)
wining_props.append(wining_props_first_round)
assert len(wining_props_first_round) == len(props)
for round_num in range(2, n + 1):
# calculate propabilitys for winning in i round for each team
# prop of winning in i round = prop of winning prev round + mo of win this one
# mo win this = for each team we can meet prop of them wining prev * prop we win them
# each team we can meet on round i = all teems // 2^i == we//2^i
this_round_wining_props = []
for team_num in range(2 ** n):
t = team_num // (2 ** round_num) * (2 ** (round_num))
teams_we_meet_this_round = [t + x for x in range(2 ** round_num)]
t = team_num // (2 ** (round_num-1)) * (2 ** (round_num-1))
teams_we_meet_prev_round = [t + x for x in range(2 ** (round_num-1))]
for tt in teams_we_meet_prev_round:
teams_we_meet_this_round.remove(tt)
this_team_wining_props = wining_props[round_num - 2][team_num] # -2 cause numeration
chances_win_i_team = []
for tm in teams_we_meet_this_round:
# chances we meet them * chances we win
chances_win_i_team.append(wining_props[round_num - 2][tm] * props[team_num][tm])
mo_win_this_round = sum(chances_win_i_team)
this_team_wining_props *= mo_win_this_round
this_round_wining_props.append(this_team_wining_props)
#assert 0.99 < sum(this_round_wining_props) < 1.01
wining_props.append(this_round_wining_props)
# now we got props of each win on each round. Lets bet on most propable winer and calculate revenue
#from left to right-1 is playing
def revenue(round_num, teams_left, teams_right, winner=-1):
# let the strongest team win, we bet, and calculate to the bottom
if round_num == 1:
return wining_props[0][winner] if winner != -1 else max(wining_props[0][teams_left:teams_right])
if winner == -1:
winner_prop = max(wining_props[round_num-1][teams_left:teams_right])
winner = wining_props[round_num - 1].index(winner_prop)
else:
winner_prop = wining_props[round_num-1][winner]
split = ((teams_left + teams_right) // 2)
if winner >= split:
return sum([revenue(round_num - 1, teams_left, split), revenue(round_num - 1, split, teams_right, winner),
winner_prop * (2 ** (round_num - 1))])
else:
return sum([revenue(round_num - 1, teams_left, split, winner), revenue(round_num - 1, split, teams_right),
winner_prop * (2 ** (round_num - 1))])
print(revenue(n, 0, (2 ** n)))
```
No
| 9,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Submitted Solution:
```
n = int(input())
# Using the same index I would for a tree
m = 2**n
P = [[int(x)/100.0 for x in input().split()] for _ in range(m)]
state = [[0.0]*64 for _ in range(2*m)]
for i in range(m):
state[m+i][i] = 1.0
for i in reversed(range(1,m)):
for j in range(m):
for k in range(j,m):
# x is probability that team j meets team k in match i
x = state[2*i][j]*state[2*i+1][k]
state[i][j] += P[j][k]*x
state[i][k] += P[k][j]*x
winner = [-1]*(2*m)
winner[1] = max(range(m),key = lambda j: state[1][j])
for i in range(2,m):
if state[i][winner[i//2]]>0:
winner[i] = winner[i//2]
else:
winner[i] = max(range(m),key = lambda j: state[i][j])
points = [0]*(2*m)
points[1] = 2**(n-1)
for i in range(1,m):
x = points[i]//2
points[2*i] = x
points[2*i+1] = x
score = 0.0
score_fix = 0.0
for i in range(1,m):
x = points[i]*state[i][winner[i]]
y = x - score_fix
t = score + y
score_fix = (t - score) - y
score = t
print(repr(score))
```
No
| 9,614 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The annual college sports-ball tournament is approaching, which for trademark reasons we'll refer to as Third Month Insanity. There are a total of 2N teams participating in the tournament, numbered from 1 to 2N. The tournament lasts N rounds, with each round eliminating half the teams. The first round consists of 2N - 1 games, numbered starting from 1. In game i, team 2·i - 1 will play against team 2·i. The loser is eliminated and the winner advances to the next round (there are no ties). Each subsequent round has half as many games as the previous round, and in game i the winner of the previous round's game 2·i - 1 will play against the winner of the previous round's game 2·i.
Every year the office has a pool to see who can create the best bracket. A bracket is a set of winner predictions for every game. For games in the first round you may predict either team to win, but for games in later rounds the winner you predict must also be predicted as a winner in the previous round. Note that the bracket is fully constructed before any games are actually played. Correct predictions in the first round are worth 1 point, and correct predictions in each subsequent round are worth twice as many points as the previous, so correct predictions in the final game are worth 2N - 1 points.
For every pair of teams in the league, you have estimated the probability of each team winning if they play against each other. Now you want to construct a bracket with the maximum possible expected score.
Input
Input will begin with a line containing N (2 ≤ N ≤ 6).
2N lines follow, each with 2N integers. The j-th column of the i-th row indicates the percentage chance that team i will defeat team j, unless i = j, in which case the value will be 0. It is guaranteed that the i-th column of the j-th row plus the j-th column of the i-th row will add to exactly 100.
Output
Print the maximum possible expected score over all possible brackets. Your answer must be correct to within an absolute or relative error of 10 - 9.
Formally, let your answer be a, and the jury's answer be b. Your answer will be considered correct, if <image>.
Examples
Input
2
0 40 100 100
60 0 40 40
0 60 0 45
0 60 55 0
Output
1.75
Input
3
0 0 100 0 100 0 0 0
100 0 100 0 0 0 100 100
0 0 0 100 100 0 0 0
100 100 0 0 0 0 100 100
0 100 0 100 0 0 100 0
100 100 100 100 100 0 0 0
100 0 100 0 0 100 0 0
100 0 100 0 100 100 100 0
Output
12
Input
2
0 21 41 26
79 0 97 33
59 3 0 91
74 67 9 0
Output
3.141592
Note
In the first example, you should predict teams 1 and 4 to win in round 1, and team 1 to win in round 2. Recall that the winner you predict in round 2 must also be predicted as a winner in round 1.
Submitted Solution:
```
n = int(input())
# Using the same index I would for a tree
m = 2**n
P = [[int(x)/100.0 for x in input().split()] for _ in range(m)]
state = [[0.0]*64 for _ in range(2*m)]
for i in range(m):
state[m+i][i] = 1.0
for i in reversed(range(1,m)):
for j in range(m):
for k in range(j,m):
# x is probability that team j meets team k in match i
x = state[2*i][j]*state[2*i+1][k]
state[i][j] += P[j][k]*x
state[i][k] += P[k][j]*x
winner = [-1]*(2*m)
winner[1] = max(range(m),key = lambda j: state[1][j])
for i in range(2,m):
if state[i][winner[i//2]]>0:
winner[i] = winner[i//2]
else:
winner[i] = max(range(m),key = lambda j: state[i][j])
points = [0]*(2*m)
points[1] = 2**(n-1)
for i in range(1,m):
x = points[i]//2
points[2*i] = x
points[2*i+1] = x
score = 0.0
for i in range(1,m):
score += points[i]*state[i][winner[i]]
print(repr(score))
```
No
| 9,615 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
n=int(input())
a=list(map(int,input().split()))
if(n==1):print('1'),exit()
if(n==2):print('4'),exit()
b=[i for i in range(0,n+1)]
r=[1 for i in range(0,n+1)]
def find(x):
if b[x]==x:
return x
else:
b[x]=find(b[x])
return b[x]
for i in range(1,n+1):
x,y=find(i),find(a[i-1])
if x==y:continue
if(r[x]>=r[y]):
r[x]+=r[y]
r[y]=0
b[y]=x
else:
r[y] += r[x]
r[x]=0
b[x] = y
k=0
for i in range(1,n+1):
k+=r[i]**2
mx1=max(r[2],r[1])
mx2=min(r[2],r[1])
for i in range(3,n+1):
if r[i]>mx1:
mx2=mx1
mx1=r[i]
elif r[i]>mx2:
mx2=r[i]
#print(k,mx1,mx2)
k-=mx1**2+mx2**2
k+=(mx1+mx2)**2
print(k)
```
| 9,616 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
input()
l = [[int(x)-1,False] for x in input().split()]
loop = []
for begin in l:
if begin[1]:
continue
count = 0;
nextI = begin[0];
while not l[nextI][1]:
l[nextI][1]=True
nextI = l[nextI][0]
count += 1
loop.append(count)
s = sorted(loop,reverse=True)
total = sum(map(lambda x:x*x,s)) + (2*s[0]*s[1] if len(s)>=2 else 0)
print(total)
```
| 9,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
n=int(input())
p=[0]+list(map(int,input().split()))
vis=[0]*(n+1)
part=[]
for i in range(1,n+1):
if not vis[i]:
tot=0
x=i
while not vis[x]:
tot+=1
vis[x]=1
x=p[x]
part.append(tot)
part.sort(reverse=True)
if len(part)==1:
print(n*n)
else:
ans=(part[0]+part[1])**2
for x in part[2:]:
ans+=x*x
print(ans)
```
| 9,618 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
from itertools import product
def solve():
stations = int(input())
arr = [int(x) - 1 for x in input().split(" ")]
cycles = []
discovered = {} # All the nodes already traversed
for i in arr:
# Already part of a cycle found
if i in discovered:
continue
count = 1
dest = arr[i]
path = [dest]
discovered[dest] = 1
# While still have nodes that are reachable
while dest != i:
count += 1
dest = arr[dest]
path.append(dest)
discovered[dest] = 1
cycles.append(path)
# The whole graph is reachable
if len(cycles) == 1:
print(stations * stations)
return
# Swap destination stations for two points in two chains
longest = sorted(cycles, key=len)[len(cycles) - 2:]
joined = longest[0] + longest[1]
cycles = sorted(cycles, key=len)[:len(cycles) - 2]
cycles.append(joined)
# Find total amount of combinations
total = 0
for cycle in cycles:
total += len(cycle) ** 2
print(total)
solve()
```
| 9,619 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
from collections import defaultdict as dd
g=dd(list)
def addE(u,v):
g[u].append(v)
g[v].append(u)
n=int(input())
l=[int(x) for x in input().split()]
for i in range(n):
addE(i+1,l[i])
visited=[False]*(n+1)
def dfs(v,count):
visited[v]=True
stack=[v]
while len(stack)!=0:
cur=stack.pop()
for ch in g[cur]:
if visited[ch]:
continue
visited[ch]=True
count+=1
stack.append(ch)
return count
ans=[]
for i in range(1,n+1):
if not visited[i]:
ans.append(dfs(i,1))
ans=sorted(ans,reverse=True)
if len(ans) ==1:
print(ans[0]*ans[0])
else:
ans[1]+=ans[0]
ans.pop(0)
print(sum(x*x for x in ans))
```
| 9,620 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
n = int(input())
p = [int(i)-1 for i in input().split()]
visited = [0 for _ in range(n)]
cycle = [0,0]
for i in range(n):
j = i
count = 0
while not visited[j]:
visited[j] = 1
count += 1
j = p[j]
if count > 0:
cycle.append(count)
cycle.sort()
print(sum([i*i for i in cycle]) + 2 * cycle[-1] * cycle[-2])
```
| 9,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
import sys
input = sys.stdin.readline
class Unionfind:
def __init__(self, n):
self.par = [-1]*n
self.rank = [1]*n
def root(self, x):
p = x
while not self.par[p]<0:
p = self.par[p]
while x!=p:
tmp = x
x = self.par[x]
self.par[tmp] = p
return p
def unite(self, x, y):
rx, ry = self.root(x), self.root(y)
if rx==ry: return False
if self.rank[rx]<self.rank[ry]:
rx, ry = ry, rx
self.par[rx] += self.par[ry]
self.par[ry] = rx
if self.rank[rx]==self.rank[ry]:
self.rank[rx] += 1
def is_same(self, x, y):
return self.root(x)==self.root(y)
def count(self, x):
return -self.par[self.root(x)]
n = int(input())
p = list(map(int, input().split()))
uf = Unionfind(n)
for i in range(n):
uf.unite(i, p[i]-1)
rs = set(uf.root(i) for i in range(n))
l = []
for r in rs:
l.append(uf.count(r))
l.sort(reverse=True)
if len(l)==1:
print(n*n)
exit()
ans = (l[0]+l[1])**2
for i in range(2, len(l)):
ans += l[i]**2
print(ans)
```
| 9,622 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Tags: dfs and similar, greedy, math
Correct Solution:
```
def dfs(i, Colour, P):
Stack = [i]
size = 0
while Stack:
v = Stack[-1]
if Colour[v] == 0:
Colour[v] = 1
size += 1
if Colour[P[v] - 1] == 0:
Stack.append(P[v] - 1)
else:
Colour[v] = 2
Stack.pop()
else:
Colour[v] = 2
Stack.pop()
return size
n = int(input())
P = list(map(int, input().split()))
Colour = [0] * n
Len = []
for i in range(n):
if Colour[i] == 0:
Len.append(dfs(i, Colour, P))
c1 = 0
c2 = 0
count = 0
for i in Len:
if c1 <= i:
c2 = c1
c1 = i
elif i > c2:
c2 = i
for i in Len:
count += i*i
count += c1*c2*2
print(count)
```
| 9,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
def dfs(root,t):
time[root]=t
vis[root]=1
stack=[root]
while (len(stack)!=0):
element = stack.pop()
time[element] = t
vis[element] = 1
for i in graph[element]:
if vis[i]==0:
stack.append(i)
t+=1
else:
c.append(t-time[i]+1)
# for i in graph[root]:
# if vis[i]==0:
# dfs(i,t+1)
# else:
# c.append(t-time[i]+1)
n=int(input())
l=list(map(int,input().split()))
graph=[[] for i in range(n)]
for i in range(n):
graph[i].append(l[i]-1)
# print (graph)
vis=[0]*n
c=[]
time=[0]*n
for i in range(n):
if vis[i]==0:
dfs(i,1)
# print (time)
# print (c)
c.sort()
ans=0
for i in c:
ans+=i**2
if len(c)>=2:
print (ans+c[-1]*c[-2]*2)
else:
print (ans)
```
Yes
| 9,624 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
n = int(input())
graph = {}
a = input().split()
for i in range(n):
graph[i] = int(a[i]) - 1
vis = [False] * n
cycles = []
for i in graph.keys():
if not vis[i]:
cv = graph[i]
vis[i] = True
size = 1
while cv != i:
vis[cv] = True
cv = graph[cv]
size += 1
cycles.append(size)
cycles.sort(reverse = True)
v = 0
if len(cycles) >= 2:
v += (cycles[0] + cycles[1]) ** 2
for i in cycles[2:]:
v += i ** 2
else:
v = cycles[0] ** 2
print(v)
```
Yes
| 9,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
n=int(input())
p=[int(x) for x in input().split()]
p.insert(0,-3)
max1,max2=0,0
used=[0]*(n+1)
count=0
for i in range (1, n+1):
m=0
v=i
while used[p[v]]==0:
used[p[v]]=1
v=p[v]
m+=1
if m>max2:
max2=m
if max2>max1:
max2,max1=max1,max2
count+=m**2
count=count-max1**2-max2**2+(max1+max2)**2
print(count)
```
Yes
| 9,626 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
#!/usr/bin/env python3
n = int(input())
P = [int(p)-1 for p in input().split()] # permutation
seen = [False]*n
res = m0 = m1 = 0
for i in range(n):
if not seen[i]:
seen[i] = True
j = P[i]
c = 1 # taille du cycle
while j!=i:
seen[j] = True
j = P[j]
c += 1
res += c*c
if c>m0:
m0,m1 = c,m0
elif c>m1:
m1 = c
# on fusionne les 2 plus grands cycles
res += (m0+m1)*(m0+m1)-m0*m0-m1*m1
print(res)
```
Yes
| 9,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
b=[0]*n
k1=0
s=[]
for i in range (n):
if b[i]==0:
j=a[i]-1
k=1
b[i]=1
sp=[i]
while b[j] == 0:
sp.append(j)
k+=1
j=a[j]-1
k1=max(k,k1)
if k > k1:
s.append(k1)
k1=int(k)
else:
s.append(k)
for u in sp:
b[u]=k
print(s,b,k1)
print(sum(list(map(lambda x: x*x,s)))+k1*max(s))
```
No
| 9,628 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
n = int(input())
p = list(map(int, input().split()))
c = []
visited = [0]*(n+1)
for i in range(n):
if visited[p[i]] == 0:
ct = 1
t = p[p[i]-1]
visited[p[i]] = 1
while t != p[i]:
t = p[t-1]
visited[t-1] = 1
ct += 1
c.append(ct)
c.sort()
if len(c) == 1:
print(c[0]**2)
else:
aux = c[-1] + c[-2]
c = c[:-2] + [aux]
print(sum(i**2 for i in c))
```
No
| 9,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
from collections import defaultdict as dd
g=dd(list)
def addE(u,v):
g[u].append(v)
g[v].append(u)
n=int(input())
l=[int(x) for x in input().split()]
for i in range(n):
addE(i+1,l[i])
visited=[False]*(n+1)
def dfs(v,count):
visited[v]=True
for ch in g[v]:
if visited[ch]:
continue
count+=1
count=dfs(ch,count)
return count
ans=[]
for i in range(1,n+1):
if not visited[i]:
ans.append(dfs(i,1))
ans=sorted(ans,reverse=True)
if len(ans) > 1:
ans2=ans[0]+ans[1]
else:
ans2=ans[0]
ans2*=ans2
if len(ans) > 2:
ans2+=sum(ans[2:])
print(ans2)
```
No
| 9,630 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The construction of subway in Bertown is almost finished! The President of Berland will visit this city soon to look at the new subway himself.
There are n stations in the subway. It was built according to the Bertown Transport Law:
1. For each station i there exists exactly one train that goes from this station. Its destination station is pi, possibly pi = i;
2. For each station i there exists exactly one station j such that pj = i.
The President will consider the convenience of subway after visiting it. The convenience is the number of ordered pairs (x, y) such that person can start at station x and, after taking some subway trains (possibly zero), arrive at station y (1 ≤ x, y ≤ n).
The mayor of Bertown thinks that if the subway is not convenient enough, then the President might consider installing a new mayor (and, of course, the current mayor doesn't want it to happen). Before President visits the city mayor has enough time to rebuild some paths of subway, thus changing the values of pi for not more than two subway stations. Of course, breaking the Bertown Transport Law is really bad, so the subway must be built according to the Law even after changes.
The mayor wants to do these changes in such a way that the convenience of the subway is maximized. Help him to calculate the maximum possible convenience he can get!
Input
The first line contains one integer number n (1 ≤ n ≤ 100000) — the number of stations.
The second line contains n integer numbers p1, p2, ..., pn (1 ≤ pi ≤ n) — the current structure of the subway. All these numbers are distinct.
Output
Print one number — the maximum possible value of convenience.
Examples
Input
3
2 1 3
Output
9
Input
5
1 5 4 3 2
Output
17
Note
In the first example the mayor can change p2 to 3 and p3 to 1, so there will be 9 pairs: (1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3).
In the second example the mayor can change p2 to 4 and p3 to 5.
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 27 19:33:34 2017
@author: savit
"""
n=int(input())
a=list(map(int,input().split()))
b=[]
chains=[]
for i in range(n):
b.append(True)
for i in range(n):
if(b[i]):
chains.append([i,])
j=i
b[j]=False
while((a[j]-1)!=chains[-1][0]):
chains[-1].append(a[j]-1)
j=a[j]-1
b[j]=False
chainlen=list(map(len,chains))
if(len(chains)<1):
#print("entered")
max1=max(chainlen)
max1=chainlen.index(max1)
chainlen[max1]*=-1
max2=max(chainlen)
max2=chainlen.index(max2)
#print(max1,max2,chainlen)
chainlen[max2]=chainlen[max2]+(-1*chainlen[max1])
del chainlen[max1]
con=0
#print(chains)
#print(chainlen)
for i in chainlen:
con+=i*i
print(con)
```
No
| 9,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
#Problem Set E: Collaborated with no one
from collections import defaultdict
mod_v = 1000000007
temp_arr = [[1]]
for i in range(1,1010):
a = [1]
for k in range(1,i):
a.append((temp_arr[i-1][k-1]+temp_arr[i-1][k]) % mod_v)
a.append(1)
temp_arr.append(a)
ans_arr = [1]
for i in range(1,1010):
res = 0
for j in range(i):
res += ans_arr[j] * temp_arr[i-1][j]
res %= mod_v
ans_arr.append(res)
n_list=list(map(int, input().split()))
n = n_list[0]
lines = n_list[1]
new_list = [0 for __ in range(n)]
for i in range(lines):
input1 = list(map(int, input()))
for k in range(n):
new_list[k] |= input1[k] << i
default_d = defaultdict(int)
for k in new_list:
default_d[k] += 1
answer = 1
for n in default_d.values():
answer = answer * ans_arr[n] % mod_v
print(answer)
```
| 9,632 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
from collections import defaultdict
def E1():
mod = 10 ** 9 + 7
comb = [[1]]
for i in range(1, 1010):
x = [1]
for j in range(1, i):
x.append((comb[i - 1][j - 1] + comb[i - 1][j]) % mod)
x.append(1)
comb.append(x)
dp = [1]
for i in range(1, 1010):
r = 0
for k in range(i):
r += dp[k] * comb[i - 1][k]
r %= mod
dp.append(r)
m, n = map(int, input().split())
ns = [0 for __ in range(m)]
for j in range(n):
temp = input()
s = [int(i) for i in temp]
for i in range(m):
ns[i] |= s[i] << j
dd = defaultdict(int)
for e in ns:
dd[e] += 1
ans = 1
for b in dd.values():
ans = ans * dp[b] % mod
print(ans)
if __name__=='__main__':
E1()
```
| 9,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
import sys
from collections import defaultdict as di
MOD = int(1e9+7)
#bells = di(int)
#bells[0,0] = 1
#K=1000
#for j in range(1,K):
# bells[0,j] = bells[j-1,j-1]
# for i in range(j):
# bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD
#
#def bellman(n):
# return bells[n-1,n-1]
#lista = []
#for i in range(K):
# lista.append(bellman(i+1))
#print(lista)
#sys.exit()
bells = [1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570, 4213597, 27644437, 190899322, 382958538, 480142077, 864869230, 76801385, 742164233, 157873304, 812832668, 706900318, 546020311, 173093227, 759867260, 200033042, 40680577, 159122123, 665114805, 272358185, 365885605, 744733441, 692873095, 463056339, 828412002, 817756178, 366396447, 683685664, 681586780, 840750853, 683889724, 216039853, 954226396, 858087702, 540284076, 514254014, 647209774, 900185117, 348985796, 609459762, 781824096, 756600466, 654591160, 171792186, 748630189, 848074470, 75742990, 352494923, 278101098, 462072300, 334907097, 10474572, 495625635, 586051441, 159996073, 479379757, 707597945, 561063550, 974840072, 209152841, 906106015, 467465396, 82034048, 392794164, 700950185, 344807921, 475335490, 496881113, 358229039, 519104519, 784488542, 665151655, 307919717, 591199688, 692769253, 335414677, 884560880, 847374378, 791103220, 200350027, 485480275, 557337842, 434181960, 73976309, 792463021, 462067202, 677783523, 295755371, 435431099, 193120002, 513369106, 134597056, 143018012, 353529690, 591382993, 163160926, 287984994, 842145354, 703798750, 386436223, 618375990, 636477101, 536261496, 574800957, 34046224, 167415054, 961776342, 807141069, 218578541, 513967253, 460200768, 230725907, 239843627, 792763805, 368353031, 740982762, 126993201, 967654419, 588554507, 728057622, 239984996, 818342358, 882367644, 216705655, 267152940, 867213913, 330735015, 934583772, 59261085, 443816525, 568733052, 754405433, 244324432, 153903806, 292097031, 557968620, 311976469, 242994387, 773037141, 549999484, 243701468, 941251494, 7149216, 932327662, 456857477, 739044033, 645452229, 69273749, 304951367, 503353209, 243194926, 688663125, 239795364, 522687881, 121506491, 835250259, 159173149, 545801717, 19848500, 322507013, 106069527, 807985703, 290163328, 971751677, 238407093, 981758956, 301257197, 728003485, 817681690, 318332431, 864806329, 87958605, 929106232, 617996713, 519300437, 307911059, 137306007, 887695462, 633135243, 442387331, 730250437, 27723819, 80605394, 760335262, 822289356, 415861662, 558003999, 645049413, 347692428, 380668983, 897875109, 278111491, 106909073, 951914124, 374756177, 635211535, 286442394, 774619548, 756991257, 929298287, 923425488, 182439740, 266683608, 415378498, 728411148, 808161291, 436338820, 692451577, 228029692, 235546564, 895805974, 758052804, 700926159, 226442121, 579900323, 96916377, 243044550, 858703179, 30279679, 343764928, 100627558, 840734795, 291199760, 989808717, 370270411, 158336199, 393391701, 881731480, 507200370, 588418523, 340981140, 295449954, 683858381, 903859151, 866470542, 4959332, 237784075, 861373023, 950693473, 955867890, 400039807, 939877954, 124824910, 954530940, 204884446, 42218442, 234856311, 189836713, 179563650, 683193288, 929322036, 73574908, 943547254, 103031032, 141180580, 540183111, 680050153, 382916846, 948921599, 252835397, 199109508, 551172546, 700090782, 44999714, 970123610, 145637563, 33948107, 267648423, 504777414, 584919509, 212459491, 242880452, 351366578, 345323768, 285497541, 692868556, 706562675, 675626979, 620872182, 136458675, 971105139, 182064384, 948539342, 186406165, 706529481, 790490927, 888369436, 784409511, 835815713, 447895018, 17015606, 342727699, 321837918, 394134115, 563672582, 70390332, 61116103, 949269501, 833942074, 581389345, 570974405, 768179852, 765734098, 928340756, 541194960, 126833304, 427218334, 75800034, 100445725, 242810216, 330081440, 986329793, 298082322, 643160582, 505669854, 255287400, 403977567, 659185446, 596703087, 289443930, 478095124, 920175726, 205886838, 729278433, 535998256, 658801091, 606948240, 432632296, 552723022, 17794080, 234033713, 189986528, 444922724, 263196004, 846019724, 684703320, 895782046, 505050988, 44287113, 505335732, 436498414, 12098144, 714227851, 643983136, 647148160, 579243434, 951209063, 511291462, 426622734, 830870687, 949900312, 599926584, 633837711, 176405710, 913717356, 753535741, 874916804, 956692925, 220742732, 649500982, 584759931, 109573948, 937203173, 96881033, 305784835, 559854872, 894253854, 746366726, 951492991, 532579856, 822308583, 572042503, 397665465, 600979983, 914199453, 628402767, 594763006, 9791558, 451332658, 516069180, 651367831, 962708649, 687016963, 539878802, 107278296, 926059014, 371504543, 556987417, 447666745, 565595310, 778161513, 995461128, 121460302, 599892490, 242414970, 900391574, 362620950, 292857964, 495260535, 355054738, 176340034, 370047225, 509682533, 459314034, 40869728, 534741938, 788604648, 945028000, 701904601, 154924404, 695162652, 220536827, 615701976, 167761915, 833779942, 52430883, 368585637, 936409860, 654822736, 613850019, 941559844, 357840989, 218223326, 721900618, 171013438, 597980462, 193395922, 949112044, 859322955, 354602094, 807705992, 347609311, 451694117, 623122523, 252980054, 491785682, 13877214, 918727309, 750110421, 114981703, 174636266, 363160184, 781715298, 30575457, 862940854, 642129450, 34525888, 798422280, 792396821, 168367459, 344551406, 799847612, 626838494, 671596530, 167280197, 959000039, 614621296, 273560655, 8705247, 284372524, 940371542, 906010703, 582585495, 929449942, 308961449, 768816240, 674729787, 279648144, 286568146, 938661138, 536038536, 456529723, 18843013, 501518651, 457224675, 520694423, 938573228, 179014658, 169719825, 459657583, 302109678, 560375405, 556039265, 348713003, 957546568, 687116649, 3656313, 562760316, 716689588, 324677598, 570275686, 60738163, 996201577, 305457565, 38935942, 538451492, 228282207, 77975017, 389525459, 25000235, 152169430, 62331625, 618611219, 462328092, 106666757, 661839198, 177836427, 313546124, 392585017, 950280707, 551167559, 389204003, 77447456, 158414991, 766574847, 941433736, 363591676, 805565034, 312418363, 999641612, 122925536, 768845786, 608121932, 373163730, 783033644, 74564718, 894150080, 796617981, 274365270, 802488053, 947861187, 401960309, 143529635, 769621671, 249500752, 619408647, 849453216, 354838551, 69741157, 944781258, 135254314, 7413076, 416298064, 871313316, 343673168, 375656287, 868866230, 179060630, 399560227, 852555486, 987661859, 165863065, 12882359, 3688778, 380092596, 438366086, 720041886, 240796679, 588918084, 14802664, 17188673, 504951961, 842108931, 839289310, 256364811, 121095676, 164017670, 35340476, 875551801, 239615760, 262141182, 262741417, 456560451, 350350882, 777143297, 264469934, 807530935, 89546104, 246698645, 241166716, 125659016, 839103323, 418357064, 186866754, 179291319, 326054960, 172454707, 430532716, 558625738, 306201933, 61986384, 837357643, 575407529, 983555480, 13784333, 311989892, 153386582, 633092291, 722816631, 633510090, 551352594, 323601313, 248995449, 672011813, 612805937, 202743586, 215183002, 32688571, 38454892, 245790100, 451190956, 823199664, 12164578, 67389319, 584760532, 968838901, 307205626, 971537038, 836812364, 663878188, 468850566, 647599527, 839342879, 242347168, 169911213, 993779953, 251402771, 969281106, 416168275, 738337745, 8172262, 852101376, 879373674, 929752458, 452163141, 48347012, 500253327, 672444134, 406391337, 665852222, 499704706, 116418822, 67956495, 994761753, 808150613, 251453632, 543431315, 143101466, 381253760, 826943616, 763270983, 959511676, 323777679, 514214633, 669340157, 471626592, 557874503, 304789863, 116939617, 503636634, 660499296, 659726735, 273788323, 704107733, 718417780, 624033370, 355000823, 194537583, 760997582, 289828020, 778033293, 933152490, 910945024, 644565086, 434509630, 289427510, 502291783, 421699389, 159196930, 834667293, 313599675, 560298831, 812176354, 865521998, 126796474, 886921339, 937011401, 791993161, 583948688, 275408655, 665183437, 130342900, 699431744, 117550047, 460234251, 56770880, 306091228, 912949106, 626369877, 852501236, 241076503, 262988042, 737247015, 831044258, 475123008, 928949542, 332750699, 696284377, 689111142, 196862045, 570365577, 187156806, 451528865, 635110126, 385331290, 263486377, 200189955, 206842029, 457862597, 450522487, 818984909, 710634976, 461356455, 71985964, 781500456, 467334209, 46762760, 97663653, 870671823, 255977331, 79650379, 32876340, 636190780, 364339752, 597149326, 452604321, 748186407, 302032725, 779013981, 111971627, 175687535, 399961122, 451853028, 798326812, 902775588, 362836436, 498862780, 160000437, 629259604, 919729986, 5994845, 631476109, 371320167, 76164236, 448643023, 945220853, 111192011, 150577654, 827274836, 17668451, 938388515, 88566735, 27940328, 882026632, 712756966, 83642744, 873585716, 638987456, 405271094, 822216133, 345587303, 668558160, 314983205, 826678060, 563583341, 516998387, 77703032, 726563479, 155257773, 49705622, 891556456, 164127879, 842558039, 189099480, 956148983, 992226557, 671472701, 137476493, 871069222, 78241093, 728497057, 278888712, 332713952, 222597908, 235198692, 876216003, 167364357, 722341150, 519365334, 604855967, 834816722, 850786742, 416385106, 608404143, 311628039, 507077268, 571796589, 506398832, 305540948, 556971113, 444565912, 866477296, 411983920, 905854221, 901986568, 512703782, 684027511, 596294441, 916862272, 495347444, 802477106, 235968146, 257527513, 528476230, 969655767, 772044489, 682345813, 66418556, 603372280, 439233253, 278244332, 590581374, 353687769, 321352820, 245676729, 325255315, 91010070, 923699200, 837616604, 736177081, 528261400, 876353388, 339195128, 377206087, 769944080, 772953529, 123785293, 35984916, 461119619, 236140329, 884137913, 625494604, 791773064, 661436140, 308509072, 54134926, 279367618, 51918421, 149844467, 308119110, 948074070, 941738748, 890320056, 933243910, 430364344, 903312966, 574904506, 56353560, 861112413, 440392450, 937276559, 944662107, 599470900, 458887833, 962614595, 589151703, 997944986, 642961512, 63773929, 737273926, 110546606, 654813100, 374632916, 327432718, 307869727, 387738989, 133844439, 688886605, 989252194, 303514517, 79062408, 79381603, 941446109, 189307316, 728764788, 619946432, 359845738, 216171670, 690964059, 337106876, 762119224, 226624101, 401879891, 47069454, 41411521, 429556898, 188042667, 832342137, 770962364, 294422843, 991268380, 137519647, 903275202, 115040918, 521250780, 783585266, 98267582, 337193737, 717487549, 510794369, 206729333, 248526905, 412652544, 146948138, 103954760, 132289464, 938042429, 185735408, 640754677, 315573450, 956487685, 454822141, 783819416, 882547786, 976850791, 307258357, 929434429, 832158433, 334518103, 700273615, 734048238, 48618988, 693477108, 12561960, 598093056, 154072663, 174314067, 345548333, 479759833, 658594149, 282072153, 57970886, 905112877, 584117466, 472359245, 776860470, 324216896, 334199385, 321245477, 508188925, 521442872, 286692969, 245141864, 59342176, 896413224, 573301289, 869453643, 87399903, 60102262, 835514392, 493582549, 649986925, 576899388, 20454903, 271374500, 589229956, 505139242, 789538901, 243337905, 248443618, 39334644, 831631854, 541659849, 159802612, 524090232, 855135628, 542520502, 967119953, 597294058, 465231251]
def bellman(n):
return bells[n-1]
m,n = [int(x) for x in input().split()]
Tlist = []
for _ in range(n):
Tlist.append(input())
numbs = []
for i in range(m):
numb = []
for j in range(n):
numb.append(Tlist[j][i])
numbs.append(int(''.join(numb),2))
eqsize = di(lambda:0)
for numb in numbs:
eqsize[numb]+=1
sets = []
for numb in eqsize:
sets.append(eqsize[numb])
parts = 1
for s in sets:
parts*=bellman(s)
parts%=MOD
print(parts)
```
| 9,634 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
import sys
#f = open('input', 'r')
f = sys.stdin
n,m = list(map(int, f.readline().split()))
s = [f.readline().strip() for _ in range(m)]
s = [list(x) for x in s]
d = {}
for k in zip(*s):
if k in d:
d[k] += 1
else:
d[k] = 1
dv = d.values()
got = [1, 2, 5, 15, 52, 203, 877, 4140, 21147, 115975, 678570, 4213597, 27644437, 190899322, 382958538, 480142077, 864869230, 76801385, 742164233, 157873304, 812832668, 706900318, 546020311, 173093227, 759867260, 200033042, 40680577, 159122123, 665114805, 272358185, 365885605, 744733441, 692873095, 463056339, 828412002, 817756178, 366396447, 683685664, 681586780, 840750853, 683889724, 216039853, 954226396, 858087702, 540284076, 514254014, 647209774, 900185117, 348985796, 609459762, 781824096, 756600466, 654591160, 171792186, 748630189, 848074470, 75742990, 352494923, 278101098, 462072300, 334907097, 10474572, 495625635, 586051441, 159996073, 479379757, 707597945, 561063550, 974840072, 209152841, 906106015, 467465396, 82034048, 392794164, 700950185, 344807921, 475335490, 496881113, 358229039, 519104519, 784488542, 665151655, 307919717, 591199688, 692769253, 335414677, 884560880, 847374378, 791103220, 200350027, 485480275, 557337842, 434181960, 73976309, 792463021, 462067202, 677783523, 295755371, 435431099, 193120002, 513369106, 134597056, 143018012, 353529690, 591382993, 163160926, 287984994, 842145354, 703798750, 386436223, 618375990, 636477101, 536261496, 574800957, 34046224, 167415054, 961776342, 807141069, 218578541, 513967253, 460200768, 230725907, 239843627, 792763805, 368353031, 740982762, 126993201, 967654419, 588554507, 728057622, 239984996, 818342358, 882367644, 216705655, 267152940, 867213913, 330735015, 934583772, 59261085, 443816525, 568733052, 754405433, 244324432, 153903806, 292097031, 557968620, 311976469, 242994387, 773037141, 549999484, 243701468, 941251494, 7149216, 932327662, 456857477, 739044033, 645452229, 69273749, 304951367, 503353209, 243194926, 688663125, 239795364, 522687881, 121506491, 835250259, 159173149, 545801717, 19848500, 322507013, 106069527, 807985703, 290163328, 971751677, 238407093, 981758956, 301257197, 728003485, 817681690, 318332431, 864806329, 87958605, 929106232, 617996713, 519300437, 307911059, 137306007, 887695462, 633135243, 442387331, 730250437, 27723819, 80605394, 760335262, 822289356, 415861662, 558003999, 645049413, 347692428, 380668983, 897875109, 278111491, 106909073, 951914124, 374756177, 635211535, 286442394, 774619548, 756991257, 929298287, 923425488, 182439740, 266683608, 415378498, 728411148, 808161291, 436338820, 692451577, 228029692, 235546564, 895805974, 758052804, 700926159, 226442121, 579900323, 96916377, 243044550, 858703179, 30279679, 343764928, 100627558, 840734795, 291199760, 989808717, 370270411, 158336199, 393391701, 881731480, 507200370, 588418523, 340981140, 295449954, 683858381, 903859151, 866470542, 4959332, 237784075, 861373023, 950693473, 955867890, 400039807, 939877954, 124824910, 954530940, 204884446, 42218442, 234856311, 189836713, 179563650, 683193288, 929322036, 73574908, 943547254, 103031032, 141180580, 540183111, 680050153, 382916846, 948921599, 252835397, 199109508, 551172546, 700090782, 44999714, 970123610, 145637563, 33948107, 267648423, 504777414, 584919509, 212459491, 242880452, 351366578, 345323768, 285497541, 692868556, 706562675, 675626979, 620872182, 136458675, 971105139, 182064384, 948539342, 186406165, 706529481, 790490927, 888369436, 784409511, 835815713, 447895018, 17015606, 342727699, 321837918, 394134115, 563672582, 70390332, 61116103, 949269501, 833942074, 581389345, 570974405, 768179852, 765734098, 928340756, 541194960, 126833304, 427218334, 75800034, 100445725, 242810216, 330081440, 986329793, 298082322, 643160582, 505669854, 255287400, 403977567, 659185446, 596703087, 289443930, 478095124, 920175726, 205886838, 729278433, 535998256, 658801091, 606948240, 432632296, 552723022, 17794080, 234033713, 189986528, 444922724, 263196004, 846019724, 684703320, 895782046, 505050988, 44287113, 505335732, 436498414, 12098144, 714227851, 643983136, 647148160, 579243434, 951209063, 511291462, 426622734, 830870687, 949900312, 599926584, 633837711, 176405710, 913717356, 753535741, 874916804, 956692925, 220742732, 649500982, 584759931, 109573948, 937203173, 96881033, 305784835, 559854872, 894253854, 746366726, 951492991, 532579856, 822308583, 572042503, 397665465, 600979983, 914199453, 628402767, 594763006, 9791558, 451332658, 516069180, 651367831, 962708649, 687016963, 539878802, 107278296, 926059014, 371504543, 556987417, 447666745, 565595310, 778161513, 995461128, 121460302, 599892490, 242414970, 900391574, 362620950, 292857964, 495260535, 355054738, 176340034, 370047225, 509682533, 459314034, 40869728, 534741938, 788604648, 945028000, 701904601, 154924404, 695162652, 220536827, 615701976, 167761915, 833779942, 52430883, 368585637, 936409860, 654822736, 613850019, 941559844, 357840989, 218223326, 721900618, 171013438, 597980462, 193395922, 949112044, 859322955, 354602094, 807705992, 347609311, 451694117, 623122523, 252980054, 491785682, 13877214, 918727309, 750110421, 114981703, 174636266, 363160184, 781715298, 30575457, 862940854, 642129450, 34525888, 798422280, 792396821, 168367459, 344551406, 799847612, 626838494, 671596530, 167280197, 959000039, 614621296, 273560655, 8705247, 284372524, 940371542, 906010703, 582585495, 929449942, 308961449, 768816240, 674729787, 279648144, 286568146, 938661138, 536038536, 456529723, 18843013, 501518651, 457224675, 520694423, 938573228, 179014658, 169719825, 459657583, 302109678, 560375405, 556039265, 348713003, 957546568, 687116649, 3656313, 562760316, 716689588, 324677598, 570275686, 60738163, 996201577, 305457565, 38935942, 538451492, 228282207, 77975017, 389525459, 25000235, 152169430, 62331625, 618611219, 462328092, 106666757, 661839198, 177836427, 313546124, 392585017, 950280707, 551167559, 389204003, 77447456, 158414991, 766574847, 941433736, 363591676, 805565034, 312418363, 999641612, 122925536, 768845786, 608121932, 373163730, 783033644, 74564718, 894150080, 796617981, 274365270, 802488053, 947861187, 401960309, 143529635, 769621671, 249500752, 619408647, 849453216, 354838551, 69741157, 944781258, 135254314, 7413076, 416298064, 871313316, 343673168, 375656287, 868866230, 179060630, 399560227, 852555486, 987661859, 165863065, 12882359, 3688778, 380092596, 438366086, 720041886, 240796679, 588918084, 14802664, 17188673, 504951961, 842108931, 839289310, 256364811, 121095676, 164017670, 35340476, 875551801, 239615760, 262141182, 262741417, 456560451, 350350882, 777143297, 264469934, 807530935, 89546104, 246698645, 241166716, 125659016, 839103323, 418357064, 186866754, 179291319, 326054960, 172454707, 430532716, 558625738, 306201933, 61986384, 837357643, 575407529, 983555480, 13784333, 311989892, 153386582, 633092291, 722816631, 633510090, 551352594, 323601313, 248995449, 672011813, 612805937, 202743586, 215183002, 32688571, 38454892, 245790100, 451190956, 823199664, 12164578, 67389319, 584760532, 968838901, 307205626, 971537038, 836812364, 663878188, 468850566, 647599527, 839342879, 242347168, 169911213, 993779953, 251402771, 969281106, 416168275, 738337745, 8172262, 852101376, 879373674, 929752458, 452163141, 48347012, 500253327, 672444134, 406391337, 665852222, 499704706, 116418822, 67956495, 994761753, 808150613, 251453632, 543431315, 143101466, 381253760, 826943616, 763270983, 959511676, 323777679, 514214633, 669340157, 471626592, 557874503, 304789863, 116939617, 503636634, 660499296, 659726735, 273788323, 704107733, 718417780, 624033370, 355000823, 194537583, 760997582, 289828020, 778033293, 933152490, 910945024, 644565086, 434509630, 289427510, 502291783, 421699389, 159196930, 834667293, 313599675, 560298831, 812176354, 865521998, 126796474, 886921339, 937011401, 791993161, 583948688, 275408655, 665183437, 130342900, 699431744, 117550047, 460234251, 56770880, 306091228, 912949106, 626369877, 852501236, 241076503, 262988042, 737247015, 831044258, 475123008, 928949542, 332750699, 696284377, 689111142, 196862045, 570365577, 187156806, 451528865, 635110126, 385331290, 263486377, 200189955, 206842029, 457862597, 450522487, 818984909, 710634976, 461356455, 71985964, 781500456, 467334209, 46762760, 97663653, 870671823, 255977331, 79650379, 32876340, 636190780, 364339752, 597149326, 452604321, 748186407, 302032725, 779013981, 111971627, 175687535, 399961122, 451853028, 798326812, 902775588, 362836436, 498862780, 160000437, 629259604, 919729986, 5994845, 631476109, 371320167, 76164236, 448643023, 945220853, 111192011, 150577654, 827274836, 17668451, 938388515, 88566735, 27940328, 882026632, 712756966, 83642744, 873585716, 638987456, 405271094, 822216133, 345587303, 668558160, 314983205, 826678060, 563583341, 516998387, 77703032, 726563479, 155257773, 49705622, 891556456, 164127879, 842558039, 189099480, 956148983, 992226557, 671472701, 137476493, 871069222, 78241093, 728497057, 278888712, 332713952, 222597908, 235198692, 876216003, 167364357, 722341150, 519365334, 604855967, 834816722, 850786742, 416385106, 608404143, 311628039, 507077268, 571796589, 506398832, 305540948, 556971113, 444565912, 866477296, 411983920, 905854221, 901986568, 512703782, 684027511, 596294441, 916862272, 495347444, 802477106, 235968146, 257527513, 528476230, 969655767, 772044489, 682345813, 66418556, 603372280, 439233253, 278244332, 590581374, 353687769, 321352820, 245676729, 325255315, 91010070, 923699200, 837616604, 736177081, 528261400, 876353388, 339195128, 377206087, 769944080, 772953529, 123785293, 35984916, 461119619, 236140329, 884137913, 625494604, 791773064, 661436140, 308509072, 54134926, 279367618, 51918421, 149844467, 308119110, 948074070, 941738748, 890320056, 933243910, 430364344, 903312966, 574904506, 56353560, 861112413, 440392450, 937276559, 944662107, 599470900, 458887833, 962614595, 589151703, 997944986, 642961512, 63773929, 737273926, 110546606, 654813100, 374632916, 327432718, 307869727, 387738989, 133844439, 688886605, 989252194, 303514517, 79062408, 79381603, 941446109, 189307316, 728764788, 619946432, 359845738, 216171670, 690964059, 337106876, 762119224, 226624101, 401879891, 47069454, 41411521, 429556898, 188042667, 832342137, 770962364, 294422843, 991268380, 137519647, 903275202, 115040918, 521250780, 783585266, 98267582, 337193737, 717487549, 510794369, 206729333, 248526905, 412652544, 146948138, 103954760, 132289464, 938042429, 185735408, 640754677, 315573450, 956487685, 454822141, 783819416, 882547786, 976850791, 307258357, 929434429, 832158433, 334518103, 700273615, 734048238, 48618988, 693477108, 12561960, 598093056, 154072663, 174314067, 345548333, 479759833, 658594149, 282072153, 57970886, 905112877, 584117466, 472359245, 776860470, 324216896, 334199385, 321245477, 508188925, 521442872, 286692969, 245141864, 59342176, 896413224, 573301289, 869453643, 87399903, 60102262, 835514392, 493582549, 649986925, 576899388, 20454903, 271374500, 589229956, 505139242, 789538901, 243337905, 248443618, 39334644, 831631854, 541659849, 159802612, 524090232, 855135628, 542520502, 967119953, 597294058, 465231251]
MM = 10**9 + 7
ans = 1
for v in dv:
ans = ans*got[v-1]
ans = ans%MM
print(ans)
'''
t = [[0] * 1010 for _ in range(1010)]
t[1][1] = 1
for i in range(2,1001):
for j in range(1,i+1):
t[i][j] = t[i-1][j-1] + t[i-1][j]*j
t[i][j] = t[i][j] % MM
print([sum(t[i])%MM for i in range(1,1001)])
'''
```
| 9,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
MOD = 10**9 + 7
m, N = map(int, input().split())
binom = [[1] + [0 for i in range(m)] for j in range(m + 1)]
for n in range(1, m + 1):
for k in range(1, n + 1):
binom[n][k] = (binom[n - 1][k] + binom[n - 1][k - 1]) % MOD
bell = [0 for n in range(m + 1)]
bell[0] = bell[1] = 1
for n in range(1, m):
for k in range(n + 1):
bell[n + 1] += bell[k] * binom[n][k]
bell[n + 1] %= MOD
#print(bell)
bags = [0 for i in range(m)]
for it in range(N):
for i, z in enumerate(input()):
if z == '1':
bags[i] |= (1 << it)
difs = set(bags)
sol = 1
for mask in difs:
sol = sol * bell[bags.count(mask)] % MOD
print(sol)
```
| 9,636 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Tags: bitmasks, combinatorics, dp, math
Correct Solution:
```
from collections import defaultdict as di
MOD = int(1e9+7)
bells = di(int)
bells[0,0] = 1
K=1000
for j in range(1,K):
bells[0,j] = bells[j-1,j-1]
for i in range(j):
bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD
def bellman(n):
return bells[n-1,n-1]
m,n = [int(x) for x in input().split()]
Tlist = []
for _ in range(n):
Tlist.append(input())
numbs = []
for i in range(m):
numb = []
for j in range(n):
numb.append(Tlist[j][i])
numbs.append(int(''.join(numb),2))
eqsize = di(lambda:0)
for numb in numbs:
eqsize[numb]+=1
sets = []
for numb in eqsize:
sets.append(eqsize[numb])
parts = 1
for s in sets:
parts*=bellman(s)
parts%=MOD
print(parts)
```
| 9,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
m, n = input().split()
m = int(m)
n = int(n)
nums = set()
mostaghel = [(1 << m) - 1]
for _ in range(0, n):
x = int(input(), 2)
complement = (1 << m) - 1 - x
newmos = set()
for a in mostaghel:
if a & x == a:
newmos.update({a})
continue
if a & complement == a:
newmos.update({a})
continue
firstpart = a & x
secondpart = a & complement
newmos.update({firstpart, secondpart})
mostaghel = list(newmos)
Bellnums = [1, 1, 2, 5]
CNR = [[1], [1, 1]]
def getCNR(s, t):
if s < t:
return 0
elif t < 0:
return 0
else:
return CNR[s][t]
for a in range(2, m):
CNR.append([])
for b in range(0, a + 1):
CNR[a].append(getCNR(a-1, b-1) + getCNR(a-1, b))
for x in range(4, m + 1):
temp = 0
for y in range(0, x):
temp += getCNR(x - 1, y) * Bellnums[y]
Bellnums.append(temp)
result = 1
for x in mostaghel:
size = 0
temp = x
for s in range(0, m):
size += (x % 2)
x >>= 1
result *= Bellnums[size]
print(size)
print(result)
```
No
| 9,638 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
from collections import defaultdict as di
MOD = int(1e9+7)
bells = di(int)
bells[0,0] = 1
K=60
for j in range(1,K):
bells[0,j] = bells[j-1,j-1]
for i in range(j):
bells[i+1,j] = (bells[i,j] + bells[i,j-1])%MOD
def bellman(n):
return bells[n-1,n-1]
m,n = [int(x) for x in input().split()]
Tlist = []
for _ in range(n):
Tlist.append(input())
numbs = []
for i in range(m):
numb = []
for j in range(n):
numb.append(Tlist[j][i])
numbs.append(int(''.join(numb),2))
eqsize = di(lambda:0)
for numb in numbs:
eqsize[numb]+=1
sets = []
for numb in eqsize:
sets.append(eqsize[numb])
parts = 1
for s in sets:
parts*=bellman(s)
parts%=MOD
print(parts)
```
No
| 9,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer m.
Let M = 2m - 1.
You are also given a set of n integers denoted as the set T. The integers will be provided in base 2 as n binary strings of length m.
A set of integers S is called "good" if the following hold.
1. If <image>, then <image>.
2. If <image>, then <image>
3. <image>
4. All elements of S are less than or equal to M.
Here, <image> and <image> refer to the bitwise XOR and bitwise AND operators, respectively.
Count the number of good sets S, modulo 109 + 7.
Input
The first line will contain two integers m and n (1 ≤ m ≤ 1 000, 1 ≤ n ≤ min(2m, 50)).
The next n lines will contain the elements of T. Each line will contain exactly m zeros and ones. Elements of T will be distinct.
Output
Print a single integer, the number of good sets modulo 109 + 7.
Examples
Input
5 3
11010
00101
11000
Output
4
Input
30 2
010101010101010010101010101010
110110110110110011011011011011
Output
860616440
Note
An example of a valid set S is {00000, 00101, 00010, 00111, 11000, 11010, 11101, 11111}.
Submitted Solution:
```
m, n = input().split()
m = int(m)
n = int(n)
nums = set()
mostaghel = [(1 << m) - 1]
for _ in range(0, n):
x = int(input(), 2)
complement = (1 << m) - 1 - x
newmos = set()
for a in mostaghel:
if a & x == a:
newmos.update({a})
continue
if a & complement == a:
newmos.update({a})
continue
firstpart = a & x
secondpart = a & complement
newmos.update({firstpart, secondpart})
mostaghel = list(newmos)
Bellnums = [1, 1, 2, 5]
CNR = [[1], [1, 1]]
def getCNR(s, t):
if s < t:
return 0
elif t < 0:
return 0
else:
return CNR[s][t]
for a in range(2, m):
CNR.append([])
for b in range(0, a + 1):
CNR[a].append(getCNR(a-1, b-1) + getCNR(a-1, b))
for x in range(4, m + 1):
temp = 0
for y in range(0, x):
temp += getCNR(x - 1, y) * Bellnums[y]
Bellnums.append(temp)
result = 1
for x in mostaghel:
size = 0
temp = x
for s in range(0, m):
size += (x % 2)
x >>= 1
result *= Bellnums[size]
print(result)
```
No
| 9,640 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of n walruses in the queue his displeasure.
Input
The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109).
Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.
Output
Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.
Examples
Input
6
10 8 5 3 50 45
Output
2 1 0 -1 0 -1
Input
7
10 4 6 3 2 8 15
Output
4 2 1 0 -1 -1 -1
Input
5
10 3 1 10 11
Output
1 0 -1 -1 -1
Tags: binary search, data structures
Correct Solution:
```
from typing import TypeVar, Generic, Callable, List
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
T = TypeVar('T')
class SegmentTree(Generic[T]):
__slots__ = ["size", "tree", "identity", "op", "update_op"]
def __init__(self, size: int, identity: T, op: Callable[[T, T], T],
update_op: Callable[[T, T], T]) -> None:
self.size = size
self.tree = [identity] * (size * 2)
self.identity = identity
self.op = op
self.update_op = update_op
def build(self, a: List[T]) -> None:
tree = self.tree
tree[self.size:self.size + len(a)] = a
for i in range(self.size - 1, 0, -1):
tree[i] = self.op(tree[i << 1], tree[(i << 1) + 1])
def find(self, left: int, right: int) -> T:
left += self.size
right += self.size
tree, result, op = self.tree, self.identity, self.op
while left < right:
if left & 1:
result = op(tree[left], result)
left += 1
if right & 1:
result = op(tree[right - 1], result)
left, right = left >> 1, right >> 1
return result
def update(self, i: int, value: T) -> None:
op, tree = self.op, self.tree
i = self.size + i
tree[i] = self.update_op(tree[i], value)
while i > 1:
i >>= 1
tree[i] = op(tree[i << 1], tree[(i << 1) + 1])
n = int(input())
a = tuple(map(int, input().split()))
comp_dict = {x: i for i, x in enumerate(sorted(a), start=1)}
segt = SegmentTree[int](n + 10, -1, max, max)
ans = [-1] * n
for i, x in zip(range(n - 1, -1, -1), reversed(a)):
res = segt.find(0, comp_dict[x])
if res != -1:
ans[i] = res - i - 1
segt.update(comp_dict[x], i)
print(*ans)
```
| 9,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of n walruses in the queue his displeasure.
Input
The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109).
Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.
Output
Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.
Examples
Input
6
10 8 5 3 50 45
Output
2 1 0 -1 0 -1
Input
7
10 4 6 3 2 8 15
Output
4 2 1 0 -1 -1 -1
Input
5
10 3 1 10 11
Output
1 0 -1 -1 -1
Tags: binary search, data structures
Correct Solution:
```
from collections import *
from sys import stdin
from copy import deepcopy
def arr_enu():
return [[n - i, int(x)] for i, x in enumerate(stdin.readline().split())]
def min_arr(a):
arr = deque(sorted(deepcopy(a), key=lambda x: x[1]))
tem = deepcopy(arr)
arr.appendleft([float('inf'), 0])
for i in range(1, n + 1):
arr[i][0] = min(arr[i][0], arr[i - 1][0])
arr.popleft()
return {tem[i][0]: arr[i][0] for i in range(n)}
n = int(input())
a = arr_enu()
mem, ans = min_arr(a), []
for i, j in a:
ans.append(str(i - mem[i] - 1))
print(' '.join(ans))
```
| 9,642 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of n walruses in the queue his displeasure.
Input
The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109).
Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.
Output
Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.
Examples
Input
6
10 8 5 3 50 45
Output
2 1 0 -1 0 -1
Input
7
10 4 6 3 2 8 15
Output
4 2 1 0 -1 -1 -1
Input
5
10 3 1 10 11
Output
1 0 -1 -1 -1
Tags: binary search, data structures
Correct Solution:
```
from bisect import bisect_left
n = int(input())
a = list(map(int, input().split()))
b = [0] * n
for i in range(n - 1, -1, -1):
b[i] = bisect_left(a, a[i], i + 1, len(a)) - i - 2
a[i] = min(a[i + 1], a[i]) if i != n - 1 else a[i]
print (*b)
# Made By Mostafa_Khaled
```
| 9,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
There are n walruses standing in a queue in an airport. They are numbered starting from the queue's tail: the 1-st walrus stands at the end of the queue and the n-th walrus stands at the beginning of the queue. The i-th walrus has the age equal to ai.
The i-th walrus becomes displeased if there's a younger walrus standing in front of him, that is, if exists such j (i < j), that ai > aj. The displeasure of the i-th walrus is equal to the number of walruses between him and the furthest walrus ahead of him, which is younger than the i-th one. That is, the further that young walrus stands from him, the stronger the displeasure is.
The airport manager asked you to count for each of n walruses in the queue his displeasure.
Input
The first line contains an integer n (2 ≤ n ≤ 105) — the number of walruses in the queue. The second line contains integers ai (1 ≤ ai ≤ 109).
Note that some walruses can have the same age but for the displeasure to emerge the walrus that is closer to the head of the queue needs to be strictly younger than the other one.
Output
Print n numbers: if the i-th walrus is pleased with everything, print "-1" (without the quotes). Otherwise, print the i-th walrus's displeasure: the number of other walruses that stand between him and the furthest from him younger walrus.
Examples
Input
6
10 8 5 3 50 45
Output
2 1 0 -1 0 -1
Input
7
10 4 6 3 2 8 15
Output
4 2 1 0 -1 -1 -1
Input
5
10 3 1 10 11
Output
1 0 -1 -1 -1
Tags: binary search, data structures
Correct Solution:
```
n = int(input())
a = [int(x) for x in input().split(' ')]
INF = 1<<30
mn = [INF] * n
for i in range(n - 1, -1, -1):
mn[i] = min(a[i], mn[i + 1] if i + 1 < n else INF)
# print(mn)
for i in range(n):
l = i
r = n - 1
while l < r:
mid = r - (r - l) // 2
if (mn[mid] >= a[i]): r = mid - 1
else: l = mid
print(l - i - 1, end=' ')
```
| 9,644 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
Examples
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
Note
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Tags: data structures, dfs and similar, graphs, greedy, trees
Correct Solution:
```
from sys import stdin
from collections import defaultdict
import heapq
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]
def dfs_from(root):
depth = defaultdict(int)
child = {}
parent = defaultdict(lambda: -1)
stack = [root]
visited = [False for _ in range(n)]
while len(stack) > 0:
crt = stack[-1]
if visited[crt]:
stack.pop(-1)
if len(a[crt]) > 1: # not a leaf
child[crt], depth[crt] = max([(c, depth[c]+1) for c in a[crt]
if c != parent[crt]],
key=lambda x: x[1])
else:
child[crt] = -1
depth[crt] = 0
continue
visited[crt] = True
for next in a[crt]:
if next != parent[crt]:
stack.append(next)
parent[next] = crt
return depth, child
first_choice = leaves[0]
d1, child1 = dfs_from(first_choice)
root = max([(a[leaf][0], d1[a[leaf][0]]) for leaf in leaves],
key=lambda leaf_depth: leaf_depth[1])[0]
while child1[root] != -1:
root = child1[root]
depth, child = dfs_from(root)
solution = [1]
pq = []
for k, v in depth.items():
heapq.heappush(pq, (-v, k))
seen = [False for _ in range(n)]
seen[root] = True
while len(pq) > 0:
_, best = heapq.heappop(pq)
if seen[best]:
continue
path = []
c = best
s = 0
while c != -1:
seen[c] = True
c = child[c]
s = s+1
s = s + solution[-1]
solution.append(s)
for _ in range(n - min(len(solution), n)):
solution.append(n)
print(' '.join([str(s) for s in solution]))
```
| 9,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
Examples
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
Note
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
import heapq
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]
def dfs_from(root):
depth = defaultdict(int)
child = {}
stack = [root]
visited = set()
while len(stack) > 0:
crt = stack[-1]
if crt in visited:
stack.pop(-1)
if len(a[crt]) > 1: # not a leaf
child[crt], depth[crt] = max([(c, depth[c]+1) for c in a[crt]
if c in child.keys()],
key=lambda x: x[1])
else:
child[crt] = -1
depth[crt] = 0
continue
visited.add(crt)
for next in a[crt]:
if next not in visited:
stack.append(next)
return depth, child
first_choice = leaves[0]
d1, _ = dfs_from(first_choice)
root = max([(leaf, d1[a[leaf][0]]) for leaf in leaves],
key=lambda leaf_depth: leaf_depth[1])[0]
depth, child = dfs_from(root)
solution = [1]
depth.pop(root)
pq = []
for k, v in depth.items():
heapq.heappush(pq, (-v, k))
while len(pq) > 0:
_, best = heapq.heappop(pq)
path = []
c = best
s = 0
while c != -1:
path.append(c)
c = child[c]
s = s+1
pq = [(d, x) for d, x in pq if x not in path]
heapq.heapify(pq)
s = s + solution[-1]
solution.append(s)
for _ in range(n - min(len(solution), n)):
solution.append(n)
print(' '.join([str(s) for s in solution]))
```
No
| 9,646 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
Examples
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
Note
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Submitted Solution:
```
from sys import stdin
from collections import defaultdict
import heapq
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]
def dfs_from(root):
depth = defaultdict(int)
child = {}
parent = defaultdict(lambda: -1)
stack = [root]
visited = [False for _ in range(n)]
while len(stack) > 0:
crt = stack[-1]
if visited[crt]:
stack.pop(-1)
if len(a[crt]) > 1: # not a leaf
child[crt], depth[crt] = max([(c, depth[c]+1) for c in a[crt]
if c != parent[crt]],
key=lambda x: x[1])
else:
child[crt] = -1
depth[crt] = 0
continue
visited[crt] = True
for next in a[crt]:
if next != parent[crt]:
stack.append(next)
parent[next] = crt
return depth, child
first_choice = leaves[0]
d1, child1 = dfs_from(first_choice)
root = max([(leaf, d1[a[leaf][0]]) for leaf in leaves],
key=lambda leaf_depth: leaf_depth[1])[0]
while child1[root] != -1:
root = child1[root]
depth, child = dfs_from(root)
solution = [1]
pq = []
for k, v in depth.items():
heapq.heappush(pq, (-v, k))
seen = [False for _ in range(n)]
seen[root] = True
while len(pq) > 0:
_, best = heapq.heappop(pq)
if seen[best]:
continue
path = []
c = best
s = 0
while c != -1:
seen[c] = True
c = child[c]
s = s+1
s = s + solution[-1]
solution.append(s)
for _ in range(n - min(len(solution), n)):
solution.append(n)
print(' '.join([str(s) for s in solution]))
```
No
| 9,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
Examples
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
Note
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Submitted Solution:
```
from sys import stdin
from copy import deepcopy
n = int(stdin.readline())
a = [[] for _ in range(n)]
for _ in range(n-1):
e = stdin.readline().split(' ')
u, v = int(e[0]), int(e[1])
a[u-1].append(v-1)
a[v-1].append(u-1)
leaves = [i for i in range(n) if len(a[i]) == 1]
root = leaves[0]
sp = []
stack = [root]
visited = []
while len(stack) > 0:
crt = stack[-1]
if crt in visited:
stack.pop(-1)
assert crt == visited[-1]
visited.pop(-1)
continue
for next in a[crt]:
if next not in visited:
stack.append(next)
visited.append(crt)
if crt in leaves and crt != root:
sp.append(set(visited))
solution = [1]
for p in sp:
p = p.remove(root)
for _ in range(len(leaves)-1):
longest = max(sp, key=lambda x: len(x))
interm = solution[-1]
solution.append(interm + len(longest))
sp = [p.difference(longest) for p in sp]
for _ in range(n - min(len(solution), n)):
solution.append(n)
print(' '.join([str(s) for s in solution]))
```
No
| 9,648 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Resistance is trying to take control over as many planets of a particular solar system as possible. Princess Heidi is in charge of the fleet, and she must send ships to some planets in order to maximize the number of controlled planets.
The Galaxy contains N planets, connected by bidirectional hyperspace tunnels in such a way that there is a unique path between every pair of the planets.
A planet is controlled by the Resistance if there is a Resistance ship in its orbit, or if the planet lies on the shortest path between some two planets that have Resistance ships in their orbits.
Heidi has not yet made up her mind as to how many ships to use. Therefore, she is asking you to compute, for every K = 1, 2, 3, ..., N, the maximum number of planets that can be controlled with a fleet consisting of K ships.
Input
The first line of the input contains an integer N (1 ≤ N ≤ 105) – the number of planets in the galaxy.
The next N - 1 lines describe the hyperspace tunnels between the planets. Each of the N - 1 lines contains two space-separated integers u and v (1 ≤ u, v ≤ N) indicating that there is a bidirectional hyperspace tunnel between the planets u and v. It is guaranteed that every two planets are connected by a path of tunnels, and that each tunnel connects a different pair of planets.
Output
On a single line, print N space-separated integers. The K-th number should correspond to the maximum number of planets that can be controlled by the Resistance using a fleet of K ships.
Examples
Input
3
1 2
2 3
Output
1 3 3
Input
4
1 2
3 2
4 2
Output
1 3 4 4
Note
Consider the first example. If K = 1, then Heidi can only send one ship to some planet and control it. However, for K ≥ 2, sending ships to planets 1 and 3 will allow the Resistance to control all planets.
Submitted Solution:
```
import sys
n = int(input())
a = []
c = 0
result = []
for i in range(n-1):
temp = list(map(int, input().split()))
a.append(sorted(temp))
for i in range(n-1):
j = i
while(j<=n-3):
if a[i][1]!=a[j+1][0]:
break
else:
c+=1
j+=1
result.append(1)
for i in range(2, n+1):
if i==2 and (n==2 or (n>=3 and c==0)):
result.append(2)
continue
if i==2 and n>=3 and c!=0:
result.append(3)
continue
if i<=c:
res = min(i*3, n)
else:
res = min(n, (c*3)+(i-c))
result.append(res)
print(" ".join([str(i) for i in result]))
```
No
| 9,649 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
from typing import Callable, List, Union
T = Union[int, str]
class SegmentTree:
"""Segment Tree"""
__slots__ = ["e", "op", "_n", "_size", "tree"]
def __init__(self, initial_values: List[T], e: T, op: Callable[[T, T], T]) -> None:
self.e = e
self.op = op
self._n = len(initial_values)
self._size = 1 << (self._n - 1).bit_length()
self.tree = [e] * self._size + initial_values + [e] * (self._size - self._n)
for i in range(self._size - 1, 0, -1):
self._update(i)
def _update(self, k: int) -> None:
self.tree[k] = self.op(self.tree[2 * k], self.tree[2 * k + 1])
def get(self, k: int) -> T:
assert 0 <= k < self._n
return self.tree[k + self._size]
def set(self, k: int, x: T) -> None:
assert 0 <= k < self._n
k += self._size
self.tree[k] = x
while k:
k >>= 1
self._update(k)
def prod(self, l: int, r: int) -> T:
assert 0 <= l <= r <= self._n
sml, smr = self.e, self.e
l += self._size
r += self._size
while l < r:
if l & 1:
sml = self.op(sml, self.tree[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.tree[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def prod_all(self) -> T:
return self.tree[1]
def max_right(self, l: int, f: Callable[[T], bool]) -> int:
assert 0 <= l <= self._n
assert f(self.e)
if l == self._n:
return self._n
l += self._size
sm = self.e
while True:
while not l & 1:
l >>= 1
if not f(self.op(sm, self.tree[l])):
while l < self._size:
l *= 2
if f(self.op(sm, self.tree[l])):
sm = self.op(sm, self.tree[l])
l += 1
return l - self._size
sm = self.op(sm, self.tree[l])
l += 1
if (l & -l) == l:
break
return self._n
def min_left(self, r: int, f: Callable[[T], bool]) -> int:
assert 0 <= r <= self._n
assert f(self.e)
if not r:
return 0
r += self._size
sm = self.e
while True:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not f(self.op(self.tree[r], sm)):
while r < self._size:
r = 2 * r + 1
if f(self.op(self.tree[r], sm)):
sm = self.op(self.tree[r], sm)
r -= 1
return r + 1 - self._size
if (r & -r) == r:
break
return 0
def practice2_j():
N, _, *AQ = map(int, open(0).read().split())
A, Q = AQ[:N], AQ[N:]
tree = SegmentTree(A, -1, max)
res = []
for t, x, y in zip(*[iter(Q)] * 3):
if t == 1:
tree.set(x - 1, y)
elif t == 2:
res.append(tree.prod(x - 1, y))
else:
res.append(tree.max_right(x - 1, lambda n: n < y) + 1)
print("\n".join(map(str, res)))
if __name__ == "__main__":
practice2_j()
```
| 9,650 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
def segfunc(x, y):
return max(x, y)
def init(init_val):
for i in range(n):
seg[i + num - 1] = init_val[i]
for i in range(num - 2, -1, -1):
seg[i] = segfunc(seg[2 * i + 1], seg[2 * i + 2])
def update(k, x):
k += num - 1
seg[k] = x
while k:
k = (k - 1) // 2
seg[k] = segfunc(seg[k * 2 + 1], seg[k * 2 + 2])
def query(p, q):
if q <= p:
return ide_ele
p += num - 1
q += num - 2
res = ide_ele
while q - p > 1:
if p & 1 == 0:
res = segfunc(res, seg[p])
if q & 1 == 1:
res = segfunc(res, seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = segfunc(res, seg[p])
else:
res = segfunc(segfunc(res, seg[p]), seg[q])
return res
# seg tree初期値 (単位元)
n = N
ide_ele = 0
num = 2 ** (n - 1).bit_length()
seg = [ide_ele] * 2 * num
init(A)
def isOK(mid, m, value):
a = query(m, mid)
return a >= value
B = A[::]
for _ in range(Q):
T, X, V = [int(x) for x in input().split()]
if T == 1:
update(X - 1, V)
B[X - 1] = V
elif T == 2:
print(query(X - 1, V))
else:
a = query(X - 1, N)
if a < V:
print(N + 1)
else:
if B[X - 1] >= V:
print(X)
continue
ok = N
ng = X
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, X - 1, V):
ok = mid
else:
ng = mid
print(ok)
if __name__ == '__main__':
main()
```
| 9,651 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
from typing import Callable, List, Union
T = Union[int, str]
class SegmentTree:
"""Segment Tree"""
__slots__ = ["_n", "_log", "_size", "op", "e", "tree"]
def __init__(self, initial_values: List[T], op: Callable[[T, T], T], e: T) -> None:
self._n = len(initial_values)
self._log = (self._n - 1).bit_length()
self._size = 1 << self._log
self.op = op
self.e = e
self.tree = [e] * 2 * self._size
for i, a in enumerate(initial_values, self._size):
self.tree[i] = a
for i in range(self._size - 1, 0, -1):
self._update(i)
def _update(self, k: int) -> None:
self.tree[k] = self.op(self.tree[2 * k], self.tree[2 * k + 1])
def set(self, p: int, x: T) -> None:
assert 0 <= p < self._n
p += self._size
self.tree[p] = x
for i in range(1, self._log + 1):
self._update(p >> i)
def prod(self, l: int, r: int) -> T:
assert 0 <= l <= r <= self._n
sml, smr = self.e, self.e
l += self._size
r += self._size
while l < r:
if l & 1:
sml = self.op(sml, self.tree[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.tree[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
@property
def all_prod(self) -> T:
return self.tree[1]
def max_right(self, l: int, f: Callable[[T], bool]) -> int:
assert 0 <= l <= self._n
assert f(self.e)
if l == self._n:
return self._n
l += self._size
sm = self.e
while True:
while not l & 1:
l >>= 1
if not f(self.op(sm, self.tree[l])):
while l < self._size:
l *= 2
if f(self.op(sm, self.tree[l])):
sm = self.op(sm, self.tree[l])
l += 1
return l - self._size
sm = self.op(sm, self.tree[l])
l += 1
if (l & -l) == l:
break
return self._n
def min_left(self, r: int, f: Callable[[T], bool]) -> int:
assert 0 <= r <= self._n
assert f(self.e)
if not r:
return 0
r += self._size
sm = self.e
while True:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not f(self.op(self.tree[r], sm)):
while r < self._size:
r = 2 * r + 1
if f(self.op(self.tree[r], sm)):
sm = self.op(self.tree[r], sm)
r -= 1
return r + 1 - self._size
if (r & -r) == r:
break
return 0
def practice2_j():
N, _, *AQ = map(int, open(0).read().split())
A, Q = AQ[:N], AQ[N:]
tree = SegmentTree(A, max, -1)
res = []
for t, x, y in zip(*[iter(Q)] * 3):
if t == 1:
tree.set(x - 1, y)
elif t == 2:
res.append(tree.prod(x - 1, y))
else:
res.append(tree.max_right(x - 1, lambda n: n < y) + 1)
print("\n".join(map(str, res)))
if __name__ == "__main__":
practice2_j()
```
| 9,652 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
# SegmentTree
class SegmentTree:
def __init__(self,n,p,unit,f):
self.num=2**((n-1).bit_length())
self.seg=[unit]*(2*self.num)
for i in range(n):self.seg[i+self.num]=p[i]
for i in range(self.num-1,0,-1):
self.seg[i]=f(self.seg[i<<1],self.seg[(i<<1)+1])
self.f=f
self.unit=unit
def update(self,i,x):
i+=self.num
self.seg[i]=x
while i:
i>>=1
self.seg[i]=self.f(self.seg[i<<1],self.seg[(i<<1)+1])
def query(self,l,r):
ansl=ansr=self.unit
l+=self.num
r+=self.num-1
if l==r:
return self.seg[l]
f=self.f
while l<r:
if l&1:
ansl=f(ansl,self.seg[l])
l+=1
if ~r&1:
ansr=f(self.seg[r],ansr)
r-=1
l>>=1
r>>=1
if l==r:
ansl=f(ansl,self.seg[l])
return f(ansl,ansr)
n,q=map(int,input().split())
a=list(map(int,input().split()))
f=lambda x,y: max(x,y)
seg=SegmentTree(n,a,0,f)
for _ in range(q):
t,a,b=map(int,input().split())
if t==1:
seg.update(a-1,b)
if t==2:
print(seg.query(a-1,b))
if t==3:
ng=a-1
ok=n+1
while ng+1!=ok:
mid=(ng+ok)//2
if seg.query(ng,mid)>=b:ok=mid
else:ng=mid
print(ok)
```
| 9,653 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
"""
セグメント木
func:二項演算の関数(モノイドである必要あり)
e:単位元(モノイドにおける)
update, find, bisect, 全てにおいて, 1-indexとなっている。
(大抵の場合、Atcoderの問題文の表記のままの値を、メソッドに代入すれば良い)
"""
class SegmentTree:
def __init__(self, n, func, e, arrange=None):
self.init(n)
self.func = func
self.e = e
self.make_arrange(arrange)
def init(self, n):
self.inf = pow(2, 32)
self.n = n
self.N = 1
while self.N < self.n:
self.N *= 2
self.size = self.N * 2
def make_arrange(self, arrange):
self.set_arrange(arrange)
self.construct(arrange)
def set_arrange(self, arrange):
if arrange == None:
self.segment = [self.e]*(self.size)
return
self.segment = [0]*(self.N) + arrange + [self.e]*(self.size-self.N-self.n)
def construct(self, arrange):
if arrange == None:
return
for i in range(self.N-1, 0, -1):
self.segment[i] = self.func(self.segment[2*i], self.segment[2*i+1])
def update(self, i, x):
i += (self.N - 1)
self.segment[i] = x
while i > 1:
i = i//2
self.segment[i] = self.func(self.segment[2*i], self.segment[2*i+1])
def count(self, l, r):
res = self.e
l += self.N-1
r += self.N
while r > l:
if l & 1:
res = self.func(res, self.segment[l])
l += 1
if r & 1:
r -= 1
res = self.func(res, self.segment[r])
l >>= 1
r >>= 1
return res
def bisect_sub(self, a, b, k, l, r, x):
if r <= a or b <= l:
return b+1
if self.segment[k] < x:
return b+1
if k >= self.N:
return r
find_l = self.bisect_sub(a, b, 2*k, l, (l+r)//2, x)
if find_l <= b:
return find_l
find_r = self.bisect_sub(a, b, 2*k+1, (l+r)//2, r, x)
return find_r
def bisect(self, l, r, x):
return self.bisect_sub(l-1, r, 1, 0, self.size-self.N, x)
def main():
n, q = map(int, input().split())
p = list(map(int, input().split()))
seg = SegmentTree(n, max, 0, arrange=p)
res = []
for i in range(q):
a, b, c = list(map(int, input().split()))
if a == 1:
seg.update(b, c)
elif a == 2:
ans = seg.count(b, c)
res.append(ans)
else:
ans = seg.bisect(b, n, c)
res.append(ans)
print(*res, sep="\n")
if __name__ == "__main__":
main()
```
| 9,654 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
class RMaxQ:
__slots__ = ["n", "data"]
def __init__(self, li):
self.n = len(li)
self.data = li*2
for i in range(self.n - 1, 0, -1):
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def update(self, i, a):
i += self.n
self.data[i] = a
while i > 1:
i //= 2
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def add(self, i, a):
i += self.n
self.data[i] += a
while i > 1:
i //= 2
self.data[i] = max(self.data[2*i], self.data[2*i+1])
def fold(self, l, r):
l += self.n
r += self.n
res = 0
while l < r:
if l % 2:
res = max(self.data[l], res)
l += 1
if r % 2:
r -= 1
res = max(res, self.data[r])
l //= 2
r //= 2
return res
import sys
input = sys.stdin.readline
n, q = map(int, input().split())
A = list(map(int, input().split()))
seg = RMaxQ(A)
for _ in range(q):
t, x, v = map(int, input().split())
x -= 1
if t == 1:
seg.update(x, v)
elif t == 2:
print(seg.fold(x, v))
else:
ng = x
ok = n+1
while ok - ng > 1:
mid = (ok+ng)//2
if seg.fold(x, mid) >= v:
ok = mid
else:
ng = mid
print(ok)
```
| 9,655 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
class LazySegmentTree():
def __init__(self, n, op, e, mapping, composition, id):
self.n = n
self.op = op
self.e = e
self.mapping = mapping
self.composition = composition
self.id = id
self.log = (n - 1).bit_length()
self.size = 1 << self.log
self.d = [e] * (2 * self.size)
self.lz = [id] * (self.size)
def update(self, k):
self.d[k] = self.op(self.d[2 * k], self.d[2 * k + 1])
def all_apply(self, k, f):
self.d[k] = self.mapping(f, self.d[k])
if k < self.size:
self.lz[k] = self.composition(f, self.lz[k])
def push(self, k):
self.all_apply(2 * k, self.lz[k])
self.all_apply(2 * k + 1, self.lz[k])
self.lz[k] = self.id
def build(self, arr):
#assert len(arr) == self.n
for i, a in enumerate(arr):
self.d[self.size + i] = a
for i in range(1, self.size)[::-1]:
self.update(i)
def set(self, p, x):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = x
for i in range(1, self.log + 1):
self.update(p >> i)
def get(self, p):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1):
self.push(p >> i)
return self.d[p]
def prod(self, l, r):
#assert 0 <= l <= r <= self.n
if l == r: return self.e
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push(r >> i)
sml = smr = self.e
while l < r:
if l & 1:
sml = self.op(sml, self.d[l])
l += 1
if r & 1:
r -= 1
smr = self.op(self.d[r], smr)
l >>= 1
r >>= 1
return self.op(sml, smr)
def all_prod(self):
return self.d[1]
def apply(self, p, f):
#assert 0 <= p < self.n
p += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(p >> i)
self.d[p] = self.mapping(f, self.d[p])
for i in range(1, self.log + 1):
self.update(p >> i)
def range_apply(self, l, r, f):
#assert 0 <= l <= r <= self.n
if l == r: return
l += self.size
r += self.size
for i in range(1, self.log + 1)[::-1]:
if ((l >> i) << i) != l: self.push(l >> i)
if ((r >> i) << i) != r: self.push((r - 1) >> i)
l2 = l
r2 = r
while l < r:
if l & 1:
self.all_apply(l, f)
l += 1
if r & 1:
r -= 1
self.all_apply(r, f)
l >>= 1
r >>= 1
l = l2
r = r2
for i in range(1, self.log + 1):
if ((l >> i) << i) != l: self.update(l >> i)
if ((r >> i) << i) != r: self.update((r - 1) >> i)
def max_right(self, l, g):
#assert 0 <= l <= self.n
#assert g(self.e)
if l == self.n: return self.n
l += self.size
for i in range(1, self.log + 1)[::-1]:
self.push(l >> i)
sm = self.e
while True:
while l % 2 == 0: l >>= 1
if not g(self.op(sm, self.d[l])):
while l < self.size:
self.push(l)
l = 2 * l
if g(self.op(sm, self.d[l])):
sm = self.op(sm, self.d[l])
l += 1
return l - self.size
sm = self.op(sm, self.d[l])
l += 1
if (l & -l) == l: return self.n
def min_left(self, r, g):
#assert 0 <= r <= self.n
#assert g(self.e)
if r == 0: return 0
r += self.size
for i in range(1, self.log + 1)[::-1]:
self.push((r - 1) >> i)
sm = self.e
while True:
r -= 1
while r > 1 and r % 2: r >>= 1
if not g(self.op(self.d[r], sm)):
while r < self.size:
self.push(r)
r = 2 * r + 1
if g(self.op(self.d[r], sm)):
sm = self.op(self.d[r], sm)
r -= 1
return r + 1 - self.size
sm = self.op(self.d[r], sm)
if (r & -r) == r: return 0
import sys
input = sys.stdin.buffer.readline
N, Q = map(int, input().split())
A = tuple(map(int, input().split()))
eq = lambda x, y: y
lst = LazySegmentTree(N, max, 0, eq, eq, 0)
lst.build(A)
res = []
for _ in range(Q):
t, x, y = map(int, input().split())
if t == 1:
lst.set(x - 1, y)
elif t == 2:
res.append(lst.prod(x - 1, y))
else:
res.append(lst.max_right(x - 1, lambda z: z < y) + 1)
print('\n'.join(map(str, res)))
```
| 9,656 |
Provide a correct Python 3 solution for this coding contest problem.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
"Correct Solution:
```
class segment_tree:
__slots__ = ["op_M", "e_M","N","N0","dat"]
def __init__(self, N, operator_M, e_M):
self.op_M = operator_M
self.e_M = e_M
self.N = N
self.N0 = 1<<(N-1).bit_length()
self.dat = [self.e_M]*(2*self.N0)
# 長さNの配列 initial で初期化
def build(self, initial):
self.dat[self.N0:self.N0+len(initial)] = initial[:]
for k in range(self.N0-1,0,-1):
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
# a_k の値を x に更新
def update(self,k,x):
k += self.N0
self.dat[k] = x
k >>= 1
while k:
self.dat[k] = self.op_M(self.dat[2*k], self.dat[2*k+1])
k >>= 1
# 区間[L,R]をopでまとめる
def query(self,L,R):
L += self.N0; R += self.N0 + 1
sl = sr = self.e_M
while L < R:
if R & 1:
R -= 1
sr = self.op_M(self.dat[R],sr)
if L & 1:
sl = self.op_M(sl,self.dat[L])
L += 1
L >>= 1; R >>= 1
return self.op_M(sl,sr)
def get(self, k): #k番目の値を取得。query[k,k]と同じ
return self.dat[k+self.N0]
"""
f(x_l*...*x_{r-1}) が True になる最大の r
つまり TTTTFFFF となるとき、F となる最小の添え字
存在しない場合 n が返る
f(e_M) = True でないと壊れる
"""
def max_right(self,l,f):
if l == self.N: return self.N;
l += self.N0
sm = self.e_M
while True:
while l&1==0:
l >>= 1
if not f(self.op_M(sm,self.dat[l])):
while l < self.N0:
l *= 2
if f(self.op_M(sm,self.dat[l])):
sm = self.op_M(sm,self.dat[l])
l += 1
return l - self.N0
sm = self.op_M(sm,self.dat[l])
l += 1
if (l & -l) == l: break
return self.N
"""
f(x_l*...*x_{r-1}) が True になる最小の l
つまり FFFFTTTT となるとき、T となる最小の添え字
存在しない場合 r が返る
f(e_M) = True でないと壊れる
"""
def min_left(self,r,f):
if r == 0: return 0
r += self.N0
sm = self.e_M
while True:
r -= 1
while r > 1 and r&1:
r >>= 1
if not f(self.op_M(self.dat[r],sm)):
while r < self.N0:
r = r*2 + 1
if f(self.op_M(self.dat[r],sm)):
sm = self.op_M(self.dat[r],sm)
r -= 1
return r + 1 - self.N0
sm = self.op_M(self.dat[r],sm)
if (r & -r) == r: break
return 0
###########################################
import sys
readline = sys.stdin.readline
n,q = map(int, readline().split())
*a, = map(int, readline().split())
seg = segment_tree(n,max,0)
seg.build(a)
for _ in range(q):
idx,p,v = map(int, readline().split())
if idx==1:
seg.update(p-1,v)
elif idx==2:
print(seg.query(p-1,v-1))
else:
print(seg.max_right(p-1,lambda x: x < v)+1)
```
| 9,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
#region bcf
# code section by Barry Fam
#
# pylint: disable= reimported
#region rangedata.py
#region hyperlist.py
import itertools
# def hyperlist(*dim, default_factory=None):
def hyperlist(*dim, **kwarg):
default_factory = kwarg.pop("default_factory", None)
ranges = [range(n) for n in dim]
h = [None]*dim[0]
for dd in range(1, len(dim)):
for u in itertools.product(*ranges[:dd]):
hyperlist_setitem(h, u, [None]*dim[dd])
if default_factory:
for u in itertools.product(*ranges):
hyperlist_setitem(h, u, default_factory())
return h
def hyperlist_setitem(h, u, a):
ptr = h
for i in u[:-1]: ptr = ptr[i]
ptr[u[-1]] = a
def hyperlist_getitem(h, u):
ptr = h
for i in u: ptr = ptr[i]
return ptr
#endregion hyperlist.py
###############################################################################
import operator
import collections
import itertools
import functools
import math as m
try: m.prod
except AttributeError:
def _prod(iterable, start=1):
for x in iterable: start *= x
return start
m.prod = _prod
# class RangeOperators:
class RangeOperators(object): # pylint: disable= useless-object-inheritance
'''
Data class to define the behavior of a range data structure
new() := factory for zero values, e.g. int()
query(a, b) := the binary query function of the tree. e.g. operator.add() for a cumulative sum
q_inverse(a, b) := the inverse of the query function, if it exists. required for a Fenwick tree
update(t, x) := define how the tree will be updated: return the new value of t if updated with x
u_distributive(t, x, w) := return the new value of t if its w leaves are updated by x. required for lazy propagation
u_commutative: bool := True if the update operation is commutative. e.g. add() is; but "set to" is not
'''
__slots__ = [
"new",
"query",
"q_inverse",
"update",
"u_distributive",
"u_commutative",
]
_defaults = dict(
new= int,
query= operator.add,
q_inverse= operator.sub,
update= operator.add,
u_distributive= lambda t, x, w: t + x*w,
u_commutative= True,
)
def __init__(self, **kwarg):
d = kwarg or self._defaults
for k, v in d.items():
setattr(self, k, v)
MAXQUERY = RangeOperators(
new= int,
query= max,
q_inverse= None,
update= operator.add,
u_distributive= lambda t, x, w: t + x,
u_commutative= True,
)
MINQUERY = RangeOperators(
new= int,
query= min,
q_inverse= None,
update= operator.add,
u_distributive= lambda t, x, w: t + x,
u_commutative= True,
)
SETUPDATE = RangeOperators(
new= int,
query= operator.add,
q_inverse= operator.sub,
update= lambda t, x: x,
u_distributive= lambda t, x, w: x*w,
u_commutative= False,
)
# class SegmentTree:
class SegmentTree(object): # pylint: disable= useless-object-inheritance
"""
SegmentTree(n: int) -> new tree of size n
SegmentTree(iterable) -> new tree, initialized
Methods:
update_point(i, value)
update_range(start, stop, value)
update_consecutive_points(start, stop, iterable)
query_point(i)
query_range(start, stop)
"""
def __init__(self, arg, sparse=False, ops=RangeOperators(), **kwarg):
# super().__init__(**kwarg)
super(SegmentTree, self).__init__(**kwarg)
try:
init = list(arg)
dim = len(init)
except TypeError:
init = None
dim = arg
self.dim = dim
self.ops = ops
self._lazy = self.ops.u_distributive is not None
self._clean = True
if sparse:
self._tree = collections.defaultdict(ops.new)
@functools.lru_cache(maxsize=dim)
def seglen(u):
if u >= self.dim: return 1
return seglen(u<<1) + seglen(u<<1|1)
self._seglen = seglen
if self._lazy:
self._pending = collections.defaultdict(lambda: None)
else:
self._tree = [ops.new() for _ in range(dim*2)]
seglen_precomp = [1]*dim*2
for u in reversed(range(1, dim)):
seglen_precomp[u] = seglen_precomp[u<<1] + seglen_precomp[u<<1|1]
self._seglen = seglen_precomp.__getitem__
if self._lazy:
self._pending = [None]*dim
if init:
self.update_consecutive_points(0, dim, init)
# Iterators
def _downward_path(self, i):
"""Iterate over tree indexes from root to just above raw index i"""
u = self.dim + i
for s in range(u.bit_length()-1, 0, -1):
yield u >> s
def _upward_path(self, i):
"""Iterate over tree indexes from just above raw index i to root"""
u = self.dim + i
while u > 1:
u >>= 1
yield u
def _downward_fill(self, i, j):
"""Iterate over every tree index that is an ancestor of raw index range [i,j), from root downwards"""
n = self.dim
l = n+i
r = n+j-1
for s in range(l.bit_length()-1, 0, -1):
for u in range(l>>s, (r>>s)+1):
yield u
def _upward_fill(self, i, j):
"""Iterate over every tree index that is an ancestor of raw index range [i,j), from just above leaves upwards"""
n = self.dim
l = n+i
r = n+j-1
while l > 1:
l >>= 1
r >>= 1
for u in reversed(range(l, r+1)):
yield u
def _cover_nodes(self, i, j):
"""Iterate over the set of tree indexes whose segments optimally cover raw index range [i,j)"""
n = self.dim
l = n+i
r = n+j
while l < r:
if l&1:
yield l
l += 1
if r&1:
r -= 1
yield r
l >>= 1
r >>= 1
# Node modification
def _lazy_update(self, u, value):
"""Update tree index u as if its child leaves had been updated with value"""
self._tree[u] = self.ops.u_distributive(self._tree[u], value, self._seglen(u))
if u < self.dim:
self._clean = False
if self._pending[u] is None:
self._pending[u] = value
else:
self._pending[u] = self.ops.update(self._pending[u], value)
def _push1(self, u):
"""Apply any pending lazy update at tree index u to its two immediate children"""
assert u < self.dim
if self._clean: return
value = self._pending[u]
if value is not None:
for v in (u<<1, u<<1|1):
self._lazy_update(v, value)
self._pending[u] = None
def _build1(self, u):
"""Calculate the query function at tree index u from its two immediate children"""
assert u < self.dim
self._push1(u)
self._tree[u] = self.ops.query(self._tree[u<<1], self._tree[u<<1|1])
# Node-set modification
def _push_path(self, i):
"""Push lazy updates from root to raw index i"""
if self._clean: return
for u in self._downward_path(i):
self._push1(u)
def _push_fill(self, i, j):
"""Push lazy updates from root to raw index range [i,j)"""
if self._clean: return
for u in self._downward_fill(i, j):
self._push1(u)
if j-i == self.dim: self._clean = True
def _build_path(self, i):
"""Update tree nodes from raw index i to root"""
for u in self._upward_path(i):
self._build1(u)
def _build_fill(self, i, j):
"""Update all tree ancestors of raw index range [i,j)"""
for u in self._upward_fill(i, j):
self._build1(u)
if j-i == self.dim: self._clean = True
# Interface
def update_consecutive_points(self, start, stop, iterable):
assert 0 <= start < stop <= self.dim
# push if necessary
if not self.ops.u_commutative:
self._push_fill(start, stop-1)
# write leaves
for u, value in zip(range(self.dim + start, self.dim + stop), iterable):
self._tree[u] = self.ops.update(self._tree[u], value)
# build
self._build_fill(start, stop-1)
def query_range(self, start, stop):
assert start < stop
for i in {start, stop-1}:
self._push_path(i)
node_values = (self._tree[u] for u in self._cover_nodes(start, stop))
return functools.reduce(self.ops.query, node_values)
def update_range(self, start, stop, value):
assert start < stop
# if no lazy propagation, fall back to writing to leaves
if not self._lazy:
self.update_consecutive_points(start, stop, itertools.repeat(value))
return
# push if necessary
if not self.ops.u_commutative:
for i in {start, stop-1}:
self._push_path(i)
# write cover nodes
for u in self._cover_nodes(start, stop):
self._lazy_update(u, value)
# build
for i in {start, stop-1}:
self._build_path(i)
def query_point(self, i):
return self.query_range(i, i+1)
def update_point(self, i, value):
self.update_range(i, i+1, value)
# class FenwickTree:
class FenwickTree(object): # pylint: disable= useless-object-inheritance
"""
ft1d = FenwickTree(dim)
ft3d = FenwickTree(dim1, dim2, dim3)
etc.
Methods:
ft1d.iadd(i, update_value)
ft3d.iadd((i,j,k), update_value)
ft1d[i] = set_value
fr3d[i,j,k] = set_value
query = ft1d[i1:i2]
query = ft3d[i1:i2, j1:j2, k1:k2]
"""
# def __init__(self, *dim, sparse=False, **kwarg):
def __init__(self, *dim, **kwarg):
sparse = kwarg.pop("sparse", False)
# super().__init__(**kwarg)
super(FenwickTree, self).__init__(**kwarg)
self.dim = dim
self.d = len(dim)
if sparse:
self._tree = collections.defaultdict(int)
if self.d > 1:
self._tree_setitem = self._tree.__setitem__
self._tree_getitem = self._tree.__getitem__
else:
self._tree = hyperlist(*dim, default_factory=int)
if self.d > 1:
self._tree_setitem = functools.partial(hyperlist_setitem, self._tree)
self._tree_getitem = functools.partial(hyperlist_getitem, self._tree)
if self.d == 1:
self.iadd = self._iadd_1d
self._getitem = self._getitem_1d
else:
self.iadd = self._iadd_dd
self._getitem = self._getitem_dd
def __setitem__(self, key, value):
self.iadd(key, value-self[key])
def __getitem__(self, key):
return self._getitem(key)
@staticmethod
def _set_index_iter(i, n):
"""Iterate over the tree indices < n which are affected when setting raw index i"""
if i == 0:
yield 0
return
while True:
yield i
i += i & -i # increment LSB
if i >= n: return
@staticmethod
def _get_index_iter(i, j):
"""
Iterate over the tree indices whose sum equals the sum over the raw range (j,i] -- note that i > j
Each index is returned as (index, sign) where sign is +1 or -1 for inclusion-exclusion
"""
if i < 0: return
if j < 0:
yield 0, +1
j = 0
while i > j:
yield i, +1
i &= i-1 # decrement LSB
while j > i:
yield j, -1
j &= j-1 # decrement LSB
def _iadd_1d(self, key, value):
assert 0 <= key < self.dim[0]
for i in self._set_index_iter(key, self.dim[0]):
self._tree[i] += value
def _iadd_dd(self, key, value):
assert len(key) == self.d
assert all(0 <= i < self.dim[dd] for dd, i in enumerate(key)), "index out of range"
index_iters = [self._set_index_iter(i, self.dim[dd]) for dd, i in enumerate(key)]
for u in itertools.product(*index_iters):
g = self._tree_getitem(u)
self._tree_setitem(u, g+value)
def _getitem_1d(self, key):
if isinstance(key, slice):
assert key.step is None
start, stop, _ = key.indices(self.dim[0])
if stop < start: stop = start
i, j = stop-1, start-1
else:
i, j = key, key-1
assert -1 <= j <= i < self.dim[0], "index out of range"
sigma = 0
for k, sign in self._get_index_iter(i, j):
sigma += sign * self._tree[k]
return sigma
def _getitem_dd(self, key):
index_iters = []
for dd, k in enumerate(key):
if isinstance(k, slice):
assert k.step is None
start, stop, _ = k.indices(self.dim[dd])
if stop < start: stop = start
itr = self._get_index_iter(stop-1, start-1)
else:
assert 0 <= k < self.dim[dd], "index out of range"
itr = self._get_index_iter(k, k-1)
index_iters.append(itr)
assert len(index_iters) == self.d, "mismatched key dimensions"
sigma = 0
for i_sign_pairs in itertools.product(*index_iters):
u, signs = zip(*i_sign_pairs)
sign = m.prod(signs)
sigma += sign * self._tree_getitem(u)
return sigma
#endregion rangedata.py
#endregion bcf
###############################################################################
#region bcf
# code section by Barry Fam
#
# pylint: disable= reimported
#region logsearch.py
import math as m
def binary_search_int(f, start, stop):
"""
Binary search for the point at which f() becomes true
f() may be evaluated at the points in [start, stop) half-open
The return value will be in the range [start, stop] inclusive
f() must be always false to the left of some point, and always true to the right
>>> f = lambda x: x > 50
>>> binary_search_int(f, 40, 91)
51
>>> binary_search_int(f, 20, 31)
31
>>> binary_search_int(f, 60, 81)
60
"""
assert start < stop
left, right = start, stop
while left < right:
mid = (left + right)//2
if f(mid):
right = mid
else:
left = mid+1
return right
def binary_search_float(f, left, right, rel_tol=1e-09, abs_tol=0.0):
"""
Binary search for the point at which f() becomes true
f() must be always false to the left of some point, and always true to the right
Note: If the return may be close to 0, set abs_tol to avoid excessive/infinite iteration
>>> f = lambda x: x >= 3.5
>>> _ = binary_search_float(f, 0, 10)
>>> round(_, 6)
3.5
"""
assert left <= right
while not m.isclose(left, right, rel_tol=rel_tol, abs_tol=abs_tol):
mid = (left + right)/2
if f(mid):
right = mid
else:
left = mid
return right
def ternary_search_int(f, start, stop):
"""
Ternary search for the maximum point of f()
df/dx must be always positive to the left of some point, and always negative to the right
>>> f = lambda x: -(x-42)**2
>>> ternary_search_int(f, 0, 100)
42
"""
assert start < stop
invphi2 = (3-m.sqrt(5)) / 2
a, d = start, stop-1
b = a + round(invphi2 * (d-a))
c = b + m.ceil(invphi2 * (d-b))
fb = f(b)
fc = f(c)
while True:
if fb < fc:
if c == d: return d
a = b+1
b, fb = c, fc
c = b + m.ceil(invphi2 * (d-b))
fc = f(c)
else:
if a == b: return a
d = c-1
c, fc = b, fb
b = c - m.ceil(invphi2 * (c-a))
fb = f(b)
def ternary_search_float(f, left, right, rel_tol=1e-09, abs_tol=0.0):
"""
Ternary search for the maximum point of f()
df/dx must be always positive to the left of some point, and always negative to the right
Note: If the return may be close to 0, set abs_tol to avoid excessive/infinite iteration
>>> f = lambda x: -(x-3.5)**2
>>> _ = ternary_search_float(f, 0, 10)
>>> round(_, 6)
3.5
"""
assert left <= right
invphi2 = (3-m.sqrt(5)) / 2
a, d = left, right
b = a + invphi2 * (d-a)
c = b + invphi2 * (d-b)
fb = f(b)
fc = f(c)
while not m.isclose(a, d, rel_tol=rel_tol, abs_tol=abs_tol):
if fb < fc:
a = b
b, fb = c, fc
c = b + invphi2 * (d-b)
fc = f(c)
else:
d = c
c, fc = b, fb
b = c - invphi2 * (c-a)
fb = f(b)
return c
# if __name__ == "__main__":
if False: # pylint: disable= using-constant-test
import doctest
doctest.testmod()
#endregion logsearch.py
#endregion bcf
###############################################################################
import sys
def input(itr=iter(sys.stdin.readlines())): # pylint: disable= redefined-builtin
return next(itr).rstrip('\n\r')
###############################################################################
N, Q = map(int, input().split())
A = list(map(int, input().split()))
setu_maxq = RangeOperators(
new= int,
query= max,
q_inverse= None,
update= lambda t, x: x,
u_distributive= lambda t, x, w: x,
u_commutative= False,
)
st = SegmentTree(A, ops=setu_maxq)
responses = []
for _ in range(Q):
T = tuple(map(int, input().split()))
if T[0] == 1:
_, X, V = T
st.update_point(X-1, V)
elif T[0] == 2:
_, L, R = T
responses.append(st.query_range(L-1, R-1+1))
elif T[0] == 3:
_, X, V = T
def valid(j):
return st.query_range(X-1, j-1+1) >= V
j = binary_search_int(valid, X, N+1)
responses.append(j)
print(*responses, sep='\n')
```
Yes
| 9,658 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class SegmentTree:
def __init__(self, init_val, segfunc, ide_ele):
n = len(init_val)
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
self.range = [(-1,n)] * 2 * self.num
# 配列の値を葉にセット
for i in range(n):
self.tree[self.num + i] = init_val[i]
self.range[self.num + i] = (i,i)
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
self.range[i] = (self.range[2 * i][0],self.range[2 * i + 1][1])
def update(self, k, x):
k += self.num
self.tree[k] = x
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
def bisect_l(self,l,r,x):
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l & 1:
if self.tree[l] >= x and Lmin==-1:
Lmin = l
l += 1
if r & 1:
if self.tree[r-1] >=x:
Rmin = r-1
l >>= 1
r >>= 1
if Lmin != -1:
pos = Lmin
while pos<self.num:
if self.tree[2 * pos] >=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
elif Rmin != -1:
pos = Rmin
while pos<self.num:
if self.tree[2 * pos] >=x:
pos = 2 * pos
else:
pos = 2 * pos +1
return pos-self.num
else:
return N
import sys
input = sys.stdin.readline
N,Q = map(int,input().split())
A = list(map(int,input().split()))
Seg = SegmentTree(A,max,0)
for _ in range(Q):
query = list(map(int,input().split()))
if query[0] == 1:
gomi,idx,val = query
Seg.update(idx-1,val)
elif query[0] == 2:
gomi,l,r = query
print(Seg.query(l-1,r))
else:
gomi,l,val = query
print(Seg.bisect_l(l-1,N,val)+1)
```
Yes
| 9,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class LazySegmentTree():
def __init__(self, n, f, g, h, ef, eh):
"""
:param n: 配列の要素数
:param f: 取得半群の元同士の積を定義
:param g: 更新半群の元 xh が配列上の実際の値にどのように作用するかを定義
:param h: 更新半群の元同士の積を定義 (更新半群の元を xh と表記)
:param x: 配列の各要素の値。treeの葉以外は xf(x1,x2,...)
"""
self.n = n
self.f = f
self.g = lambda xh, x: g(xh, x) if xh != eh else x
self.h = h
self.ef = ef
self.eh = eh
l = (self.n - 1).bit_length()
self.size = 1 << l
self.tree = [self.ef] * (self.size << 1)
self.lazy = [self.eh] * ((self.size << 1) + 1)
self.plt_cnt = 0
def built(self, array):
"""
arrayを初期値とするセグメント木を構築
"""
for i in range(self.n):
self.tree[self.size + i] = array[i]
for i in range(self.size - 1, 0, -1):
self.tree[i] = self.f(self.tree[i<<1], self.tree[(i<<1)|1])
def update(self, i, x):
"""
i 番目の要素を x に更新する
"""
i += self.size
self.propagate_lazy(i)
self.tree[i] = x
self.lazy[i] = self.eh
self.propagate_tree(i)
def get(self, i):
"""
i 番目の値を取得( 0-indexed ) ( O(logN) )
"""
i += self.size
self.propagate_lazy(i)
return self.g(self.lazy[i], self.tree[i])
def update_range(self, l, r, x):
"""
半開区間 [l, r) の各々の要素 a に op(x, a)を作用させる ( 0-indexed ) ( O(logN) )
"""
if l >= r:
return
l += self.size
r += self.size
l0 = l//(l&-l)
r0 = r//(r&-r)
self.propagate_lazy(l0)
self.propagate_lazy(r0-1)
while l < r:
if r&1:
r -= 1 # 半開区間なので先に引いてる
self.lazy[r] = self.h(x, self.lazy[r])
if l&1:
self.lazy[l] = self.h(x, self.lazy[l])
l += 1
l >>= 1
r >>= 1
self.propagate_tree(l0)
self.propagate_tree(r0-1)
def get_range(self, l, r):
"""
[l, r)への作用の結果を返す (0-indexed)
"""
l += self.size
r += self.size
self.propagate_lazy(l//(l&-l))
self.propagate_lazy((r//(r&-r))-1)
res_l = self.ef
res_r = self.ef
while l < r:
if l & 1:
res_l = self.f(res_l, self.g(self.lazy[l], self.tree[l]))
l += 1
if r & 1:
r -= 1
res_r = self.f(self.g(self.lazy[r], self.tree[r]), res_r)
l >>= 1
r >>= 1
return self.f(res_l, res_r)
def max_right(self, l, z):
"""
以下の条件を両方満たす r を(いずれか一つ)返す
・r = l or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・r = n or f(op(a[l], a[l + 1], ..., a[r])) = false
"""
if l >= self.n: return self.n
l += self.size
s = self.ef
while 1:
while l % 2 == 0:
l >>= 1
if not z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
while l < self.size:
l *= 2
if z(self.f(s, self.g(self.lazy[l], self.tree[l]))):
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
return l - self.size
s = self.f(s, self.g(self.lazy[l], self.tree[l]))
l += 1
if l & -l == l: break
return self.n
def min_left(self, r, z):
"""
以下の条件を両方満たす l を(いずれか一つ)返す
・l = r or f(op(a[l], a[l + 1], ..., a[r - 1])) = true
・l = 0 or f(op(a[l - 1], a[l], ..., a[r - 1])) = false
"""
if r <= 0: return 0
r += self.size
s = self.ef
while 1:
r -= 1
while r > 1 and r % 2:
r >>= 1
if not z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
while r < self.size:
r = r * 2 + 1
if z(self.f(self.g(self.lazy[r], self.tree[r]), s)):
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
r -= 1
return r + 1 - self.size
s = self.f(self.g(self.lazy[r], self.tree[r]), s)
if r & -r == r: break
return 0
def propagate_lazy(self, i):
"""
lazy の値をトップダウンで更新する ( O(logN) )
"""
for k in range(i.bit_length()-1,0,-1):
x = i>>k
if self.lazy[x] == self.eh:
continue
laz = self.lazy[x]
self.lazy[(x<<1)|1] = self.h(laz, self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(laz, self.lazy[x<<1])
self.tree[x] = self.g(laz, self.tree[x]) # get_range ではボトムアップの伝搬を行わないため、この処理をしないと tree が更新されない
self.lazy[x] = self.eh
def propagate_tree(self, i):
"""
tree の値をボトムアップで更新する ( O(logN) )
"""
while i>1:
i>>=1
self.tree[i] = self.f(self.g(self.lazy[i<<1], self.tree[i<<1]), self.g(self.lazy[(i<<1)|1], self.tree[(i<<1)|1]))
def __getitem__(self, i):
return self.get(i)
def __iter__(self):
for x in range(1, self.size):
if self.lazy[x] == self.eh:
continue
self.lazy[(x<<1)|1] = self.h(self.lazy[x], self.lazy[(x<<1)|1])
self.lazy[x<<1] = self.h(self.lazy[x], self.lazy[x<<1])
self.tree[x] = self.g(self.lazy[x], self.tree[x])
self.lazy[x] = self.eh
for xh, x in zip(self.lazy[self.size:self.size+self.n], self.tree[self.size:self.size+self.n]):
yield self.g(xh,x)
def __str__(self):
return str(list(self))
##################################################################################################################
N, Q = map(int, input().split())
A = list(map(int, input().split()))
ef = 0
eh = 0
f = lambda x, y : x if x > y else y
g = lambda x, y : x if x > y else y
h = lambda x, y : x if x > y else y
st = LazySegmentTree(N, f, g, h, ef, eh)
st.built(A)
res = []
for _ in range(Q):
t, x, y = map(int, input().split())
if t == 1:
st.update(x - 1, y)
elif t == 2:
res.append(st.get_range(x - 1, y))
else:
res.append(st.max_right(x - 1, lambda z: z < y) + 1)
print('\n'.join(map(str, res)))
```
Yes
| 9,660 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
# セグ木ソラ書き練習
# 10分くらい
# query()でバグらせたので反省
import sys
input = lambda: sys.stdin.readline().rstrip()
class SegmentTree:
def __init__(self,n,p,unit,f):
self.num=2**((n-1).bit_length())
self.seg=[unit]*(self.num*2)
for i in range(n):
self.seg[self.num+i]=p[i]
for i in range(self.num-1,0,-1):
self.seg[i]=f(self.seg[i<<1],self.seg[(i<<1)+1])
self.unit=unit
self.f=f
def update(self,i,x):
i+=self.num
self.seg[i]=x
while i:
i>>=1
self.seg[i]=self.f(self.seg[i<<1],self.seg[(i<<1)+1])
def query(self,l,r):
ansl=ansr=self.unit
l+=self.num
r+=self.num-1
if l==r:
return self.seg[l]
while l<r:
if l&1:
ansl=self.f(ansl,self.seg[l])
l+=1
if ~r&1:
ansr=self.f(self.seg[r],ansr)
r-=1
l>>=1
r>>=1
if l==r:
ansl=self.f(ansl,self.seg[l])
return self.f(ansl,ansr)
n,q=map(int,input().split())
a=list(map(int,input().split()))
f=lambda x,y: max(x,y)
seg=SegmentTree(n,a,0,f)
for _ in range(q):
t,a,b=map(int,input().split())
if t==1:
seg.update(a-1,b)
if t==2:
print(seg.query(a-1,b))
if t==3:
ng=a-1
ok=n+1
while ng+1!=ok:
mid=(ng+ok)//2
if seg.query(ng,mid)>=b:ok=mid
else:ng=mid
print(ok)
```
Yes
| 9,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
# Date [ 2020-09-08 00:35:49 ]
# Problem [ j.py ]
# Author Koki_tkg
import sys
# import math
# import bisect
# import numpy as np
# from decimal import Decimal
# from numba import njit, i8, u1, b1 #JIT compiler
# from itertools import combinations, product
# from collections import Counter, deque, defaultdict
# sys.setrecursionlimit(10 ** 6)
MOD = 10 ** 9 + 7
INF = 10 ** 9
PI = 3.14159265358979323846
def read_str(): return sys.stdin.readline().strip()
def read_int(): return int(sys.stdin.readline().strip())
def read_ints(): return map(int, sys.stdin.readline().strip().split())
def read_ints2(x): return map(lambda num: int(num) - x, sys.stdin.readline().strip().split())
def read_str_list(): return list(sys.stdin.readline().strip().split())
def read_int_list(): return list(map(int, sys.stdin.readline().strip().split()))
def GCD(a: int, b: int) -> int: return b if a%b==0 else GCD(b, a%b)
def LCM(a: int, b: int) -> int: return (a * b) // GCD(a, b)
class SegmentTree:
def __init__(self, array, function, identify):
self.length = len(array)
self.func, self.ide_ele = function, identify
self.size = 1 << (self.length-1).bit_length()
self.data = [self.ide_ele] * 2*self.size
# set
for i in range(self.length):
self.data[self.size + i] = array[i]
# build
for i in range(self.size-1, 0, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i + 1])
def update(self, idx, x):
idx += self.size
self.data[idx] = x
while idx > 0:
idx >>= 1
self.data[idx] = self.func(self.data[2*idx], self.data[2*idx + 1])
def query(self, l, r):
l += self.size; r += self.size+1
l_ret = r_ret = self.ide_ele
while l < r:
if l & 1:
l_ret = self.func(l_ret, self.data[l])
l += 1
if r & 1:
r -= 1
r_ret = self.func(self.data[r], r_ret)
l >>= 1; r >>= 1
return self.func(l_ret, r_ret)
def get(self, idx):
return self.data[idx+self.size]
def Main():
n, q = read_ints()
a = read_int_list()
seg = SegmentTree(a, max, -float('inf'))
for _ in range(q):
t, x, v = read_ints()
if t == 1:
seg.update(~-x, v)
elif t == 2:
print(seg.query(x, v))
else:
l = x; r = n + 1
while r - l > 1:
mid = (l + r) // 2
if seg.query(x, mid) >= v:
r = mid
else:
l = mid
print(r)
if __name__ == '__main__':
Main()
```
No
| 9,662 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
mycode = r'''
# distutils: language=c++
# cython: language_level=3, boundscheck=False, wraparound=False, cdivision=True
ctypedef long long LL
# cython: cdivision=True
from libc.stdio cimport scanf
from libcpp.vector cimport vector
ctypedef vector[LL] vec
cdef class SegmentTree():
cdef LL num,n
cdef vec tree
def __init__(self,vec A):
cdef LL n,i
n = A.size()
self.n = n
self.num = 1 << (n-1).bit_length()
self.tree = vec(2*self.num,0)
for i in range(n):
self.tree[self.num + i] = A[i]
for i in range(self.num-1,0,-1):
self.tree[i] = max(self.tree[2*i],self.tree[2*i+1])
cdef void update(self,LL k,LL x):
k += self.num
self.tree[k] = x
while k>1:
self.tree[k>>1] = max(self.tree[k],self.tree[k^1])
k >>= 1
cdef LL query(self,LL l,LL r):
cdef LL res
res = 0
l += self.num
r += self.num
while l<r:
if l&1:
res = max(res,self.tree[l])
l += 1
if r&1:
res = max(res,self.tree[r-1])
l >>= 1
r >>= 1
return res
cdef LL bisect_l(self,LL l,LL r,LL x):
cdef LL Lmin,Rmin,pos
l += self.num
r += self.num
Lmin = -1
Rmin = -1
while l<r:
if l&1:
if self.tree[l] >= x and Lmin == -1:
Lmin = l
l += 1
if r&1:
if self.tree[r] >= x:
Rmin = r
l >>= 1
r >>= 1
if Lmin!=-1:
pos = Lmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
elif Rmin!=-1:
pos = Rmin
while pos<self.num:
if self.tree[2*pos] >= x:
pos = 2*pos
else:
pos = 2*pos + 1
return pos-self.num
else:
return self.n
cdef LL N,Q,i
cdef vec A
scanf("%lld %lld",&N,&Q)
A = vec(N,-1)
for i in range(N):
scanf("%lld",&A[i])
cdef SegmentTree S = SegmentTree(A)
cdef LL t,x,v
for i in range(Q):
scanf("%lld %lld %lld",&t,&x,&v)
if t==1:
S.update(x-1,v)
elif t==2:
print(S.query(x-1,v))
else:
print(S.bisect_l(x-1,N,v)+1)
'''
import sys
import os
if sys.argv[-1] == 'ONLINE_JUDGE': # コンパイル時
with open('mycode.pyx', 'w') as f:
f.write(mycode)
os.system('cythonize -i -3 -b mycode.pyx')
import mycode
```
No
| 9,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
class SegmentTree: #1-indexed
def __init__(self,list,f=lambda x,y:x+y,inf=0):
self.height=(len(list)-1).bit_length()+1 #木の高さ
self.zero=2**(self.height-1) #最下段に添字を合わせる用
self.id=inf #単位元
self.tree=[self.id]*(2**self.height) #木を単位元で初期化
self.f=f
for i in range(len(list)):
self.tree[self.zero+i]=list[i]
for i in range(self.zero-1,0,-1):
self.tree[i]=self.f(self.tree[2*i],self.tree[2*i+1])
def update(self,i,x): #i番目の要素をxに変更
i+=self.zero
self.tree[i]=x
while i>1:
i//=2
self.tree[i]=self.f(self.tree[2*i],self.tree[2*i+1])
def query(self,l,r):
l+=self.zero
r+=self.zero
lf,rf=self.id,self.id
while l<r:
if l&1:
lf=self.f(lf,self.tree[l])
l+=1
if r&1:
r-=1
rf=self.f(self.tree[r],rf)
l//=2
r//=2
return self.f(lf,rf)
'''
Falseを探索するかTrueを探索するかは問題によって使い分ける(デフォはTrue探索)
FFFFTTTTとしたときの最小のTを求める
'''
def BinarySearch(self,l,r,f): #fの返り値はboolにする
l+=self.zero
r+=self.zero
if not f(self.tree[1]):
return r+1-self.zero
while True:
if f(self.tree[l]):
if l>=self.zero:
return l-self.zero+1 #最下段ならreturn
else:
l*=2 #左の子供を見る
else:
if l%2==0:
l+=1 #左の子なら右を見る
else:
l=(l//2)+1 #右の子なら親の右を見る
#####################################################
n,q=map(int,input().split())
a=list(map(int,input().split()))
seg=SegmentTree(a,max)
for i in range(q):
t,x,y=map(int,input().split())
if t==1:
seg.update(x-1,y)
elif t==2:
print(seg.query(x-1,y-1))
else:
print(seg.BinarySearch(x-1,n,lambda x:x>=y))
```
No
| 9,664 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an array a_0, a_1, ..., a_{N-1} of length N. Process Q queries of the following types.
The type of i-th query is represented by T_i.
* T_i=1: You are given two integers X_i,V_i. Replace the value of A_{X_i} with V_i.
* T_i=2: You are given two integers L_i,R_i. Calculate the maximum value among A_{L_i},A_{L_i+1},\cdots,A_{R_i}.
* T_i=3: You are given two integers X_i,V_i. Calculate the minimum j such that X_i \leq j \leq N, V_i \leq A_j. If there is no such j, answer j=N+1 instead.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 0 \leq A_i \leq 10^9
* 1 \leq Q \leq 2 \times 10^5
* 1 \leq T_i \leq 3
* 1 \leq X_i \leq N, 0 \leq V_i \leq 10^9 (T_i=1,3)
* 1 \leq L_i \leq R_i \leq N (T_i=2)
* All values in Input are integer.
Input
Input is given from Standard Input in the following format:
N Q
A_1 A_2 \cdots A_N
First query
Second query
\vdots
Q-th query
Each query is given in the following format:
If T_i=1,3,
T_i X_i V_i
If T_i=2,
T_i L_i R_i
Output
For each query with T_i=2, 3, print the answer.
Example
Input
5 5
1 2 3 2 1
2 1 5
3 2 3
1 3 1
2 2 4
3 1 3
Output
3
3
2
6
Submitted Solution:
```
import sys
sys.setrecursionlimit(10 ** 8)
input = sys.stdin.readline
def main():
N, Q = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
def segfunc(x, y):
return max(x, y)
def init(init_val):
for i in range(n):
seg[i + num - 1] = init_val[i]
for i in range(num - 2, -1, -1):
seg[i] = segfunc(seg[2 * i + 1], seg[2 * i + 2])
def update(k, x):
k += num - 1
seg[k] = x
while k:
k = (k - 1) // 2
seg[k] = segfunc(seg[k * 2 + 1], seg[k * 2 + 2])
def query(p, q):
if q <= p:
return ide_ele
p += num - 1
q += num - 2
res = ide_ele
while q - p > 1:
if p & 1 == 0:
res = segfunc(res, seg[p])
if q & 1 == 1:
res = segfunc(res, seg[q])
q -= 1
p = p // 2
q = (q - 1) // 2
if p == q:
res = segfunc(res, seg[p])
else:
res = segfunc(segfunc(res, seg[p]), seg[q])
return res
# seg tree初期値 (単位元)
n = N
ide_ele = 0
num = 2 ** (n - 1).bit_length()
seg = [ide_ele] * 2 * num
init(A)
def isOK(mid, m, value):
a = query(m, mid)
return a <= value
B = A[::]
for _ in range(Q):
T, X, V = [int(x) for x in input().split()]
if T == 1:
update(X - 1, V)
B[X - 1] = V
elif T == 2:
print(query(X - 1, V - 1))
else:
a = query(X - 1, N - 1)
if a < V:
print(N + 1)
else:
if B[X - 1] >= V:
print(X)
continue
ok = N - 1
ng = X - 1
while abs(ok - ng) > 1:
mid = (ok + ng) // 2
if isOK(mid, X - 1, V):
ok = mid
else:
ng = mid
print(ok + 1)
if __name__ == '__main__':
main()
```
No
| 9,665 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
def f_lis_on_tree(INF=float('inf')):
# 参考: https://note.com/tanon_cp/n/n51ee6db8f5b2
import sys
sys.setrecursionlimit(10**7)
import bisect
N = int(input())
A = [0] + [int(i) for i in input().split()] # 以下、1-origin で考える
Edges = [[int(i) for i in input().split()] for j in range(N - 1)]
graph = [[] for _ in range(N + 1)]
for a, b in Edges:
graph[a].append(b)
graph[b].append(a)
ans = [0] * (N + 1)
visited = [False] * (N + 1)
visited[1] = True # 根は訪問済
lis = [INF] * (N + 1)
changes = []
def dfs(v):
# 行きがけの処理
# LIS の更新する場所を二分探索で求める
pos = bisect.bisect_left(lis, A[v])
changes.append((pos, lis[pos])) # 更新した要素とその値を記録しておく
lis[pos] = A[v]
ans[v] = bisect.bisect_left(lis, INF) # INF が現れるまでの要素数が v での解
# 次の頂点へ
for child in graph[v]:
if not visited[child]:
visited[child] = True
dfs(child)
# 帰りがけの処理 (頂点 v で更新した LIS の値を復元)
pos, val = changes.pop()
lis[pos] = val
dfs(1)
return ' '.join(map(str, ans[1:]))
print(f_lis_on_tree())
```
| 9,666 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
from bisect import bisect_left
import sys
sys.setrecursionlimit(10**6)
n=int(input())
a=list(map(int,input().split()))
g = [[]for _ in range(n)]
for i in range(n-1):
u,v=map(int,input().split())
g[u-1].append(v-1)
g[v-1].append(u-1)
lis = [float('inf')]*n
ans = [0]*n
def dfs(now, pre):
idx = bisect_left(lis, a[now])
tmp = lis[idx]
lis[idx] = a[now]
ans[now] = bisect_left(lis, float('inf'))
for to in g[now]:
if to == pre:
continue
dfs(to, now)
lis[idx] = tmp
dfs(0,-1)
for x in ans:
print(x)
```
| 9,667 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
from collections import deque
from bisect import bisect_left
import sys
sys.setrecursionlimit(10**7)
n=int(input())
a=list(map(int,input().split()))
edge=[[] for _ in range(n)]
for _ in range(n-1):
u,v=map(int,input().split())
u-=1
v-=1
edge[u].append(v)
edge[v].append(u)
stack=deque([])
inf=10**18
lis=[inf]*(n+1)
ans=[0 for _ in range(n)]
visited=[True]*n
#print(edge)
def dfs(s):
visited[s]=False
idx=bisect_left(lis,a[s])
stack.append((idx,lis[idx]))
lis[idx]=a[s]
ans[s]=bisect_left(lis,inf)
for x in edge[s]:
if visited[x]:
dfs(x)
idx,val=stack.pop()
lis[idx]=val
dfs(0)
#print(lis)
for i in range(n):
print(ans[i])
```
| 9,668 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
'''
自宅用PCでの解答
'''
import math
#import numpy as np
import itertools
import queue
import bisect
from collections import deque,defaultdict
import heapq as hpq
from sys import stdin,setrecursionlimit
#from scipy.sparse.csgraph import dijkstra
#from scipy.sparse import csr_matrix
ipt = stdin.readline
setrecursionlimit(10**7)
def main():
n = int(ipt())
# n = 2*10**5
a = [int(i) for i in ipt().split()]
# a = [i+1 for i in range(n)]
way = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,ipt().split())
u -= 1;v -= 1
way[u].append(v)
way[v].append(u)
# way = [[i-1,i+1] for i in range(n)]
# way[0] = [1]
# way[n-1] = [n-2]
ans = [0]*n
dp = [10**18]*n
stk = []
def solve(ni,pi):
ai = a[ni]
pt = bisect.bisect_left(dp,ai)
stk.append((pt,dp[pt]))
dp[pt] = ai
ans[ni] = bisect.bisect_left(dp,10**18-1)
for i in way[ni]:
if i == pi:
continue
else:
solve(i,ni)
pl,val = stk.pop()
dp[pl] = val
return None
solve(0,-1)
for i in ans:
print(i)
return None
if __name__ == '__main__':
main()
```
| 9,669 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
sys.setrecursionlimit(10 ** 7)
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
from collections import deque, defaultdict
from itertools import combinations, permutations
from itertools import accumulate
from math import ceil, sqrt, pi
def LLL(a, ls):
INF = 10 ** 15
flag = 0
prev = 0
indx = 0
ls_i = bisect_left(ls, a)
if a < ls[ls_i]:
flag = 1
prev = ls[ls_i]
indx = ls_i
ls[ls_i] = min(ls[ls_i], a)
ls_ii = bisect_left(ls, INF)
return ls_ii, ls, flag, prev, indx
MOD = 10 ** 9 + 7
INF = 10 ** 18
N = int(input())
A = [0] + list(map(int, input().split()))
UV = [list(map(int, input().split())) for _ in range(N - 1)]
graph = [[] for _ in range(N + 1)]
for uv in UV:
u, v = uv
graph[u].append(v)
graph[v].append(u)
#print(graph)
INF = 10 ** 15
LIS = [INF for i in range(N + 2)]
answer = [0] * (N + 1)
def dfs(prev, n, LIS):
answer[n], LIS, flag, prv, indx = LLL(A[n], LIS)
#print(n, LIS, flag, prv, indx)
for g in graph[n]:
if g != prev:
dfs(n, g, LIS)
if flag:
LIS[indx] = prv
dfs(-1, 1, LIS)
for a in answer[1:]:
print(a)
```
| 9,670 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
import bisect
import sys
N = int(input())
a = list(map(int, input().split()))
to = [[] for _ in range(N)]
for _ in range(N - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
to[u].append(v)
to[v].append(u)
del u, v
def dfs(v):
if len(dp) == 0 or a[v] > dp[-1]:
dp.append(a[v])
pos = -1
else:
pos = bisect.bisect_left(dp, a[v])
back = dp[pos]
dp[pos] = a[v]
ans[v] = len(dp)
for u in to[v]:
if ans[u] == -1:
dfs(u)
if pos == -1:
dp.pop()
else:
dp[pos] = back
ans = [-1] * N
sys.setrecursionlimit(10 ** 6)
dp = []
dfs(0)
for an in ans:
print(an)
```
| 9,671 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**7)
input = sys.stdin.buffer.readline
from bisect import bisect_left
n=int(input())
*a,=map(int,input().split())
dp=[float("inf")]*n
con=[[] for _ in range(n)]
for _ in range(n-1):
s,t=map(int,input().split())
con[s-1].append(t-1)
con[t-1].append(s-1)
ans=[0]*n
def dfs(cur,pre):
idx=bisect_left(dp,a[cur])
bef=dp[idx]
dp[idx]=min(bef,a[cur])
ans[cur]=bisect_left(dp,float("inf"))
for nxt in con[cur]:
if pre!=nxt:
dfs(nxt,cur)
dp[idx]=bef
dfs(0,-1)
print("\n".join(map(str,ans)))
```
| 9,672 |
Provide a correct Python 3 solution for this coding contest problem.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
"Correct Solution:
```
import sys
from bisect import bisect_left
def main():
sys.setrecursionlimit(202020)
N = int(input())
A = [0] + list(map(int, input().split()))
G = [[] for _ in range(N+1)]
for _ in range(N-1):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
L = [A[1]]
Ans = [0] * (N+1)
def dfs(v):
Ans[v] = len(L)
for u in G[v]:
G[u].remove(v)
Au = A[u]
if Au > L[-1]:
L.append(Au)
dfs(u)
del L[-1]
else:
idx = bisect_left(L, Au)
old = L[idx]
L[idx] = Au
dfs(u)
L[idx] = old
dfs(1)
print("\n".join(map(str, Ans[1:])))
main()
```
| 9,673 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
import sys
sys.setrecursionlimit(200000)
from collections import deque
from bisect import bisect_left
N = int(input())
A = list(map(int, input().split()))
adj = [[] for i in range(N)]
for i in range(N - 1):
u, v = map(int, input().split())
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
INF = 10 ** 10
done = [False] * N
done[0] = True
lisdp = [INF] * N
lisdp[0] = A[0]
change = [[-1, INF] for i in range(N)] #index, original
change[0] = [0, INF]
lisl = [0] * N
lisl[0] = 1
def dfs(v):
for nv in adj[v]:
if done[nv]:
continue
done[nv] = True
ind = bisect_left(lisdp, A[nv])
ori = lisdp[ind]
change[nv] = [ind, ori]
if ori == INF:
lisl[nv] = lisl[v] + 1
else:
lisl[nv] = lisl[v]
lisdp[ind] = A[nv]
dfs(nv)
lisdp[change[v][0]] = change[v][1]
dfs(0)
for i in range(N):
print(lisl[i])
```
Yes
| 9,674 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
import bisect
import sys
sys.setrecursionlimit(10**8)
n = int(input())
A = list(map(int, input().split()))
edges = [[] for _ in range(n)]
for _ in range(n-1):
from_, to = map(int, input().split())
edges[from_-1].append(to-1)
edges[to-1].append(from_-1)
DP = [10**9+7] * (n+1)
DP[0] = 0
ans = [0] * n
def dfs(node):
node = node
num = A[node]
update_idx = bisect.bisect_left(DP, num)
prev = DP[update_idx]
DP[update_idx] = num
lis = bisect.bisect_left(DP, 10**9+1) - 1
ans[node] = lis
for nex in edges[node]:
if not ans[nex]:
dfs(nex)
DP[update_idx] = prev
dfs(0)
for res in ans:
print(res)
```
Yes
| 9,675 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
from sys import stdin
import sys
import math
from functools import reduce
import functools
import itertools
from collections import deque,Counter
from operator import mul
import copy
# ! /usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
sys.setrecursionlimit(10**6)
INF = float("inf")
import bisect
## a, bを無向辺として,隣接リストを作成
N = int(input())
a = [0] + list(map(int, input().split()))
al = [[] for i in range(N+1)]
for i in range(N-1):
c, d = list(map(int, input().split()))
al[c].append(d)
al[d].append(c)
visited = [0 for i in range(N+1)]
LIS = [a[1]]
ans = [0 for i in range(N+1)]
ans[1] = 1
def dfs_rec(u):
x = a[u]
if x > LIS[-1]:
pre_idx = len(LIS)
pre_v = INF
LIS.append(x)
else:
pre_idx = bisect.bisect_left(LIS, x)
pre_v = LIS[pre_idx]
LIS[bisect.bisect_left(LIS, x)] = x
ans[u] = len(LIS)
visited[u] = 1
for v in al[u]:
if visited[v] == 0:
dfs_rec(v)
if pre_v == INF:
LIS.pop()
else:
LIS[pre_idx] = pre_v
dfs_rec(1)
for i in range(1,N+1):
print(ans[i])
```
Yes
| 9,676 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
import sys,bisect
input = sys.stdin.readline
n = int(input())
a = list(map(int,input().split()))
ans = [1]*n
edge = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
edge[u-1].append(v-1)
edge[v-1].append(u-1)
root = 0
chi = [[] for i in range(n)]
par = [-1]*n
used = [False]*n
tank = [0]
while tank:
q = tank.pop()
used[q] = True
for e in edge[q]:
if not used[e]:
chi[q].append(e)
tank.append(e)
par[e] = q
tank = [root]
idx = dict()
val = dict()
dp = [10**10]*n
eulerNum = -1
while tank:
q = tank.pop()
if q >= 0:
#first time
num = a[q]
kk = bisect.bisect_left(dp,num)
val[q] = dp[kk]
idx[q] = kk
dp[kk] = num
ans[q] = bisect.bisect_left(dp,10**10)
eulerNum += 1
tank.append(~q)
for ch in chi[q]:
tank.append(ch)
else:
if ~q != root:
if dp[idx[~q]] == a[~q]:
dp[idx[~q]] = val[~q]
eulerNum += 1
print(*ans,sep = "\n")
```
Yes
| 9,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
import sys
import math
from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN
from collections import deque
def I(): return int(sys.stdin.readline())
def MI(): return map(int, sys.stdin.readline().split())
def LI(): return list(map(int, sys.stdin.readline().split()))
def LI2(N): return [list(map(int, sys.stdin.readline().split())) for i in range(N)]
def S(): return sys.stdin.readline().rstrip()
def LS(): return sys.stdin.readline().split()
def LS2(N): return [sys.stdin.readline().split() for i in range(N)]
def FILL(i,h): return [i for j in range(h)]
def FILL2(i,h,w): return [FILL(i,w) for j in range(h)]
def FILL3(i,h,w,d): return [FILL2(i,w,d) for j in range(h)]
def FILL4(i,h,w,d,d2): return [FILL3(i,w,d,d2) for j in range(h)]
def sisha(num,digit): return Decimal(str(num)).quantize(Decimal(digit),rounding=ROUND_HALF_UP)
#'0.01'や'1E1'などで指定、整数に戻すならintをかます
MOD = 10000000007
INF = float("inf")
sys.setrecursionlimit(10**5+10)
#input = sys.stdin.readline
from bisect import bisect_left
def dfs(i,before):
global seq
global ans
added = 0
#現在地のAの値を、以前までのseqリストのどこに追加するか決める
pos = bisect_left(seq,a[i-1])
old = seq[pos]
seq[pos]=a[i-1]
ans[i-1]=bisect_left(seq,INF)
#隣接する頂点に関して再帰
for u in to[i]:
if u==before:
continue
dfs(u,i)
#seq配列をもとに戻す
seq[pos]=old
N = I()
a = LI()
to = [[] for i in range(N+1)]
to[0] += [1]
for i in range(N-1):
u,v = MI()
to[u].append(v)
to[v].append(u)
seq = [INF]*N
ans = [-1]*N
dfs(1,-1)
[print(i) for i in ans]
```
No
| 9,678 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
from collections import deque
n = int(input())
a = list(map(int, input().split()))
uv = [[] for _ in range(n)]
for i in range(n-1):
u,v = list(map(int, input().split()))
u -= 1
v -= 1
uv[u].append(v)
uv[v].append(u)
ans = [0] * n
que = deque([0])
ans[0] = 1
def dfs(x):
global ans
if ans.count(0) == 0:
return
ansx = ans[x]
ax = a[x]
for i in uv[x]:
if ans[i] == 0:
if ax < a[i]:
ans[i] = ansx + 1
else:
ans[i] = ansx
que.append(i)
while que:
nx = que.popleft()
dfs(nx)
dfs(0)
for i in range(n):
print(ans[i])
```
No
| 9,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
import bisect
import copy
import heapq
import math
import sys
from collections import *
from itertools import accumulate, combinations, permutations, product
from math import gcd
def input():
return sys.stdin.readline()[:-1]
def ruiseki(lst):
return [0]+list(accumulate(lst))
mod=pow(10,9)+7
al=[chr(ord('a') + i) for i in range(26)]
direction=[[1,0],[0,1],[-1,0],[0,-1]]
n=int(input())
a=list(map(int,input().split()))
uv=[list(map(int,input().split())) for i in range(n-1)]
edge=defaultdict(list)
for i in range(n-1):
u,v=uv[i]
edge[u].append(v)
edge[v].append(u)
# print(edge)
itta=[0]*(n+1)
# lislist=[0]*(n+1)
def dfs(now,lis):
stk=0
if a[now-1]>lis[-1]:
lis.append(a[now-1])
stk="pop"
else:
tmp=bisect.bisect_left(lis, a[now-1])
stk=[tmp,lis[tmp]]
lis[tmp]=a[now-1]
# print(now,lis)
itta[now]=len(lis)
for i in edge[now]:
if itta[i]==0:
dfs(i,lis)
if stk=="pop":
lis.pop()
else:
lis[stk[0]]=stk[1]
dfs(1,[float('inf')])
# print(itta)
for i in range(n):
print(itta[i+1])
```
No
| 9,680 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a tree with N vertices, whose i-th edge connects Vertex u_i and Vertex v_i. Vertex i has an integer a_i written on it. For every integer k from 1 through N, solve the following problem:
* We will make a sequence by lining up the integers written on the vertices along the shortest path from Vertex 1 to Vertex k, in the order they appear. Find the length of the longest increasing subsequence of this sequence.
Here, the longest increasing subsequence of a sequence A of length L is the subsequence A_{i_1} , A_{i_2} , ... , A_{i_M} with the greatest possible value of M such that 1 \leq i_1 < i_2 < ... < i_M \leq L and A_{i_1} < A_{i_2} < ... < A_{i_M}.
Constraints
* 2 \leq N \leq 2 \times 10^5
* 1 \leq a_i \leq 10^9
* 1 \leq u_i , v_i \leq N
* u_i \neq v_i
* The given graph is a tree.
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
a_1 a_2 ... a_N
u_1 v_1
u_2 v_2
:
u_{N-1} v_{N-1}
Output
Print N lines. The k-th line, print the length of the longest increasing subsequence of the sequence obtained from the shortest path from Vertex 1 to Vertex k.
Example
Input
10
1 2 5 3 4 6 7 3 2 4
1 2
2 3
3 4
4 5
3 6
6 7
1 8
8 9
9 10
Output
1
2
3
3
4
4
5
2
2
3
Submitted Solution:
```
from bisect import bisect
N = int(input())
a = list(map(int,input().split()))
g = [[] for _ in range(N)]
for i in range(N-1):
u,v = map(int,input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
ans = [0]*N
def dfs(t,f,l,seq):
l = l.copy()
seq = seq.copy()
l.append(a[t])
i = bisect(seq,l[-1])
if len(seq)==i:
seq.append(l[-1])
else:
seq[i]=l[-1]
ans[t] = len(seq)
for v in g[t]:
if v != f:
dfs(v,t,l,seq)
dfs(0,0,[],[])
for i in range(N):
print(ans[i])
```
No
| 9,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i).
pic1-small-2acea94b.png
Each balancer must be in one of two states: up or down.
Consider a token that starts moving to the right along some wire at a point to the left of all balancers. During the process, the token passes through each balancer exactly once. Whenever the token encounters balancer i, the following happens:
* If the token is moving along wire x_i and balancer i is in the down state, the token moves down to wire y_i and continues moving to the right.
* If the token is moving along wire y_i and balancer i is in the up state, the token moves up to wire x_i and continues moving to the right.
* Otherwise, the token doesn't change the wire it's moving along.
Let a state of the balancing network be a string of length M, describing the states of all balancers. The i-th character is `^` if balancer i is in the up state, and `v` if balancer i is in the down state.
A state of the balancing network is called uniforming if a wire w exists such that, regardless of the starting wire, the token will always end up at wire w and run to infinity along it. Any other state is called non-uniforming.
You are given an integer T (1 \le T \le 2). Answer the following question:
* If T = 1, find any uniforming state of the network or determine that it doesn't exist.
* If T = 2, find any non-uniforming state of the network or determine that it doesn't exist.
Note that if you answer just one kind of questions correctly, you can get partial score.
Constraints
* 2 \leq N \leq 50000
* 1 \leq M \leq 100000
* 1 \leq T \leq 2
* 1 \leq x_i < y_i \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M T
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print any uniforming state of the given network if T = 1, or any non-uniforming state if T = 2. If the required state doesn't exist, output `-1`.
Examples
Input
4 5 1
1 3
2 4
1 2
3 4
2 3
Output
^^^^^
Input
4 5 2
1 3
2 4
1 2
3 4
2 3
Output
v^^^^
Input
3 1 1
1 2
Output
-1
Input
2 1 2
1 2
Output
-1
Submitted Solution:
```
N,M,T = map(int, input().split())
L = [[int(l) for l in input().split()] for _ in range(M)]
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
def find_root(self, x):
if self.root[x] < 0:
return x
else:
self.root[x] = self.find_root(self.root[x])
return self.root[x]
def unite(self, x, y):
x = self.find_root(x)
y = self.find_root(y)
if x == y:
return
elif self.rnk[x] > self.rnk[y]:
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if self.rnk[x] == self.rnk[y]:
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.find_root(x) == self.find_root(y)
def count(self, x):
return -self.root[self.find_root(x)]
if T == 1:
uf = UnionFind(N)
S = [-1]*N
for i in range(M):
uf.unite(L[i][0]-1, L[i][1]-1)
ans = 0
for i in range(N):
if uf.isSameGroup(0, i):
continue
ans = -1
break
if ans == 0:
uf2 = UnionFind(N)
X = L[-1][0]-1
ans = [0]*M
for i in range(M-1, -1, -1):
if L[i][0]-1 == X:
ans[i] = "^"
uf2.unite(X, L[i][1]-1)
elif L[i][1]-1 == X:
ans[i] = "v"
uf2.unite(X, L[i][0]-1)
elif uf2.isSameGroup(X, L[i][0]-1):
ans[i] = "^"
uf2.unite(X, L[i][1]-1)
elif uf2.isSameGroup(X, L[i][1]-1):
ans[i] = "v"
uf2.unite(X, L[i][0]-1)
else:
ans[i] = "^"
for i in range(N):
if uf2.isSameGroup(0, i):
continue
ans = -1
break
if ans == -1:
print(-1)
else:
print("".join(ans))
else:
print(ans)
else:
print(-2)
```
No
| 9,682 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i).
pic1-small-2acea94b.png
Each balancer must be in one of two states: up or down.
Consider a token that starts moving to the right along some wire at a point to the left of all balancers. During the process, the token passes through each balancer exactly once. Whenever the token encounters balancer i, the following happens:
* If the token is moving along wire x_i and balancer i is in the down state, the token moves down to wire y_i and continues moving to the right.
* If the token is moving along wire y_i and balancer i is in the up state, the token moves up to wire x_i and continues moving to the right.
* Otherwise, the token doesn't change the wire it's moving along.
Let a state of the balancing network be a string of length M, describing the states of all balancers. The i-th character is `^` if balancer i is in the up state, and `v` if balancer i is in the down state.
A state of the balancing network is called uniforming if a wire w exists such that, regardless of the starting wire, the token will always end up at wire w and run to infinity along it. Any other state is called non-uniforming.
You are given an integer T (1 \le T \le 2). Answer the following question:
* If T = 1, find any uniforming state of the network or determine that it doesn't exist.
* If T = 2, find any non-uniforming state of the network or determine that it doesn't exist.
Note that if you answer just one kind of questions correctly, you can get partial score.
Constraints
* 2 \leq N \leq 50000
* 1 \leq M \leq 100000
* 1 \leq T \leq 2
* 1 \leq x_i < y_i \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M T
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print any uniforming state of the given network if T = 1, or any non-uniforming state if T = 2. If the required state doesn't exist, output `-1`.
Examples
Input
4 5 1
1 3
2 4
1 2
3 4
2 3
Output
^^^^^
Input
4 5 2
1 3
2 4
1 2
3 4
2 3
Output
v^^^^
Input
3 1 1
1 2
Output
-1
Input
2 1 2
1 2
Output
-1
Submitted Solution:
```
N,M,T = map(int, input().split())
L = [[int(l) for l in input().split()] for _ in range(M)]
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
def find_root(self, x):
if self.root[x] < 0:
return x
else:
self.root[x] = self.find_root(self.root[x])
return self.root[x]
def unite(self, x, y):
x = self.find_root(x)
y = self.find_root(y)
if x == y:
return
elif self.rnk[x] > self.rnk[y]:
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if self.rnk[x] == self.rnk[y]:
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.find_root(x) == self.find_root(y)
def count(self, x):
return -self.root[self.find_root(x)]
if T == 1:
uf = UnionFind(N)
for i in range(M):
uf.unite(L[i][0]-1, L[i][1]-1)
ans = 0
for i in range(N):
if uf.isSameGroup(0, i):
continue
ans = -1
break
if ans == 0:
uf2 = UnionFind(N)
X = L[-1][0]-1
ans = [0]*M
for i in range(M-1, -1, -1):
if L[i][0]-1 == X:
ans[i] = "^"
uf2.unite(X, L[i][1]-1)
elif L[i][1]-1 == X:
ans[i] = "v"
uf2.unite(X, L[i][0]-1)
elif uf2.isSameGroup(X, L[i][0]-1):
ans[i] = "^"
uf2.unite(X, L[i][1]-1)
elif uf2.isSameGroup(X, L[i][1]-1):
ans[i] = "v"
uf2.unite(X, L[i][0]-1)
else:
ans[i] = "^"
print("".join(ans))
else:
print(ans)
else:
print(-2)
```
No
| 9,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i).
pic1-small-2acea94b.png
Each balancer must be in one of two states: up or down.
Consider a token that starts moving to the right along some wire at a point to the left of all balancers. During the process, the token passes through each balancer exactly once. Whenever the token encounters balancer i, the following happens:
* If the token is moving along wire x_i and balancer i is in the down state, the token moves down to wire y_i and continues moving to the right.
* If the token is moving along wire y_i and balancer i is in the up state, the token moves up to wire x_i and continues moving to the right.
* Otherwise, the token doesn't change the wire it's moving along.
Let a state of the balancing network be a string of length M, describing the states of all balancers. The i-th character is `^` if balancer i is in the up state, and `v` if balancer i is in the down state.
A state of the balancing network is called uniforming if a wire w exists such that, regardless of the starting wire, the token will always end up at wire w and run to infinity along it. Any other state is called non-uniforming.
You are given an integer T (1 \le T \le 2). Answer the following question:
* If T = 1, find any uniforming state of the network or determine that it doesn't exist.
* If T = 2, find any non-uniforming state of the network or determine that it doesn't exist.
Note that if you answer just one kind of questions correctly, you can get partial score.
Constraints
* 2 \leq N \leq 50000
* 1 \leq M \leq 100000
* 1 \leq T \leq 2
* 1 \leq x_i < y_i \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M T
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print any uniforming state of the given network if T = 1, or any non-uniforming state if T = 2. If the required state doesn't exist, output `-1`.
Examples
Input
4 5 1
1 3
2 4
1 2
3 4
2 3
Output
^^^^^
Input
4 5 2
1 3
2 4
1 2
3 4
2 3
Output
v^^^^
Input
3 1 1
1 2
Output
-1
Input
2 1 2
1 2
Output
-1
Submitted Solution:
```
N, M, T = list(map(int,input().split()))
xy = [list(map(int,input().split())) for _ in range(M)]
UP = "^"
DW = "v"
if T == 1:
x = 10 / 0
else:
if N == 2:
print(-1)
L = [""] * M
D = []
for i in range(M):
x, y = xy[i]
if x <= 3 and y <= 3:
D.append([i, x, y])
else:
L[i] = UP
i = 0
while i < len(D):
T = []
n, x, y = D[i]
T.append(n)
j = i + 1
while j < len(D):
n, xx, yy = D[j]
if x == xx and y == yy:
T.append(n)
j += 1
else:
if x == xx:
for k in T:
L[k] = DW
elif y == yy:
for k in T:
L[k] = UP
elif x == yy:
for k in T:
L[k] = DW
elif xx == y:
for k in T:
L[k] = UP
i = j
break
else:
break
for k in T:
L[k] = UP
print("".join(L))
```
No
| 9,684 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A balancing network is an abstract device built up of N wires, thought of as running from left to right, and M balancers that connect pairs of wires. The wires are numbered from 1 to N from top to bottom, and the balancers are numbered from 1 to M from left to right. Balancer i connects wires x_i and y_i (x_i < y_i).
pic1-small-2acea94b.png
Each balancer must be in one of two states: up or down.
Consider a token that starts moving to the right along some wire at a point to the left of all balancers. During the process, the token passes through each balancer exactly once. Whenever the token encounters balancer i, the following happens:
* If the token is moving along wire x_i and balancer i is in the down state, the token moves down to wire y_i and continues moving to the right.
* If the token is moving along wire y_i and balancer i is in the up state, the token moves up to wire x_i and continues moving to the right.
* Otherwise, the token doesn't change the wire it's moving along.
Let a state of the balancing network be a string of length M, describing the states of all balancers. The i-th character is `^` if balancer i is in the up state, and `v` if balancer i is in the down state.
A state of the balancing network is called uniforming if a wire w exists such that, regardless of the starting wire, the token will always end up at wire w and run to infinity along it. Any other state is called non-uniforming.
You are given an integer T (1 \le T \le 2). Answer the following question:
* If T = 1, find any uniforming state of the network or determine that it doesn't exist.
* If T = 2, find any non-uniforming state of the network or determine that it doesn't exist.
Note that if you answer just one kind of questions correctly, you can get partial score.
Constraints
* 2 \leq N \leq 50000
* 1 \leq M \leq 100000
* 1 \leq T \leq 2
* 1 \leq x_i < y_i \leq N
* All input values are integers.
Input
Input is given from Standard Input in the following format:
N M T
x_1 y_1
x_2 y_2
:
x_M y_M
Output
Print any uniforming state of the given network if T = 1, or any non-uniforming state if T = 2. If the required state doesn't exist, output `-1`.
Examples
Input
4 5 1
1 3
2 4
1 2
3 4
2 3
Output
^^^^^
Input
4 5 2
1 3
2 4
1 2
3 4
2 3
Output
v^^^^
Input
3 1 1
1 2
Output
-1
Input
2 1 2
1 2
Output
-1
Submitted Solution:
```
n,m,t = map(int, input().split())
xy = [list(map(int, input().split())) for i in range(m)]
now = [0] + [1] * n
ans = ""
if n == 2:
print(-1)
exit()
for x,y in reversed(xy):
if now[x] >= 2:
ans = "v" + ans
now[x] -= 1
now[y] += 1
else:
ans = "^" + ans
now[x] += 1
now[y] -= 1
print(ans)
```
No
| 9,685 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
import collections
n,k=map(int,input().split())
arr=list(map(int,input().split()))
pos=[[] for _ in range(max(arr)+1)]
for i in range(2*n):
pos[arr[i%n]].append(i)
edge=[[] for _ in range(n)]
cnt=collections.defaultdict(int)
for i in range(n):
s=pos[arr[i]][cnt[arr[i]]]
g=pos[arr[i]][cnt[arr[i]]+1]
edge[s].append((g+1)%n)
edge[s].append((g+1)//n)
cnt[arr[i]]+=1
start=0
loop=0
for _ in range(n):
loop+=edge[start][1]
start=edge[start][0]
if start==0:
break
k%=loop
if k==0:
print('')
else:
k-=1
start=0
loop=0
for _ in range(n):
if loop==k:
break
loop+=edge[start][1]
start=edge[start][0]
s=set()
q=collections.deque()
for i in range(start,n):
if arr[i] not in s:
s.add(arr[i])
q.append(arr[i])
else:
while 1:
tmp=q.pop()
s.discard(tmp)
if tmp==arr[i]:
break
print(*list(q))
```
| 9,686 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
N,K = map(int,input().split())
A = list(map(int,input().split()))
hoge = [[]for i in range(200001)]
for i in range(N):
hoge[A[i]].append(i)
NEXT = [-1]*N
for i in hoge:
for j in range(-len(i),0):
NEXT[i[j]] = i[j+1]
i = 1
p = 0
while i < K:
#print(i,p)
if NEXT[p] <= p:
i += 1
if NEXT[p] == N-1:
i += 1
p = (NEXT[p]+1)%N
if p == 0:
i = ((K-1)//(i-1))*(i-1)+1
while p < N:
if NEXT[p] <= p:
print(A[p],end = " ")
p += 1
else:
p = NEXT[p]+1
print()
```
| 9,687 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
from collections import defaultdict
from bisect import bisect_right
N, K = map(int, input().split())
*A, = map(int, input().split())
dd = defaultdict(list)
for i, j in enumerate(A):
dd[j].append(i)
pos = 0
loop = 1
# l = []
cic = defaultdict(list)
while pos < N:
num = A[pos]
pp = bisect_right(dd[num], pos)
if pp < len(dd[num]):
pos = dd[num][pp]+1
else:
pos = dd[num][0]+1
loop += 1
cic[loop].append(pos)
pos = cic[K%loop][0] if cic[K%loop] else 0
ans = []
while pos < N:
num = A[pos]
pp = bisect_right(dd[num], pos)
if pp < len(dd[num]):
pos = dd[num][pp]+1
else:
ans.append(num)
pos += 1
print(*ans)
```
| 9,688 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
N,K = map(int,input().split())
A = list(map(int,input().split()))
A += A
d = {}
da = {}
for i in range(2*N):
a = A[i]
if a in da:
d[da[a]] = i
da[a] = i
for i in range(N):
if d[i] >= N:
d[i] %= N
s = 0
k = K
while k > 1:
if d[s]<=s:
k -= 1
if d[s] == N-1:
k = K%(K-k+1)
s = (d[s]+1)%N
if k == 0:
print('')
else:
ans = []
while s <= N-1:
if s < d[s]:
s = d[s]+1
else:
ans.append(str(A[s]))
s += 1
print(' '.join(ans))
```
| 9,689 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
from bisect import*
from collections import*
n,k,*a=map(int,open(0).read().split())
b=defaultdict(list)
for i,v in enumerate(a):b[v]+=i,
s=a[0]
i=c=0
while 1:
t=b[s]
m=len(t)
j=bisect(t,i)
c+=j==m
i=t[j%m]+1
if i==n:break
s=a[i]
k%=c+1
s=a[0]
i=c=0
while c<k-1:
t=b[s]
m=len(t)
j=bisect(t,i)
c+=j==m
i=t[j%m]+1
s=a[i]
r=[]
while 1:
t=b[s]
m=len(t)
j=bisect(t,i)
if j==m:
r+=s,
i+=1
else:
i=t[j]+1
if i==n:
break
s=a[i]
print(*r)
```
| 9,690 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
N, K = map(int, input().split())
A = list(map(int, input().split()))
first = [0] * (N+1)
follow_idx = [-1] * (N+1)
d = {}
for i, a in enumerate(A[::-1]):
j = N - 1 - i
if a in d:
idx = d[a][-1]
d[a].append(j)
if first[idx + 1] < 0:
first[j] = first[idx + 1]
follow_idx[j] = follow_idx[idx + 1]
else:
first[j] = -first[idx + 1]
follow_idx[j] = idx + 1
else:
first[j] = a
d[a] = [j]
follow_idx[j] = j + 1
indices = [-1]
s0 = first[0]
if s0 >= 0:
indices.append(0)
else:
s0 = -s0
indices.append(follow_idx[0])
if s0 == 0:
print('')
quit()
d2 = {0:0, s0:1}
for k in range(2, K+1):
idx = d[s0][-1] + 1
s0 = first[idx]
if s0 >= 0:
indices.append(idx)
else:
s0 = -s0
indices.append(follow_idx[idx])
if s0 in d2:
break
d2[s0] = k
if len(indices) < K:
K = d2[s0] + (K - d2[s0]) % (k - d2[s0])
if K == 0:
print('')
quit()
ans = []
idx = indices[K]
while idx < N:
s = first[idx]
if s > 0:
ans.append(s)
idx = follow_idx[idx]
print(*ans)
```
| 9,691 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
import os
import sys
if os.getenv("LOCAL"):
sys.stdin = open("_in.txt", "r")
sys.setrecursionlimit(2147483647)
INF = float("inf")
IINF = 10 ** 18
MOD = 10 ** 9 + 7
N, K = list(map(int, sys.stdin.readline().split()))
A = list(map(int, sys.stdin.readline().split()))
# 次 A[j] が取り除かれるまでの操作回数
counts = [0] * N
D = {}
for i, a in enumerate(A + A):
if a not in D:
D[a] = i
else:
if D[a] < N:
counts[D[a]] = i - D[a]
D[a] = i
circle = counts[0] + 1
i = (counts[0] + 1) % N
while i != 0:
circle += counts[i] + 1
i = (i + counts[i] + 1) % N
rem = N * K % circle
ans = []
i = 0
while rem > 0:
while rem - counts[i] > 0:
rem -= counts[i] + 1
i = (i + counts[i] + 1) % N
if rem:
ans.append(A[i])
rem -= 1
i = (i + 1) % N
if ans:
print(*ans)
# hist = []
# stack = []
# for _ in range(K):
# for a in A:
# if a in stack:
# while a in stack:
# stack.pop()
# else:
# stack.append(a)
#
# hist.append(a)
# print(hist)
# print('', stack)
# print()
```
| 9,692 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
"Correct Solution:
```
n, k = map(int, input().split())
a = list(map(int, input().split()))
b = a + a
to = [-1] * n
num = [-1] * (2 * 10 ** 5 + 1)
for i, x in enumerate(b):
if 0 <= num[x] < n:
to[num[x]] = i + 1
num[x] = i
c, now = 1, 0
check = 0
while now != n:
v = to[now]
if v > n:
c += 1
v -= n
now = v
k %= c
now = 0
while k > 1:
v = to[now]
if v > n:
k -= 1
v -= n
now = v
ans = []
while now < n:
if to[now] < n:
now = to[now]
elif to[now] == n:
break
else:
ans.append(a[now])
now += 1
print(*ans)
```
| 9,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)
N, K = mapint()
As = list(mapint())
double_As = As*2
idx_dic = {}
idx_lis = [N+1]*(2*N)
for i in range(N*2-1, -1, -1):
a = double_As[i]
if a in idx_dic:
idx_lis[i] = idx_dic[a]+1
idx_dic[a] = i
doubling = [[0]*N for _ in range(60)]
accum = [[0]*N for _ in range(60)]
doubling[0] = [i%N for i in idx_lis[:N]]
accum[0] = [a-i for i, a in enumerate(idx_lis[:N])]
for i in range(1, 60):
for j in range(N):
doubling[i][j] = doubling[i-1][doubling[i-1][j]]
accum[i][j] = accum[i-1][j] + accum[i-1][doubling[i-1][j]]
now = 0
cum = 0
cnt = 0
for i in range(59, -1, -1):
if cum + accum[i][now]>N*K:
continue
else:
cum += accum[i][now]
now = doubling[i][now]
ans = []
while cum<N*K:
if cum+accum[0][now]<=N*K:
cum += accum[0][now]
now = doubling[0][now]
else:
ans.append(As[now])
now += 1
cum += 1
print(*ans)
```
Yes
| 9,694 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import *
N, K = map(int, input().split())
A = list(map(int, input().split()))
log_size = 65
#行き先ではなく移動量をダブリングする
dp = [[-1]*N for _ in range(log_size)]
idx = defaultdict(int)
for i in range(2*N):
if A[i%N] in idx and idx[A[i%N]]<N:
dp[0][idx[A[i%N]]] = i+1-idx[A[i%N]]
idx[A[i%N]] = i
for i in range(1, log_size):
for j in range(N):
#値が大きくなりすぎるとTLEする
dp[i][j] = min(10**18, dp[i-1][j]+dp[i-1][(j+dp[i-1][j])%N])
now = 0
NK = N*K
for i in range(log_size-1, -1, -1):
if NK-dp[i][now]>=0:
NK -= dp[i][now]
now = (now+dp[i][now])%N
if NK==0:
print()
exit()
q = deque([])
cnt = defaultdict(int)
for i in range(now, N):
if cnt[A[i]]>0:
while cnt[A[i]]>0:
rem = q.pop()
cnt[rem] -= 1
else:
cnt[A[i]] += 1
q.append(A[i])
print(*q)
```
Yes
| 9,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
from collections import defaultdict
N, K = map(int, readline().split())
A = list(map(int, readline().split()))
c = N * K
b = 0
while 2 ** b < c:
b += 1
doubling = [[0] * N for _ in range(b + 1)]
idx = defaultdict(list)
for i, x in enumerate(A):
idx[x].append(i)
for i in range(1, 200001):
d = idx[i]
l = len(d)
for j in range(l):
cur = d[j]
nx = d[(j + 1) % l]
if nx <= cur:
doubling[0][cur] = N - (cur - nx) + 1
else:
doubling[0][cur] = nx - cur + 1
for i in range(1, b + 1):
for j in range(N):
p = doubling[i - 1][j]
doubling[i][j] = p + doubling[i - 1][(j + p) % N]
cnt = 0
cur = 0
while c - cnt > 200000:
for i in range(b, -1, -1):
if cnt + doubling[i][cur] < c:
cnt += doubling[i][cur]
cur = cnt % N
break
rem = c - cnt
res = []
res_set = set()
while rem > 0:
num = A[cur]
if num in res_set:
while True:
back = res[-1]
res.pop()
res_set.discard(back)
if back == num:
break
else:
res.append(num)
res_set.add(num)
rem -= 1
cur += 1
cur %= N
print(*res)
if __name__ == '__main__':
main()
```
Yes
| 9,696 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
import bisect
N,K=map(int,input().split())
A=list(map(int,input().split()))
dic={}
for i in range(N):
if A[i] not in dic:
dic[A[i]]=[]
dic[A[i]].append(i)
check={}
for ai in dic:
check[ai]=0
check[ai]=max(dic[ai])
front=[-1]
pos=0
visit=set([-1])
while True:
val=A[pos]
if pos>=check[val]:
front.append(pos)
if pos in visit:
break
else:
visit.add(pos)
pos=dic[val][0]+1
if pos==N:
front.append(-1)
break
else:
index=bisect.bisect_right(dic[val],pos)
pos=dic[val][index]+1
if pos==N:
front.append(-1)
break
last=front[-1]
i=front.index(last)
period=len(front)-i-1
const=i
K-=const
K-=1
r=K%period
fff=front[r]
if fff!=-1:
import heapq
que=[]
check={A[i]:0 for i in range(N)}
index=0
flag=True
while N>index:
if A[index]!=A[fff] and flag:
index+=1
elif A[index]==A[fff] and flag:
index+=1
flag=False
else:
if check[A[index]]==0:
heapq.heappush(que,(-index,A[index]))
check[A[index]]=1
index+=1
else:
while True:
test,a=heapq.heappop(que)
check[a]=0
if a==A[index]:
break
check[A[index]]=0
index+=1
que.sort(reverse=True)
que=[que[i][1] for i in range(len(que))]
print(*que)
else:
import heapq
que=[]
check={A[i]:0 for i in range(N)}
index=0
while N>index:
if check[A[index]]==0:
heapq.heappush(que,(-index,A[index]))
check[A[index]]=0
check[A[index]]=1
index+=1
else:
while True:
test,a=heapq.heappop(que)
check[a]=0
if a==A[index]:
break
check[A[index]]=0
index+=1
que.sort(reverse=True)
que=[que[i][1] for i in range(len(que))]
print(*que)
```
Yes
| 9,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
N, K = map(int, input().split())
A = list(map(int, input().split()))
def add(S, A):
for Ai in A:
try:
S = S[:S.index(Ai)]
except ValueError as _:
S.append(Ai)
return S
ok = False
S = []
for i in range(K):
S = add(S, A)
if len(S) == 0:
break
else:
ok = True
print(" ".join(map(str, S)))
if not ok:
for i in range(K%(i+1)):
S = add(S, A)
print(" ".join(map(str, S)))
```
No
| 9,698 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of N \times K integers: X=(X_0,X_1,\cdots,X_{N \times K-1}). Its elements are represented by another sequence of N integers: A=(A_0,A_1,\cdots,A_{N-1}). For each pair i, j (0 \leq i \leq K-1,\ 0 \leq j \leq N-1), X_{i \times N + j}=A_j holds.
Snuke has an integer sequence s, which is initially empty. For each i=0,1,2,\cdots,N \times K-1, in this order, he will perform the following operation:
* If s does not contain X_i: add X_i to the end of s.
* If s does contain X_i: repeatedly delete the element at the end of s until s no longer contains X_i. Note that, in this case, we do not add X_i to the end of s.
Find the elements of s after Snuke finished the operations.
Constraints
* 1 \leq N \leq 2 \times 10^5
* 1 \leq K \leq 10^{12}
* 1 \leq A_i \leq 2 \times 10^5
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N K
A_0 A_1 \cdots A_{N-1}
Output
Print the elements of s after Snuke finished the operations, in order from beginning to end, with spaces in between.
Examples
Input
3 2
1 2 3
Output
2 3
Input
5 10
1 2 3 2 3
Output
3
Input
6 1000000000000
1 1 2 2 3 3
Output
Input
11 97
3 1 4 1 5 9 2 6 5 3 5
Output
9 2 6
Submitted Solution:
```
n,k=map(int,input().split())
A=list(map(int,input().split()))
s=[]
m=k%(n+1)
for i in range(0,m+1):
if s.count(A[i%n])==0:
s.append(A[i%n])
else:
while s.count(A[i%n])!=0:
del s[-1]
for j in range(0,len(s)):
s[j]=str(s[j])
print(" ".join(s))
```
No
| 9,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.